Compare commits

...

4 Commits

Author SHA1 Message Date
8e953cdd7c fmt 2026-06-03 14:05:49 -04:00
a07c004f2d drop notification, reget deps 2026-06-03 14:05:27 -04:00
203591ca05 resetting 2026-06-03 13:54:53 -04:00
61d48d3648 onnx, fix depl issue 2026-06-03 13:35:37 -04:00
27 changed files with 2137 additions and 13683 deletions

1074
bun.lock

File diff suppressed because it is too large Load Diff

10232
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +0,0 @@
packages:
- "web"
- "browser-ext"

View File

@@ -21,7 +21,7 @@ Status legend: [ ] todo, [~] in-progress, [x] done
### Performance Optimization ### Performance Optimization
- [x] 09 — Image Caching & Lazy Loading → `09-image-caching.md` - [x] 09 — Image Caching & Lazy Loading → `09-image-caching.md`
- [x] 10 — Memory Management & Leak Audit → `10-memory-leak-audit.md` - [x] 10 — Memory Management & Leak Audit → `10-memory-leak-audit.md`
- [~] 11 — Background Fetch & Sync Optimization → `11-background-fetch.md` - [x] 11 — Background Fetch & Sync Optimization → `11-background-fetch.md`
- [x] 12 — App Launch Time Optimization → `12-launch-time.md` - [x] 12 — App Launch Time Optimization → `12-launch-time.md`
### Native Features ### Native Features

1
web/.gitignore vendored
View File

@@ -5,6 +5,7 @@ dist
.netlify .netlify
.vinxi .vinxi
app.config.timestamp_*.js app.config.timestamp_*.js
.pi-lens
# Environment # Environment
.env* .env*

File diff suppressed because one or more lines are too long

51
web/.vercelignore Normal file
View File

@@ -0,0 +1,51 @@
# ── ML Model (255MB ONNX model — too large for Vercel, downloaded at runtime) ──
src/server/models/spam-classifier/
# ── Build Artifacts ──
.output/
.nitro/
dist/
# ── Test Files (not needed in production) ──
e2e/
test/
**/*.test.ts
**/*.test.tsx
**/*.spec.ts
**/*.spec.tsx
# ── Development / Config ──
.dockerignore
Dockerfile
docker-compose.yml
docker-compose.yaml
vitest.config.ts
vitest.node.config.ts
playwright.config.ts
drizzle.config.ts
drizzle/
# ── Version Control ──
.git/
.gitignore
.github/
.husky/
# ── Environment (already in .gitignore, being explicit) ──
.env
.env.development
.env.production
.env.local
# ── Editors / OS ──
.idea/
.vscode/
*.swp
*.swo
*~
.DS_Store
Thumbs.db
# ── Pi agent / dev tooling ──
.pi-lens/
.agents/

View File

@@ -15,56 +15,38 @@
"benchmark:spamshield": "tsx src/server/services/spamshield/benchmark.ts" "benchmark:spamshield": "tsx src/server/services/spamshield/benchmark.ts"
}, },
"dependencies": { "dependencies": {
"@libsql/client": "^0.15.0", "@libsql/client": "^0.17.3",
"@sentry/solidstart": "^10.54.0", "@sentry/solidstart": "^10.56.0",
"@solidjs/meta": "^0.29.4",
"@solidjs/router": "^0.15.0", "@solidjs/router": "^0.15.0",
"@solidjs/start": "2.0.0-alpha.2", "@solidjs/start": "2.0.0-alpha.2",
"@solidjs/vite-plugin-nitro-2": "^0.1.0", "@solidjs/vite-plugin-nitro-2": "^0.1.0",
"@stripe/stripe-js": "^9.6.0", "@stripe/stripe-js": "^9.7.0",
"@tailwindcss/vite": "^4.0.0", "@trpc/client": "^11.17.0",
"@trpc/client": "^10.45.2", "@trpc/server": "^11.17.0",
"@trpc/server": "^10.45.2", "@typeschema/valibot": "^0.14.0",
"@types/three": "^0.184.1",
"@typeschema/valibot": "^0.13.4",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"bullmq": "^5.77.3",
"clerk-solidjs": "^2.0.10", "clerk-solidjs": "^2.0.10",
"dompurify": "^3.4.7",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"firebase-admin": "^13.10.0", "imapflow": "^1.3.5",
"imapflow": "^1.3.4", "ioredis": "^5.11.0",
"ioredis": "^5.10.1",
"isomorphic-dompurify": "^3.15.0", "isomorphic-dompurify": "^3.15.0",
"jose": "^5", "jose": "^6.2.3",
"marked": "^18.0.4", "marked": "^18.0.4",
"node-cron": "^4.2.1", "node-cron": "^4.2.1",
"onnxruntime-node": "^1.26.0", "onnxruntime-node": "^1.26.0",
"pino": "^10.3.1", "puppeteer": "^25.1.0",
"pino-pretty": "^13.1.3",
"puppeteer": "^25.0.4",
"resend": "^6.12.4", "resend": "^6.12.4",
"solid-js": "^1.9.5", "solid-js": "^1.9.5",
"stripe": "^22.1.1", "stripe": "^22.2.0",
"tailwindcss": "^4.0.0",
"three": "^0.184.0", "three": "^0.184.0",
"twilio": "^6.0.2", "valibot": "^1.4.1",
"valibot": "^0.29.0", "vite": "^7.0.0"
"vite": "^7.0.0",
"ws": "^8.21.0"
}, },
"engines": { "engines": {
"node": ">=22" "node": ">=22"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.60.0", "@tailwindcss/vite": "^4.0.7",
"@types/node-cron": "^3.0.11", "tailwindcss": "^4.0.7"
"@types/ws": "^8.18.1",
"drizzle-kit": "^0.31.10",
"jsdom": "^29.1.1",
"playwright": "^1.60.0",
"tsx": "^4.22.3",
"vite-plugin-solid": "^2.11.12",
"vitest": "^4.1.5"
} }
} }

View File

@@ -1,7 +1,6 @@
import type { APIEvent } from "@solidjs/start/server"; import type { APIEvent } from "@solidjs/start/server";
import { import {
authenticateUser, authenticateUser,
authenticateWithGoogle,
authenticateWithApple, authenticateWithApple,
createUserWithPassword, createUserWithPassword,
forgotPassword, forgotPassword,
@@ -55,7 +54,9 @@ export async function POST(event: APIEvent) {
const { name, email, password } = body; const { name, email, password } = body;
if (!email || !password) { if (!email || !password) {
return new Response( return new Response(
JSON.stringify({ message: "Name, email, and password are required" }), JSON.stringify({
message: "Name, email, and password are required",
}),
{ status: 400, headers: { "Content-Type": "application/json" } }, { status: 400, headers: { "Content-Type": "application/json" } },
); );
} }
@@ -74,32 +75,13 @@ export async function POST(event: APIEvent) {
}); });
} }
case "google": {
const { idToken } = body;
if (!idToken) {
return new Response(
JSON.stringify({ message: "idToken is required" }),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
const result = await authenticateWithGoogle(idToken);
return Response.json({
id: result.user.id,
name: result.user.name ?? "",
email: result.user.email,
image: result.user.image,
accessToken: result.accessToken,
refreshToken: result.refreshToken,
sessionToken: result.sessionToken,
isNewUser: result.isNewUser ?? false,
});
}
case "apple": { case "apple": {
const { identityToken, authorizationCode, userIdentifier } = body; const { identityToken, authorizationCode, userIdentifier } = body;
if (!identityToken || !authorizationCode) { if (!identityToken || !authorizationCode) {
return new Response( return new Response(
JSON.stringify({ message: "identityToken and authorizationCode are required" }), JSON.stringify({
message: "identityToken and authorizationCode are required",
}),
{ status: 400, headers: { "Content-Type": "application/json" } }, { status: 400, headers: { "Content-Type": "application/json" } },
); );
} }
@@ -184,10 +166,15 @@ export async function POST(event: APIEvent) {
); );
} }
} catch (error: any) { } catch (error: any) {
const statusCode = error.code === "UNAUTHORIZED" ? 401 const statusCode =
: error.code === "CONFLICT" ? 409 error.code === "UNAUTHORIZED"
: error.code === "NOT_FOUND" ? 404 ? 401
: error.code === "FORBIDDEN" ? 403 : error.code === "CONFLICT"
? 409
: error.code === "NOT_FOUND"
? 404
: error.code === "FORBIDDEN"
? 403
: 500; : 500;
return new Response( return new Response(

View File

@@ -1,7 +1,6 @@
import { exampleRouter } from "./routers/example"; import { exampleRouter } from "./routers/example";
import { userRouter } from "./routers/user"; import { userRouter } from "./routers/user";
import { billingRouter } from "./routers/billing"; import { billingRouter } from "./routers/billing";
import { notificationRouter } from "./routers/notification";
import { darkwatchRouter } from "./routers/darkwatch"; import { darkwatchRouter } from "./routers/darkwatch";
import { voiceprintRouter } from "./routers/voiceprint"; import { voiceprintRouter } from "./routers/voiceprint";
import { spamshieldRouter } from "./routers/spamshield"; import { spamshieldRouter } from "./routers/spamshield";
@@ -20,7 +19,6 @@ export const appRouter = createTRPCRouter({
example: exampleRouter, example: exampleRouter,
user: userRouter, user: userRouter,
billing: billingRouter, billing: billingRouter,
notification: notificationRouter,
darkwatch: darkwatchRouter, darkwatch: darkwatchRouter,
voiceprint: voiceprintRouter, voiceprint: voiceprintRouter,
spamshield: spamshieldRouter, spamshield: spamshieldRouter,

View File

@@ -1,100 +0,0 @@
import { wrap } from "@typeschema/valibot";
import {
object,
string,
optional,
record,
boolean,
picklist,
} from "valibot";
import { createTRPCRouter, protectedProcedure, adminProcedure } from "../utils";
import {
sendEmail,
sendPush,
sendSMS,
registerDevice,
unregisterDevice,
listDevices,
getPreferences,
updatePreferences,
} from "~/server/services/notification.service";
const SendEmailSchema = object({
to: string(),
subject: string(),
html: string(),
text: optional(string()),
});
const SendPushSchema = object({
title: string(),
body: string(),
data: optional(record(string(), string())),
});
const SendSMSSchema = object({
phoneNumber: string(),
message: string(),
});
const RegisterDeviceSchema = object({
token: string(),
platform: picklist(["ios", "android", "web"]),
deviceType: picklist(["mobile", "web", "desktop"]),
});
const UnregisterDeviceSchema = object({
token: string(),
});
const UpdatePreferencesSchema = object({
emailEnabled: optional(boolean()),
pushEnabled: optional(boolean()),
smsEnabled: optional(boolean()),
});
export const notificationRouter = createTRPCRouter({
sendEmail: adminProcedure
.input(wrap(SendEmailSchema))
.mutation(async ({ input }) => {
return sendEmail(input.to, input.subject, input.html, input.text);
}),
sendPush: protectedProcedure
.input(wrap(SendPushSchema))
.mutation(async ({ ctx, input }) => {
return sendPush(ctx.user.id, input.title, input.body, input.data);
}),
sendSMS: protectedProcedure
.input(wrap(SendSMSSchema))
.mutation(async ({ input }) => {
return sendSMS(input.phoneNumber, input.message);
}),
registerDevice: protectedProcedure
.input(wrap(RegisterDeviceSchema))
.mutation(async ({ ctx, input }) => {
return registerDevice(ctx.user.id, input.token, input.platform, input.deviceType);
}),
unregisterDevice: protectedProcedure
.input(wrap(UnregisterDeviceSchema))
.mutation(async ({ ctx, input }) => {
return unregisterDevice(ctx.user.id, input.token);
}),
listDevices: protectedProcedure.query(async ({ ctx }) => {
return listDevices(ctx.user.id);
}),
getPreferences: protectedProcedure.query(async ({ ctx }) => {
return getPreferences(ctx.user.id);
}),
updatePreferences: protectedProcedure
.input(wrap(UpdatePreferencesSchema))
.mutation(async ({ ctx, input }) => {
return updatePreferences(ctx.user.id, input);
}),
});

View File

@@ -1,7 +1,11 @@
import { wrap } from "@typeschema/valibot"; import { wrap } from "@typeschema/valibot";
import { object, string, minLength, email as emailVal } from "valibot"; import { object, string, minLength, email as emailVal } from "valibot";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { createTRPCRouter, publicProcedure, protectedProcedure } from "../utils"; import {
createTRPCRouter,
publicProcedure,
protectedProcedure,
} from "../utils";
import { import {
UpdateUserSchema, UpdateUserSchema,
InviteMemberSchema, InviteMemberSchema,
@@ -14,7 +18,6 @@ import {
deleteUser, deleteUser,
createUserWithPassword, createUserWithPassword,
authenticateUser, authenticateUser,
authenticateWithGoogle,
authenticateWithApple, authenticateWithApple,
refreshAccessToken, refreshAccessToken,
forgotPassword, forgotPassword,
@@ -39,10 +42,6 @@ const SignupSchema = object({
password: string([minLength(8)]), password: string([minLength(8)]),
}); });
const GoogleAuthSchema = object({
idToken: string([minLength(1)]),
});
const AppleAuthSchema = object({ const AppleAuthSchema = object({
identityToken: string([minLength(1)]), identityToken: string([minLength(1)]),
authorizationCode: string([minLength(1)]), authorizationCode: string([minLength(1)]),
@@ -75,12 +74,6 @@ export const userRouter = createTRPCRouter({
return createUserWithPassword(input.name, input.email, input.password); return createUserWithPassword(input.name, input.email, input.password);
}), }),
googleAuth: publicProcedure
.input(wrap(GoogleAuthSchema))
.mutation(async ({ input }) => {
return authenticateWithGoogle(input.idToken);
}),
appleAuth: publicProcedure appleAuth: publicProcedure
.input(wrap(AppleAuthSchema)) .input(wrap(AppleAuthSchema))
.mutation(async ({ input }) => { .mutation(async ({ input }) => {
@@ -141,11 +134,12 @@ export const userRouter = createTRPCRouter({
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const group = await getFamilyGroup(ctx.user.id); const group = await getFamilyGroup(ctx.user.id);
const callerMember = group.members.find( const callerMember = group.members.find((m) => m.userId === ctx.user.id);
(m) => m.userId === ctx.user.id,
);
if (!callerMember || (callerMember.role !== "owner" && callerMember.role !== "admin")) { if (
!callerMember ||
(callerMember.role !== "owner" && callerMember.role !== "admin")
) {
throw new TRPCError({ throw new TRPCError({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Only owner or admin can invite members", message: "Only owner or admin can invite members",

View File

@@ -1,40 +1,84 @@
import { sqliteTable, text, integer, uniqueIndex, index } from "drizzle-orm/sqlite-core"; import {
sqliteTable,
text,
integer,
uniqueIndex,
index,
} from "drizzle-orm/sqlite-core";
import { familyGroupMembers } from "./subscription"; import { familyGroupMembers } from "./subscription";
export { familyGroupMembers };
/** /**
* Per-member service configuration. * Per-member service configuration.
* The primary account holder assigns which services each member gets. * The primary account holder assigns which services each member gets.
* Default: all members get darkwatch + spamshield + removebrokers. * Default: all members get darkwatch + spamshield + removebrokers.
* HomeTitle and VoicePrint limited by property/voice enrollment slots. * HomeTitle and VoicePrint limited by property/voice enrollment slots.
*/ */
export const familyMemberServices = sqliteTable("family_member_services", { export const familyMemberServices = sqliteTable(
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()), "family_member_services",
memberId: text("member_id").notNull().references(() => familyGroupMembers.id, { onDelete: "cascade" }), {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
memberId: text("member_id")
.notNull()
.references(() => familyGroupMembers.id, { onDelete: "cascade" }),
service: text("service").notNull(), service: text("service").notNull(),
enabled: integer("enabled", { mode: "boolean" }).default(true).notNull(), enabled: integer("enabled", { mode: "boolean" }).default(true).notNull(),
configuredBy: text("configured_by").notNull(), configuredBy: text("configured_by").notNull(),
configuredAt: integer("configured_at", { mode: "timestamp_ms" }).defaultNow().notNull(), configuredAt: integer("configured_at", { mode: "timestamp_ms" })
createdAt: integer("created_at", { mode: "timestamp_ms" }).defaultNow().notNull(), .defaultNow()
updatedAt: integer("updated_at", { mode: "timestamp_ms" }).defaultNow().notNull().$onUpdate(() => new Date()), .notNull(),
}, (table) => ({ createdAt: integer("created_at", { mode: "timestamp_ms" })
memberServiceUnique: uniqueIndex("family_member_services_member_service_unique").on(table.memberId, table.service), .defaultNow()
memberIdIdx: index("family_member_services_member_id_idx").on(table.memberId), .notNull(),
updatedAt: integer("updated_at", { mode: "timestamp_ms" })
.defaultNow()
.notNull()
.$onUpdate(() => new Date()),
},
(table) => ({
memberServiceUnique: uniqueIndex(
"family_member_services_member_service_unique",
).on(table.memberId, table.service),
memberIdIdx: index("family_member_services_member_id_idx").on(
table.memberId,
),
serviceIdx: index("family_member_services_service_idx").on(table.service), serviceIdx: index("family_member_services_service_idx").on(table.service),
})); }),
);
/** /**
* Per-member alert notification preferences. * Per-member alert notification preferences.
* Members can opt into/off specific alert types and channels. * Members can opt into/off specific alert types and channels.
*/ */
export const familyMemberAlertPreferences = sqliteTable("family_member_alert_preferences", { export const familyMemberAlertPreferences = sqliteTable(
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()), "family_member_alert_preferences",
memberId: text("member_id").notNull().references(() => familyGroupMembers.id, { onDelete: "cascade" }), {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
memberId: text("member_id")
.notNull()
.references(() => familyGroupMembers.id, { onDelete: "cascade" }),
alertType: text("alert_type").notNull(), alertType: text("alert_type").notNull(),
channel: text("channel").notNull(), channel: text("channel").notNull(),
enabled: integer("enabled", { mode: "boolean" }).default(true).notNull(), enabled: integer("enabled", { mode: "boolean" }).default(true).notNull(),
createdAt: integer("created_at", { mode: "timestamp_ms" }).defaultNow().notNull(), createdAt: integer("created_at", { mode: "timestamp_ms" })
updatedAt: integer("updated_at", { mode: "timestamp_ms" }).defaultNow().notNull().$onUpdate(() => new Date()), .defaultNow()
}, (table) => ({ .notNull(),
memberChannelTypeUnique: uniqueIndex("family_member_alert_prefs_member_channel_type_unique").on(table.memberId, table.channel, table.alertType), updatedAt: integer("updated_at", { mode: "timestamp_ms" })
memberIdIdx: index("family_member_alert_prefs_member_id_idx").on(table.memberId), .defaultNow()
})); .notNull()
.$onUpdate(() => new Date()),
},
(table) => ({
memberChannelTypeUnique: uniqueIndex(
"family_member_alert_prefs_member_channel_type_unique",
).on(table.memberId, table.channel, table.alertType),
memberIdIdx: index("family_member_alert_prefs_member_id_idx").on(
table.memberId,
),
}),
);

View File

@@ -1,6 +1,8 @@
import type { JobPayload, JobType } from "../queue"; import type { JobPayload, JobType } from "../queue";
export type JobHandler<T extends JobType = JobType> = (payload: JobPayload[T]) => Promise<void>; export type JobHandler<T extends JobType = JobType> = (
payload: JobPayload[T],
) => Promise<void>;
export type HandlerMap = { export type HandlerMap = {
[K in JobType]: JobHandler<K>; [K in JobType]: JobHandler<K>;
@@ -17,7 +19,6 @@ export function getHandlers(): HandlerMap {
"hometitle.scan": require("./hometitle.scan").handler, "hometitle.scan": require("./hometitle.scan").handler,
"removebrokers.process": require("./removebrokers.process").handler, "removebrokers.process": require("./removebrokers.process").handler,
"reports.generate": require("./reports.generate").handler, "reports.generate": require("./reports.generate").handler,
"notifications.send": require("./notifications.send").handler,
}; };
} }
return handlers; return handlers;
@@ -31,6 +32,5 @@ export function setHandlers(mock: Partial<HandlerMap>): void {
"hometitle.scan": mock["hometitle.scan"] ?? (async () => {}), "hometitle.scan": mock["hometitle.scan"] ?? (async () => {}),
"removebrokers.process": mock["removebrokers.process"] ?? (async () => {}), "removebrokers.process": mock["removebrokers.process"] ?? (async () => {}),
"reports.generate": mock["reports.generate"] ?? (async () => {}), "reports.generate": mock["reports.generate"] ?? (async () => {}),
"notifications.send": mock["notifications.send"] ?? (async () => {}),
}; };
} }

View File

@@ -1,70 +0,0 @@
import { eq, and } from "drizzle-orm";
import { db } from "~/server/db";
import { alerts, subscriptions, users } from "~/server/db/schema";
import { sendEmail, sendPush, sendSMS } from "~/server/services/notification.service";
interface NotificationsSendPayload {
userId: string;
alertId?: string;
channel: string;
}
export async function handler(payload: NotificationsSendPayload): Promise<void> {
const { userId, alertId, channel } = payload;
const [user] = await db
.select()
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user) {
console.warn(`[notifications.send] User ${userId} not found`);
return;
}
if (alertId) {
const [alert] = await db
.select()
.from(alerts)
.where(and(eq(alerts.id, alertId), eq(alerts.userId, userId)))
.limit(1);
if (!alert) {
console.warn(`[notifications.send] Alert ${alertId} not found`);
return;
}
await sendViaChannel(channel, user, alert.title, alert.message);
} else {
const unsentAlerts = await db
.select()
.from(alerts)
.where(and(eq(alerts.userId, userId), eq(alerts.isRead, false)))
.limit(20);
for (const alert of unsentAlerts) {
for (const ch of alert.channel as string[]) {
await sendViaChannel(ch, user, alert.title, alert.message);
}
}
}
}
async function sendViaChannel(channel: string, user: { email: string; id: string }, title: string, message: string): Promise<void> {
try {
switch (channel) {
case "email":
await sendEmail(user.email, title, `<p>${message}</p>`);
break;
case "push":
await sendPush(user.id, title, message);
break;
case "sms":
await sendSMS(user.email, message);
break;
}
} catch (err) {
console.error(`[notifications.send] Failed to send via ${channel}:`, err);
}
}

View File

@@ -7,7 +7,6 @@ export const JOB_TYPES = [
"hometitle.scan", "hometitle.scan",
"removebrokers.process", "removebrokers.process",
"reports.generate", "reports.generate",
"notifications.send",
] as const; ] as const;
export type JobType = (typeof JOB_TYPES)[number]; export type JobType = (typeof JOB_TYPES)[number];
@@ -18,8 +17,11 @@ export type JobPayload = {
"voiceprint.batch": { userId?: string; jobId?: string }; "voiceprint.batch": { userId?: string; jobId?: string };
"hometitle.scan": { userId: string; subscriptionId: string }; "hometitle.scan": { userId: string; subscriptionId: string };
"removebrokers.process": { subscriptionId?: string; requestId?: string }; "removebrokers.process": { subscriptionId?: string; requestId?: string };
"reports.generate": { userId: string; reportScheduleId?: string; reportType: string }; "reports.generate": {
"notifications.send": { userId: string; alertId?: string; channel: string }; userId: string;
reportScheduleId?: string;
reportType: string;
};
}; };
export type JobStatus = "pending" | "running" | "completed" | "failed"; export type JobStatus = "pending" | "running" | "completed" | "failed";
@@ -42,7 +44,11 @@ export interface EnqueueOptions {
} }
export interface QueueAdapter { export interface QueueAdapter {
enqueue<T extends JobType>(type: T, payload: JobPayload[T], options?: EnqueueOptions): Promise<Job<T>>; enqueue<T extends JobType>(
type: T,
payload: JobPayload[T],
options?: EnqueueOptions,
): Promise<Job<T>>;
dequeue(): Promise<Job | null>; dequeue(): Promise<Job | null>;
markComplete(jobId: string): Promise<void>; markComplete(jobId: string): Promise<void>;
markFailed(jobId: string, error: string): Promise<void>; markFailed(jobId: string, error: string): Promise<void>;
@@ -55,7 +61,11 @@ export class InMemoryQueue implements QueueAdapter {
private jobs = new Map<string, Job>(); private jobs = new Map<string, Job>();
private pendingQueue: string[] = []; private pendingQueue: string[] = [];
async enqueue<T extends JobType>(type: T, payload: JobPayload[T], options?: EnqueueOptions): Promise<Job<T>> { async enqueue<T extends JobType>(
type: T,
payload: JobPayload[T],
options?: EnqueueOptions,
): Promise<Job<T>> {
const id = randomUUID(); const id = randomUUID();
const job: Job<T> = { const job: Job<T> = {
id, id,
@@ -132,12 +142,15 @@ function createRedisAdapter(): QueueAdapter {
const BullMQ = require("bullmq"); const BullMQ = require("bullmq");
const IORedis = require("ioredis"); const IORedis = require("ioredis");
const connection = new IORedis.default(process.env.REDIS_URL ?? "redis://localhost:6379", { const connection = new IORedis.default(
process.env.REDIS_URL ?? "redis://localhost:6379",
{
maxRetriesPerRequest: null, maxRetriesPerRequest: null,
}); },
);
const queue = new BullMQ.Queue("kordant-jobs", { connection }); const queue = new BullMQ.Queue("kordant-jobs", { connection });
let bullJobs = new Map<string, any>(); const bullJobs = new Map<string, any>();
async function toJob(bullJob: any): Promise<Job> { async function toJob(bullJob: any): Promise<Job> {
return { return {
@@ -149,12 +162,18 @@ function createRedisAdapter(): QueueAdapter {
maxAttempts: bullJob.opts?.attempts ?? 3, maxAttempts: bullJob.opts?.attempts ?? 3,
error: bullJob.failedReason ?? undefined, error: bullJob.failedReason ?? undefined,
createdAt: bullJob.timestamp ? new Date(bullJob.timestamp) : new Date(), createdAt: bullJob.timestamp ? new Date(bullJob.timestamp) : new Date(),
updatedAt: bullJob.processedOn ? new Date(bullJob.processedOn) : new Date(), updatedAt: bullJob.processedOn
? new Date(bullJob.processedOn)
: new Date(),
}; };
} }
return { return {
async enqueue<T extends JobType>(type: T, payload: JobPayload[T], options?: EnqueueOptions) { async enqueue<T extends JobType>(
type: T,
payload: JobPayload[T],
options?: EnqueueOptions,
) {
const bullJob = await queue.add(type, payload, { const bullJob = await queue.add(type, payload, {
attempts: options?.maxAttempts ?? 3, attempts: options?.maxAttempts ?? 3,
delay: options?.delay, delay: options?.delay,
@@ -187,7 +206,9 @@ function createRedisAdapter(): QueueAdapter {
}, },
async getJobs(status) { async getJobs(status) {
const states = status ? [status] : ["waiting", "active", "completed", "failed"]; const states = status
? [status]
: ["waiting", "active", "completed", "failed"];
const allJobs: Job[] = []; const allJobs: Job[] = [];
for (const state of states) { for (const state of states) {
const jobs = await queue.getJobs(state); const jobs = await queue.getJobs(state);

View File

@@ -0,0 +1,42 @@
import { TRPCError } from "@trpc/server";
import { resend } from "~/server/lib/resend";
export async function sendEmail(
to: string,
subject: string,
html: string,
text?: string,
) {
if (!process.env.RESEND_API_KEY) {
console.warn("[email] Resend not configured, skipping email");
return { id: null };
}
try {
const { data, error } = await resend.emails.send({
from: process.env.RESEND_FROM_EMAIL ?? "noreply@kordant.ai",
to,
subject,
html,
text: text ?? "",
});
if (error) {
console.error("[email] Resend error:", error);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send email",
});
}
console.log("[email] Email sent:", data?.id);
return { id: data?.id ?? null };
} catch (err) {
if (err instanceof TRPCError) throw err;
console.error("[email] Email send error:", err);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send email",
});
}
}

View File

@@ -32,11 +32,6 @@ const envSchema = object({
// Email // Email
RESEND_API_KEY: optional(string()), RESEND_API_KEY: optional(string()),
// Push
FCM_PROJECT_ID: optional(string()),
FCM_CLIENT_EMAIL: optional(string()),
FCM_PRIVATE_KEY: optional(string()),
// SMS // SMS
TWILIO_ACCOUNT_SID: optional(string()), TWILIO_ACCOUNT_SID: optional(string()),
TWILIO_AUTH_TOKEN: optional(string()), TWILIO_AUTH_TOKEN: optional(string()),

View File

@@ -1,18 +0,0 @@
import { initializeApp, cert, getApps } from "firebase-admin/app";
import { getMessaging } from "firebase-admin/messaging";
const projectId = process.env.FCM_PROJECT_ID;
const clientEmail = process.env.FCM_CLIENT_EMAIL;
const privateKey = process.env.FCM_PRIVATE_KEY;
if (!getApps().length && projectId && clientEmail && privateKey) {
initializeApp({
credential: cert({
projectId,
clientEmail,
privateKey: privateKey.replace(/\\n/g, "\n"),
}),
});
}
export const messaging = getApps().length ? getMessaging() : null;

View File

@@ -7,11 +7,9 @@ vi.mock("~/server/websocket", () => ({
broadcastToUser: mockBroadcastToUser, broadcastToUser: mockBroadcastToUser,
})); }));
const mockSendPush = vi.fn();
const mockSendEmail = vi.fn(); const mockSendEmail = vi.fn();
vi.mock("~/server/services/notification.service", () => ({ vi.mock("~/server/lib/email", () => ({
sendPush: mockSendPush,
sendEmail: mockSendEmail, sendEmail: mockSendEmail,
})); }));
@@ -54,13 +52,22 @@ describe("alert.publisher", () => {
createdAt: expect.any(String), createdAt: expect.any(String),
}, },
}); });
expect(mockSendPush).not.toHaveBeenCalled();
expect(mockSendEmail).not.toHaveBeenCalled(); expect(mockSendEmail).not.toHaveBeenCalled();
}); });
it("should fall back to push notification when user is not connected", async () => { it("should fall back to email when user is not connected and has email", async () => {
mockBroadcastToUser.mockReturnValue(false); mockBroadcastToUser.mockReturnValue(false);
mockSendPush.mockResolvedValue({ successCount: 1 });
const db = await import("~/server/db");
(db.db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi
.fn()
.mockResolvedValue([{ id: "user-1", email: "user@example.com" }]),
}),
}),
});
const { publishAlert } = await import("./alert.publisher"); const { publishAlert } = await import("./alert.publisher");
await publishAlert("user-1", { await publishAlert("user-1", {
@@ -74,17 +81,16 @@ describe("alert.publisher", () => {
}); });
expect(mockBroadcastToUser).toHaveBeenCalled(); expect(mockBroadcastToUser).toHaveBeenCalled();
expect(mockSendPush).toHaveBeenCalledWith( expect(mockSendEmail).toHaveBeenCalledWith(
"user-1", "user@example.com",
"Offline Alert", "[Kordant] Offline Alert",
"<p>Offline message</p>",
"Offline message", "Offline message",
{ alertId: "alert-2", source: "VOICEPRINT", severity: "WARNING" },
); );
}); });
it("should publish alert to multiple users", async () => { it("should not send email when user has no email", async () => {
mockBroadcastToUser.mockReturnValue(false); mockBroadcastToUser.mockReturnValue(false);
mockSendPush.mockResolvedValue({ successCount: 0 });
const db = await import("~/server/db"); const db = await import("~/server/db");
(db.db.select as ReturnType<typeof vi.fn>).mockReturnValue({ (db.db.select as ReturnType<typeof vi.fn>).mockReturnValue({
@@ -95,9 +101,26 @@ describe("alert.publisher", () => {
}), }),
}); });
const { publishAlert } = await import("./alert.publisher");
await publishAlert("user-1", {
id: "alert-3",
title: "No Email",
message: "No email",
severity: "INFO",
source: "HOME_TITLE",
category: "HOME_TITLE",
createdAt: new Date(),
});
expect(mockSendEmail).not.toHaveBeenCalled();
});
it("should publish alert to multiple users", async () => {
mockBroadcastToUser.mockReturnValue(true);
const { publishToGroup } = await import("./alert.publisher"); const { publishToGroup } = await import("./alert.publisher");
await publishToGroup(["user-1", "user-2"], { await publishToGroup(["user-1", "user-2"], {
id: "alert-3", id: "alert-4",
title: "Group Alert", title: "Group Alert",
message: "Group message", message: "Group message",
severity: "INFO", severity: "INFO",

View File

@@ -1,5 +1,5 @@
import { broadcastToUser } from "~/server/websocket"; import { broadcastToUser } from "~/server/websocket";
import { sendPush, sendEmail } from "~/server/services/notification.service"; import { sendEmail } from "~/server/lib/email";
import { db } from "~/server/db"; import { db } from "~/server/db";
import { users } from "~/server/db/schema/auth"; import { users } from "~/server/db/schema/auth";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
@@ -14,7 +14,10 @@ export interface PublishableAlert {
createdAt: Date; createdAt: Date;
} }
export async function publishAlert(userId: string, alert: PublishableAlert): Promise<void> { export async function publishAlert(
userId: string,
alert: PublishableAlert,
): Promise<void> {
const message = { const message = {
type: "alert" as const, type: "alert" as const,
alert: { alert: {
@@ -31,14 +34,6 @@ export async function publishAlert(userId: string, alert: PublishableAlert): Pro
const sent = broadcastToUser(userId, message); const sent = broadcastToUser(userId, message);
if (!sent) { if (!sent) {
try {
const pushResult = await sendPush(userId, alert.title, alert.message, {
alertId: alert.id,
source: alert.source,
severity: alert.severity,
});
if (pushResult.successCount === 0) {
const [user] = await db const [user] = await db
.select() .select()
.from(users) .from(users)
@@ -46,21 +41,24 @@ export async function publishAlert(userId: string, alert: PublishableAlert): Pro
.limit(1); .limit(1);
if (user?.email) { if (user?.email) {
try {
await sendEmail( await sendEmail(
user.email, user.email,
`[Kordant] ${alert.title}`, `[Kordant] ${alert.title}`,
`<p>${alert.message}</p>`, `<p>${alert.message}</p>`,
alert.message, alert.message,
); );
}
}
} catch (err) { } catch (err) {
console.error("[alert.publisher] Fallback notification failed:", err); console.error("[alert.publisher] Email notification failed:", err);
}
} }
} }
} }
export async function publishToGroup(userIds: string[], alert: PublishableAlert): Promise<void> { export async function publishToGroup(
userIds: string[],
alert: PublishableAlert,
): Promise<void> {
const promises = userIds.map((userId) => publishAlert(userId, alert)); const promises = userIds.map((userId) => publishAlert(userId, alert));
await Promise.allSettled(promises); await Promise.allSettled(promises);
} }

View File

@@ -1,7 +1,7 @@
import { eq, and, asc } from "drizzle-orm"; import { eq, and, asc } from "drizzle-orm";
import { db } from "~/server/db"; import { db } from "~/server/db";
import { digestAlerts, notificationPreferences } from "~/server/db/schema"; import { digestAlerts, notificationPreferences } from "~/server/db/schema";
import { sendEmail } from "~/server/services/notification.service"; import { sendEmail } from "~/server/lib/email";
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Digest configuration // Digest configuration
@@ -55,7 +55,9 @@ export async function shouldDigest(
/** /**
* Calculates the next scheduled digest date based on config. * Calculates the next scheduled digest date based on config.
*/ */
export function calculateNextDigestDate(config: DigestConfig = DEFAULT_DIGEST_CONFIG): Date { export function calculateNextDigestDate(
config: DigestConfig = DEFAULT_DIGEST_CONFIG,
): Date {
const now = new Date(); const now = new Date();
const next = new Date(now); const next = new Date(now);
@@ -155,7 +157,9 @@ export async function sendDigestEmail(
await db await db
.update(digestAlerts) .update(digestAlerts)
.set({ sent: true, sentAt: new Date() }) .set({ sent: true, sentAt: new Date() })
.where(and(eq(digestAlerts.userId, userId), eq(digestAlerts.id, alertIds[0]))); .where(
and(eq(digestAlerts.userId, userId), eq(digestAlerts.id, alertIds[0])),
);
// Update all matching alerts // Update all matching alerts
for (const alertId of alertIds) { for (const alertId of alertIds) {
@@ -165,7 +169,9 @@ export async function sendDigestEmail(
.where(eq(digestAlerts.id, alertId)); .where(eq(digestAlerts.id, alertId));
} }
console.log(`[digest] Sent digest to ${user.email} with ${pendingAlerts.length} alerts`); console.log(
`[digest] Sent digest to ${user.email} with ${pendingAlerts.length} alerts`,
);
return pendingAlerts.length; return pendingAlerts.length;
} catch (err) { } catch (err) {
console.error(`[digest] Failed to send digest for user ${userId}:`, err); console.error(`[digest] Failed to send digest for user ${userId}:`, err);
@@ -193,11 +199,7 @@ export async function processDueDigests(): Promise<void> {
scheduledDate: digestAlerts.scheduledDigestDate, scheduledDate: digestAlerts.scheduledDigestDate,
}) })
.from(digestAlerts) .from(digestAlerts)
.where( .where(and(eq(digestAlerts.sent, false)));
and(
eq(digestAlerts.sent, false),
),
);
// Group by user // Group by user
const userMap = new Map<string, Date[]>(); const userMap = new Map<string, Date[]>();
@@ -221,9 +223,9 @@ export async function processDueDigests(): Promise<void> {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function groupBySeverity( function groupBySeverity(
alerts: typeof digestAlerts.$InferInsert[], alerts: (typeof digestAlerts.$InferInsert)[],
): Record<string, typeof digestAlerts.$InferInsert[]> { ): Record<string, (typeof digestAlerts.$InferInsert)[]> {
const groups: Record<string, typeof digestAlerts.$InferInsert[]> = { const groups: Record<string, (typeof digestAlerts.$InferInsert)[]> = {
critical: [], critical: [],
warning: [], warning: [],
info: [], info: [],
@@ -242,7 +244,7 @@ function groupBySeverity(
} }
function buildDigestEmailHTML( function buildDigestEmailHTML(
groups: Record<string, typeof digestAlerts.$InferInsert[]>, groups: Record<string, (typeof digestAlerts.$InferInsert)[]>,
total: number, total: number,
): string { ): string {
const sections = []; const sections = [];
@@ -289,10 +291,13 @@ function buildDigestEmailHTML(
} }
function buildDigestPlainText( function buildDigestPlainText(
groups: Record<string, typeof digestAlerts.$InferInsert[]>, groups: Record<string, (typeof digestAlerts.$InferInsert)[]>,
total: number, total: number,
): string { ): string {
const lines = [`Kordant Security Digest — ${total} alert${total > 1 ? "s" : ""}`, ""]; const lines = [
`Kordant Security Digest — ${total} alert${total > 1 ? "s" : ""}`,
"",
];
for (const [key, alerts] of Object.entries(groups)) { for (const [key, alerts] of Object.entries(groups)) {
if (!alerts.length) continue; if (!alerts.length) continue;
@@ -321,13 +326,7 @@ function escapeHtml(str: string): string {
export async function cleanupOldDigests(): Promise<void> { export async function cleanupOldDigests(): Promise<void> {
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
await db await db.delete(digestAlerts).where(and(eq(digestAlerts.sent, true)));
.delete(digestAlerts)
.where(
and(
eq(digestAlerts.sent, true),
),
);
console.log(`[digest] Cleaned up old digest records`); console.log(`[digest] Cleaned up old digest records`);
} }

View File

@@ -1,464 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { TRPCError } from "@trpc/server";
const mockResendSend = vi.fn();
const mockMessagingSend = vi.fn();
const mockTwilioCreate = vi.fn();
vi.mock("~/server/db", () => ({
db: {
select: vi.fn(),
insert: vi.fn(),
update: vi.fn(),
},
}));
vi.mock("~/server/lib/resend", () => ({
resend: { emails: { send: mockResendSend } },
}));
vi.mock("~/server/lib/fcm", () => ({
messaging: { send: mockMessagingSend },
}));
vi.mock("~/server/lib/twilio", () => ({
twilioClient: { messages: { create: mockTwilioCreate } },
}));
import { db } from "~/server/db";
beforeEach(() => {
vi.clearAllMocks();
});
describe("sendEmail", () => {
it("calls Resend with correct parameters", async () => {
process.env.RESEND_API_KEY = "test-key";
mockResendSend.mockResolvedValue({
data: { id: "email-1" },
error: null,
});
const { sendEmail } = await import("./notification.service");
const result = await sendEmail("test@example.com", "Subject", "<p>Body</p>", "Text body");
expect(mockResendSend).toHaveBeenCalledWith({
from: "noreply@kordant.ai",
to: "test@example.com",
subject: "Subject",
html: "<p>Body</p>",
text: "Text body",
});
expect(result).toEqual({ id: "email-1" });
});
it("skips sending when Resend API key is not configured", async () => {
delete process.env.RESEND_API_KEY;
const { sendEmail } = await import("./notification.service");
const result = await sendEmail("test@example.com", "Subject", "<p>Body</p>");
expect(result).toEqual({ id: null });
expect(mockResendSend).not.toHaveBeenCalled();
});
it("throws INTERNAL_SERVER_ERROR when Resend returns an error", async () => {
process.env.RESEND_API_KEY = "test-key";
mockResendSend.mockResolvedValue({
data: null,
error: { message: "API error" },
});
const { sendEmail } = await import("./notification.service");
await expect(sendEmail("test@example.com", "Subject", "<p>Body</p>")).rejects.toThrow(TRPCError);
await expect(sendEmail("test@example.com", "Subject", "<p>Body</p>")).rejects.toMatchObject({
code: "INTERNAL_SERVER_ERROR",
});
});
});
describe("sendPush", () => {
it("sends FCM message to all active devices", async () => {
const devices = [
{ id: "d1", userId: "u1", token: "token-1", platform: "android", deviceType: "mobile", isActive: true },
{ id: "d2", userId: "u1", token: "token-2", platform: "ios", deviceType: "mobile", isActive: true },
];
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockResolvedValue(devices),
}),
});
mockMessagingSend.mockResolvedValue({});
const { sendPush } = await import("./notification.service");
const result = await sendPush("u1", "Title", "Body", { key: "val" });
expect(result).toEqual({ successCount: 2 });
expect(mockMessagingSend).toHaveBeenCalledTimes(2);
expect(mockMessagingSend).toHaveBeenCalledWith({
token: "token-1",
notification: { title: "Title", body: "Body" },
data: { key: "val" },
android: { priority: "high" },
apns: { payload: { aps: { alert: { title: "Title", body: "Body" }, sound: "default", badge: 1 } } },
});
});
it("returns 0 success when no active devices", async () => {
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockResolvedValue([]),
}),
});
const { sendPush } = await import("./notification.service");
const result = await sendPush("u1", "Title", "Body");
expect(result).toEqual({ successCount: 0 });
expect(mockMessagingSend).not.toHaveBeenCalled();
});
it("continues sending if one push fails", async () => {
const devices = [
{ id: "d1", userId: "u1", token: "token-1", platform: "android", deviceType: "mobile", isActive: true },
{ id: "d2", userId: "u1", token: "token-2", platform: "ios", deviceType: "mobile", isActive: true },
];
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockResolvedValue(devices),
}),
});
mockMessagingSend
.mockRejectedValueOnce(new Error("FCM error"))
.mockResolvedValueOnce({});
const { sendPush } = await import("./notification.service");
const result = await sendPush("u1", "Title", "Body");
expect(result).toEqual({ successCount: 1 });
});
});
describe("sendSMS", () => {
it("calls Twilio with correct parameters", async () => {
process.env.TWILIO_MESSAGING_SERVICE_SID = "MGxxx";
mockTwilioCreate.mockResolvedValue({ sid: "SMxxx" });
const { sendSMS } = await import("./notification.service");
const result = await sendSMS("+1234567890", "Hello");
expect(mockTwilioCreate).toHaveBeenCalledWith({
body: "Hello",
to: "+1234567890",
messagingServiceSid: "MGxxx",
});
expect(result).toEqual({ sid: "SMxxx" });
});
it("throws BAD_REQUEST for non-E.164 phone numbers", async () => {
const { sendSMS } = await import("./notification.service");
await expect(sendSMS("1234567890", "Hello")).rejects.toThrow(TRPCError);
await expect(sendSMS("1234567890", "Hello")).rejects.toMatchObject({
code: "BAD_REQUEST",
});
await expect(sendSMS("+12", "Hello")).rejects.toMatchObject({
code: "BAD_REQUEST",
});
});
it("accepts valid E.164 phone numbers", async () => {
mockTwilioCreate.mockResolvedValue({ sid: "SMxxx" });
const { sendSMS } = await import("./notification.service");
await expect(sendSMS("+1234567890", "Hello")).resolves.toEqual({ sid: "SMxxx" });
await expect(sendSMS("+447911123456", "Hello")).resolves.toEqual({ sid: "SMxxx" });
});
});
describe("registerDevice", () => {
it("creates a new device token record", async () => {
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([]),
}),
}),
});
const newDevice = {
id: "d-new",
userId: "u1",
token: "new-token",
platform: "android",
deviceType: "mobile",
isActive: true,
lastUsedAt: new Date(),
};
(db.insert as ReturnType<typeof vi.fn>).mockReturnValue({
values: vi.fn().mockReturnValue({
returning: vi.fn().mockResolvedValue([newDevice]),
}),
});
const { registerDevice } = await import("./notification.service");
const result = await registerDevice("u1", "new-token", "android", "mobile");
expect(result).toEqual(newDevice);
expect(db.insert).toHaveBeenCalled();
});
it("reactivates an existing token for the same user", async () => {
const existing = {
id: "d1",
userId: "u1",
token: "existing-token",
platform: "android",
deviceType: "mobile",
isActive: false,
lastUsedAt: new Date(0),
};
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([existing]),
}),
}),
});
const updated = { ...existing, isActive: true, lastUsedAt: expect.any(Date) };
(db.update as ReturnType<typeof vi.fn>).mockReturnValue({
set: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
returning: vi.fn().mockResolvedValue([updated]),
}),
}),
});
const { registerDevice } = await import("./notification.service");
const result = await registerDevice("u1", "existing-token", "android", "mobile");
expect(result).toEqual(updated);
expect(db.update).toHaveBeenCalled();
});
it("throws CONFLICT when token belongs to another user", async () => {
const existing = {
id: "d1",
userId: "u2",
token: "other-user-token",
platform: "android",
deviceType: "mobile",
isActive: true,
};
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([existing]),
}),
}),
});
const { registerDevice } = await import("./notification.service");
await expect(registerDevice("u1", "other-user-token", "android", "mobile")).rejects.toThrow(TRPCError);
await expect(registerDevice("u1", "other-user-token", "android", "mobile")).rejects.toMatchObject({
code: "CONFLICT",
});
});
});
describe("unregisterDevice", () => {
it("marks a device token as inactive", async () => {
const existing = {
id: "d1",
userId: "u1",
token: "token-1",
platform: "android",
deviceType: "mobile",
isActive: true,
};
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([existing]),
}),
}),
});
const deactivated = { ...existing, isActive: false };
(db.update as ReturnType<typeof vi.fn>).mockReturnValue({
set: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
returning: vi.fn().mockResolvedValue([deactivated]),
}),
}),
});
const { unregisterDevice } = await import("./notification.service");
const result = await unregisterDevice("u1", "token-1");
expect(result.isActive).toBe(false);
});
it("throws NOT_FOUND when token does not exist", async () => {
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([]),
}),
}),
});
const { unregisterDevice } = await import("./notification.service");
await expect(unregisterDevice("u1", "nonexistent")).rejects.toThrow(TRPCError);
await expect(unregisterDevice("u1", "nonexistent")).rejects.toMatchObject({
code: "NOT_FOUND",
});
});
});
describe("listDevices", () => {
it("returns all devices for a user ordered by creation date", async () => {
const devices = [
{ id: "d1", userId: "u1", token: "token-1", platform: "android", createdAt: new Date("2024-01-01") },
{ id: "d2", userId: "u1", token: "token-2", platform: "ios", createdAt: new Date("2024-01-02") },
];
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
orderBy: vi.fn().mockResolvedValue(devices),
}),
}),
});
const { listDevices } = await import("./notification.service");
const result = await listDevices("u1");
expect(result).toEqual(devices);
expect(result).toHaveLength(2);
});
});
describe("getPreferences", () => {
it("returns existing preferences from DB", async () => {
const prefs = {
id: "p1",
userId: "u1",
emailEnabled: false,
pushEnabled: true,
smsEnabled: false,
};
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([prefs]),
}),
}),
});
const { getPreferences } = await import("./notification.service");
const result = await getPreferences("u1");
expect(result).toMatchObject({
emailEnabled: false,
pushEnabled: true,
smsEnabled: false,
});
});
it("returns default preferences when no record exists", async () => {
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([]),
}),
}),
});
const { getPreferences } = await import("./notification.service");
const result = await getPreferences("u1");
expect(result).toEqual({
emailEnabled: true,
pushEnabled: true,
smsEnabled: true,
});
});
});
describe("updatePreferences", () => {
it("updates existing preferences", async () => {
const existing = {
id: "p1",
userId: "u1",
emailEnabled: true,
pushEnabled: true,
smsEnabled: true,
};
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([existing]),
}),
}),
});
const updated = { ...existing, smsEnabled: false };
(db.update as ReturnType<typeof vi.fn>).mockReturnValue({
set: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
returning: vi.fn().mockResolvedValue([updated]),
}),
}),
});
const { updatePreferences } = await import("./notification.service");
const result = await updatePreferences("u1", { smsEnabled: false });
expect(result.smsEnabled).toBe(false);
});
it("creates new preferences record when none exists", async () => {
(db.select as ReturnType<typeof vi.fn>).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([]),
}),
}),
});
const created = {
id: "p-new",
userId: "u1",
emailEnabled: false,
pushEnabled: true,
smsEnabled: true,
};
(db.insert as ReturnType<typeof vi.fn>).mockReturnValue({
values: vi.fn().mockReturnValue({
returning: vi.fn().mockResolvedValue([created]),
}),
});
const { updatePreferences } = await import("./notification.service");
const result = await updatePreferences("u1", { emailEnabled: false });
expect(result).toEqual(created);
expect(db.insert).toHaveBeenCalled();
});
});

View File

@@ -1,256 +0,0 @@
import { eq, and } from "drizzle-orm";
import { TRPCError } from "@trpc/server";
import { db } from "~/server/db";
import { deviceTokens } from "~/server/db/schema/auth";
import { notificationPreferences } from "~/server/db/schema/notifications";
import { resend } from "~/server/lib/resend";
import { messaging } from "~/server/lib/fcm";
import { twilioClient } from "~/server/lib/twilio";
export async function sendEmail(
to: string,
subject: string,
html: string,
text?: string,
) {
if (!process.env.RESEND_API_KEY) {
console.warn("[notifications] Resend not configured, skipping email");
return { id: null };
}
try {
const { data, error } = await resend.emails.send({
from: process.env.RESEND_FROM_EMAIL ?? "noreply@kordant.ai",
to,
subject,
html,
text: text ?? "",
});
if (error) {
console.error("[notifications] Resend error:", error);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send email",
});
}
console.log("[notifications] Email sent:", data?.id);
return { id: data?.id ?? null };
} catch (err) {
if (err instanceof TRPCError) throw err;
console.error("[notifications] Email send error:", err);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send email",
});
}
}
export async function sendPush(
userId: string,
title: string,
body: string,
data?: Record<string, string>,
) {
const tokens = await db
.select()
.from(deviceTokens)
.where(
and(
eq(deviceTokens.userId, userId),
eq(deviceTokens.isActive, true),
),
);
if (!tokens.length) {
console.warn("[notifications] No active devices for user", userId);
return { successCount: 0 };
}
if (!messaging) {
console.warn("[notifications] FCM not configured, skipping push");
return { successCount: 0 };
}
const tokenStrings = tokens.map((t) => t.token);
let successCount = 0;
for (const token of tokenStrings) {
try {
await messaging.send({
token,
notification: { title, body },
data,
android: { priority: "high" },
apns: {
payload: {
aps: {
alert: { title, body },
sound: "default",
badge: 1,
},
},
},
});
successCount++;
} catch (err) {
console.error("[notifications] Push send error for token:", err);
}
}
console.log("[notifications] Push sent to", successCount, "/", tokens.length, "devices");
return { successCount };
}
export async function sendSMS(phoneNumber: string, message: string) {
const e164Regex = /^\+[1-9]\d{6,14}$/;
if (!e164Regex.test(phoneNumber)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Phone number must be in E.164 format (e.g. +1234567890)",
});
}
if (!twilioClient) {
console.warn("[notifications] Twilio not configured, skipping SMS");
return { sid: null };
}
try {
const result = await twilioClient.messages.create({
body: message,
to: phoneNumber,
messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID,
});
console.log("[notifications] SMS sent:", result.sid);
return { sid: result.sid };
} catch (err) {
console.error("[notifications] SMS send error:", err);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send SMS",
});
}
}
export async function registerDevice(
userId: string,
token: string,
platform: "ios" | "android" | "web",
deviceType: "mobile" | "web" | "desktop",
) {
const [existing] = await db
.select()
.from(deviceTokens)
.where(eq(deviceTokens.token, token))
.limit(1);
if (existing) {
if (existing.userId !== userId) {
throw new TRPCError({
code: "CONFLICT",
message: "Device token already registered to another user",
});
}
const [updated] = await db
.update(deviceTokens)
.set({ isActive: true, lastUsedAt: new Date() })
.where(eq(deviceTokens.id, existing.id))
.returning();
return updated;
}
const [created] = await db
.insert(deviceTokens)
.values({ userId, token, platform, deviceType })
.returning();
return created;
}
export async function unregisterDevice(userId: string, token: string) {
const [existing] = await db
.select()
.from(deviceTokens)
.where(
and(
eq(deviceTokens.token, token),
eq(deviceTokens.userId, userId),
),
)
.limit(1);
if (!existing) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Device token not found",
});
}
const [updated] = await db
.update(deviceTokens)
.set({ isActive: false })
.where(eq(deviceTokens.id, existing.id))
.returning();
return updated;
}
export async function listDevices(userId: string) {
const devices = await db
.select()
.from(deviceTokens)
.where(eq(deviceTokens.userId, userId))
.orderBy(deviceTokens.createdAt);
return devices;
}
export async function getPreferences(userId: string) {
const [prefs] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1);
if (!prefs) {
return {
emailEnabled: true,
pushEnabled: true,
smsEnabled: true,
};
}
return prefs;
}
export async function updatePreferences(
userId: string,
prefs: { emailEnabled?: boolean; pushEnabled?: boolean; smsEnabled?: boolean },
) {
const [existing] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1);
if (existing) {
const [updated] = await db
.update(notificationPreferences)
.set(prefs)
.where(eq(notificationPreferences.userId, userId))
.returning();
return updated;
}
const [created] = await db
.insert(notificationPreferences)
.values({ userId, ...prefs })
.returning();
return created;
}

View File

@@ -90,7 +90,7 @@ function cacheKey(text: string): string {
let hash = 0; let hash = 0;
for (let i = 0; i < normalized.length; i++) { for (let i = 0; i < normalized.length; i++) {
const char = normalized.charCodeAt(i); const char = normalized.charCodeAt(i);
hash = ((hash << 5) - hash) + char; hash = (hash << 5) - hash + char;
hash |= 0; // Convert to 32bit integer hash |= 0; // Convert to 32bit integer
} }
return String(hash); return String(hash);
@@ -155,7 +155,9 @@ class BertTokenizer {
let doLowercase = true; let doLowercase = true;
let modelMaxLength = 512; let modelMaxLength = 512;
try { try {
const configData = JSON.parse(fs.readFileSync(tokenizerConfigPath, "utf-8")); const configData = JSON.parse(
fs.readFileSync(tokenizerConfigPath, "utf-8"),
);
doLowercase = configData.do_lower_case ?? true; doLowercase = configData.do_lower_case ?? true;
modelMaxLength = configData.model_max_length ?? 512; modelMaxLength = configData.model_max_length ?? 512;
} catch { } catch {
@@ -180,13 +182,20 @@ class BertTokenizer {
return text.split(/\s+/).filter((t) => t.length > 0); return text.split(/\s+/).filter((t) => t.length > 0);
} }
private wordpiece_tokenize(token: string, maxOutputTokens: number = 20): string[] { private wordpiece_tokenize(
token: string,
maxOutputTokens: number = 20,
): string[] {
const outputTokens: string[] = []; const outputTokens: string[] = [];
let isBad = false; let isBad = false;
let start = 0; let start = 0;
let subToken: string | null = null; let subToken: string | null = null;
while (start < token.length && !isBad && outputTokens.length < maxOutputTokens) { while (
start < token.length &&
!isBad &&
outputTokens.length < maxOutputTokens
) {
let found = false; let found = false;
for (let end = token.length; end > start; end--) { for (let end = token.length; end > start; end--) {
@@ -230,7 +239,10 @@ class BertTokenizer {
return tokens; return tokens;
} }
encode(text: string, maxLen: number = 128): { inputIds: number[]; attentionMask: number[] } { encode(
text: string,
maxLen: number = 128,
): { inputIds: number[]; attentionMask: number[] } {
const tokens = this.tokenize(text); const tokens = this.tokenize(text);
// Add [CLS] and [SEP] // Add [CLS] and [SEP]
@@ -252,12 +264,153 @@ class BertTokenizer {
// ── Model Loading ────────────────────────────────────────────────────────── // ── Model Loading ──────────────────────────────────────────────────────────
const MODEL_DIR_ENV = "SPAM_MODEL_DIR"; const MODEL_DIR_ENV = "SPAM_MODEL_DIR";
const DEFAULT_MODEL_DIR = path.join(__dirname, "..", "..", "models", "spam-classifier"); const DEFAULT_MODEL_DIR = path.join(
__dirname,
"..",
"..",
"models",
"spam-classifier",
);
function getModelDir(): string { function getModelDir(): string {
return process.env[MODEL_DIR_ENV] || DEFAULT_MODEL_DIR; return process.env[MODEL_DIR_ENV] || DEFAULT_MODEL_DIR;
} }
// ── Remote Model Download ────────────────────────────────────────────────────
const MODEL_DOWNLOAD_URL_ENV = "SPAM_MODEL_URL_BASE";
/** Model files that need to be available in the model directory. */
const MODEL_FILES = [
"model.onnx",
"model.onnx.data",
"tokenizer.json",
"vocab.txt",
"tokenizer_config.json",
"special_tokens_map.json",
"model_metadata.json",
] as const;
/**
* Check if all required model files exist in the given directory.
*/
function modelFilesExist(dir: string): boolean {
try {
return MODEL_FILES.every((f) => fs.existsSync(path.join(dir, f)));
} catch {
return false;
}
}
/**
* Download a single model file from a remote URL to a local path.
* Uses streaming to handle large files (e.g., model.onnx.data at 255MB).
*/
async function downloadModelFile(url: string, destPath: string): Promise<void> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to download ${url}: ${response.status} ${response.statusText}`,
);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error(`No response body stream for ${url}`);
}
// Ensure parent directory exists
const dir = path.dirname(destPath);
fs.mkdirSync(dir, { recursive: true });
// Stream to file
const writer = fs.createWriteStream(destPath);
try {
let totalBytes = 0;
let lastLog = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
writer.write(value);
totalBytes += value.length;
// Log progress every ~10MB
if (totalBytes - lastLog > 10 * 1024 * 1024) {
lastLog = totalBytes;
const mb = (totalBytes / (1024 * 1024)).toFixed(1);
console.log(
`[spamshield] Downloaded ${path.basename(destPath)}: ${mb}MB`,
);
}
}
} finally {
writer.end();
await new Promise<void>((resolve) => writer.on("finish", resolve));
}
const totalMB = (fs.statSync(destPath).size / (1024 * 1024)).toFixed(1);
console.log(
`[spamshield] Downloaded ${path.basename(destPath)} (${totalMB}MB)`,
);
}
/**
* Download all model files from a remote URL base to the model directory.
* Falls back gracefully — if the URL is not configured, returns false.
*/
async function downloadModelIfMissing(modelDir: string): Promise<boolean> {
// If model files already exist locally, nothing to do
if (modelFilesExist(modelDir)) {
return true;
}
const baseUrl = process.env[MODEL_DOWNLOAD_URL_ENV];
if (!baseUrl) {
console.log(
"[spamshield] Model files not found locally and SPAM_MODEL_URL_BASE not set — " +
"will use rule-engine fallback",
);
return false;
}
const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
console.log(`[spamshield] Downloading model from: ${normalizedBase}`);
// Ensure model directory exists
fs.mkdirSync(modelDir, { recursive: true });
// Track which files we already have (for caching across cold starts)
const existing = new Set<string>();
for (const file of MODEL_FILES) {
const filePath = path.join(modelDir, file);
if (fs.existsSync(filePath) && fs.statSync(filePath).size > 0) {
existing.add(file);
}
}
// Download missing files
for (const file of MODEL_FILES) {
if (existing.has(file)) {
console.log(`[spamshield] Already have ${file}, skipping download`);
continue;
}
const url = `${normalizedBase}${file}`;
const destPath = path.join(modelDir, file);
console.log(`[spamshield] Downloading ${file}...`);
try {
await downloadModelFile(url, destPath);
} catch (err) {
console.error(`[spamshield] Failed to download ${file}:`, err);
// If the main model files fail, we can't use the model
if (file === "model.onnx" || file === "model.onnx.data") {
throw err;
}
}
}
return modelFilesExist(modelDir);
}
async function loadModel(): Promise<void> { async function loadModel(): Promise<void> {
if (modelState.loaded) return; if (modelState.loaded) return;
@@ -265,6 +418,9 @@ async function loadModel(): Promise<void> {
const modelDir = getModelDir(); const modelDir = getModelDir();
console.log(`[spamshield] Loading ONNX model from: ${modelDir}`); console.log(`[spamshield] Loading ONNX model from: ${modelDir}`);
// Download model files if missing (production/Vercel path)
await downloadModelIfMissing(modelDir);
// Load metadata // Load metadata
const metadataPath = path.join(modelDir, "model_metadata.json"); const metadataPath = path.join(modelDir, "model_metadata.json");
if (fs.existsSync(metadataPath)) { if (fs.existsSync(metadataPath)) {
@@ -288,14 +444,21 @@ async function loadModel(): Promise<void> {
modelState.session = await ort.InferenceSession.create(modelPath); modelState.session = await ort.InferenceSession.create(modelPath);
console.log("[spamshield] ONNX session created"); console.log("[spamshield] ONNX session created");
console.log(`[spamshield] Inputs: ${modelState.session.inputNames.join(", ")}`); console.log(
console.log(`[spamshield] Outputs: ${modelState.session.outputNames.join(", ")}`); `[spamshield] Inputs: ${modelState.session.inputNames.join(", ")}`,
);
console.log(
`[spamshield] Outputs: ${modelState.session.outputNames.join(", ")}`,
);
modelState.loaded = true; modelState.loaded = true;
console.log("[spamshield] Model loaded successfully"); console.log("[spamshield] Model loaded successfully");
} catch (err) { } catch (err) {
modelState.loadError = err instanceof Error ? err : new Error(String(err)); modelState.loadError = err instanceof Error ? err : new Error(String(err));
console.error("[spamshield] Failed to load ONNX model:", modelState.loadError); console.error(
"[spamshield] Failed to load ONNX model:",
modelState.loadError,
);
console.log("[spamshield] Falling back to rule engine for classification"); console.log("[spamshield] Falling back to rule engine for classification");
} }
} }
@@ -351,7 +514,10 @@ async function runInference(
} }
const inputIdsTensor = new ort.Tensor("int64", inputIdsBigInt, [1, maxLen]); const inputIdsTensor = new ort.Tensor("int64", inputIdsBigInt, [1, maxLen]);
const attentionMaskTensor = new ort.Tensor("int64", attentionMaskBigInt, [1, maxLen]); const attentionMaskTensor = new ort.Tensor("int64", attentionMaskBigInt, [
1,
maxLen,
]);
// Run inference // Run inference
const feeds: Record<string, Tensor> = { const feeds: Record<string, Tensor> = {

View File

@@ -37,10 +37,7 @@ export async function createUserWithPassword(
return { user, sessionToken: session.sessionToken, accessToken }; return { user, sessionToken: session.sessionToken, accessToken };
} }
export async function authenticateUser( export async function authenticateUser(email: string, password: string) {
email: string,
password: string,
) {
const [user] = await db const [user] = await db
.select() .select()
.from(users) .from(users)
@@ -67,149 +64,9 @@ export async function authenticateUser(
return { user, sessionToken: session.sessionToken, accessToken }; return { user, sessionToken: session.sessionToken, accessToken };
} }
const GOOGLE_ISSUER = "https://accounts.google.com";
const APPLE_ISSUER = "https://appleid.apple.com"; const APPLE_ISSUER = "https://appleid.apple.com";
const APPLE_JWKS_URL = new URL("https://appleid.apple.com/auth/keys"); const APPLE_JWKS_URL = new URL("https://appleid.apple.com/auth/keys");
/**
* Verifies a Google ID token using firebase-admin and returns the user.
* If the user does not exist, creates a new account.
* If the user exists but has not linked Google, links the provider.
*/
export async function authenticateWithGoogle(idToken: string) {
const { initializeApp, cert, getApps } = await import("firebase-admin/app");
// Initialize Firebase Admin if not already done
if (getApps().length === 0) {
// Try to load from environment or use application default credentials
const projectId = process.env.FIREBASE_PROJECT_ID;
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
const privateKey = process.env.FIREBASE_PRIVATE_KEY;
if (projectId && clientEmail && privateKey) {
initializeApp({
credential: cert({
projectId,
clientEmail,
privateKey: privateKey.replace(/\\n/g, "\n"),
}),
});
} else {
// Fall back to application default credentials
initializeApp({ projectId: projectId ?? "kordant" });
}
}
let decodedToken: { uid: string; email?: string; name?: string; picture?: string };
try {
const authModule = await import("firebase-admin/auth");
decodedToken = await authModule.getAuth().verifyIdToken(idToken);
} catch (err) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Invalid Google ID token",
});
}
const googleUserId = decodedToken.uid;
const email = decodedToken.email;
const name = decodedToken.name ?? email?.split("@")[0] ?? "User";
const avatarUrl = decodedToken.picture ?? null;
if (!email) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Google account has no email address",
});
}
// Check if this Google account is already linked
const [existingAccount] = await db
.select()
.from(accounts)
.where(
and(
eq(accounts.provider, "google"),
eq(accounts.providerAccountId, googleUserId),
),
)
.limit(1);
let userId: string;
let isNewUser = false;
if (existingAccount) {
// Already linked — use the existing user
userId = existingAccount.userId;
isNewUser = false;
// Update the access token if provided
await db
.update(accounts)
.set({
accessToken: idToken,
updatedAt: new Date(),
})
.where(eq(accounts.id, existingAccount.id));
} else {
// Not linked — check if a user with this email exists
const [existingUserByEmail] = await db
.select()
.from(users)
.where(and(eq(users.email, email), isNull(users.deletedAt)))
.limit(1);
if (existingUserByEmail) {
// Link Google to existing user
userId = existingUserByEmail.id;
isNewUser = false;
await db.insert(accounts).values({
userId,
provider: "google",
providerAccountId: googleUserId,
accessToken: idToken,
});
// Update avatar if not set
if (!existingUserByEmail.image && avatarUrl) {
await db.update(users).set({ image: avatarUrl }).where(eq(users.id, userId));
}
} else {
// Create new user with Google
isNewUser = true;
const [newUser] = await db
.insert(users)
.values({
name,
email,
image: avatarUrl,
emailVerified: new Date(),
})
.returning();
userId = newUser.id;
await db.insert(accounts).values({
userId,
provider: "google",
providerAccountId: googleUserId,
accessToken: idToken,
});
}
}
// Create session and JWT
const session = await createSession(userId);
const accessToken = await signJWT({ sub: userId }, { expiresIn: "7d" });
const refreshToken = await signJWT({ sub: userId, type: "refresh" }, { expiresIn: "30d" });
const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
if (!user) {
throw new TRPCError({ code: "NOT_FOUND", message: "User not found after creation" });
}
return { user, sessionToken: session.sessionToken, accessToken, refreshToken, isNewUser };
}
/** /**
* Verifies an Apple identity token and authenticates the user. * Verifies an Apple identity token and authenticates the user.
* If the user does not exist, creates a new account. * If the user does not exist, creates a new account.
@@ -228,14 +85,18 @@ export async function authenticateWithApple(
} }
// Verify Apple ID token using Apple's JWKS // Verify Apple ID token using Apple's JWKS
let payload: { sub: string; email?: string; is_private_email?: string; }; let payload: { sub: string; email?: string; is_private_email?: string };
try { try {
const JWKS = createRemoteJWKSet(APPLE_JWKS_URL); const JWKS = createRemoteJWKSet(APPLE_JWKS_URL);
const result = await jwtVerify(identityToken, JWKS, { const result = await jwtVerify(identityToken, JWKS, {
issuer: APPLE_ISSUER, issuer: APPLE_ISSUER,
audience: process.env.IOS_BUNDLE_ID ?? "com.frenocorp.kordant", audience: process.env.IOS_BUNDLE_ID ?? "com.frenocorp.kordant",
}); });
payload = result.payload as unknown as { sub: string; email?: string; is_private_email?: string; }; payload = result.payload as unknown as {
sub: string;
email?: string;
is_private_email?: string;
};
} catch (err) { } catch (err) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
@@ -331,14 +192,30 @@ export async function authenticateWithApple(
// Create session and JWT // Create session and JWT
const session = await createSession(userId); const session = await createSession(userId);
const accessToken = await signJWT({ sub: userId }, { expiresIn: "7d" }); const accessToken = await signJWT({ sub: userId }, { expiresIn: "7d" });
const refreshToken = await signJWT({ sub: userId, type: "refresh" }, { expiresIn: "30d" }); const refreshToken = await signJWT(
{ sub: userId, type: "refresh" },
{ expiresIn: "30d" },
);
const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1); const [user] = await db
.select()
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user) { if (!user) {
throw new TRPCError({ code: "NOT_FOUND", message: "User not found after creation" }); throw new TRPCError({
code: "NOT_FOUND",
message: "User not found after creation",
});
} }
return { user, sessionToken: session.sessionToken, accessToken, refreshToken, isNewUser }; return {
user,
sessionToken: session.sessionToken,
accessToken,
refreshToken,
isNewUser,
};
} }
/** /**
@@ -379,7 +256,10 @@ export async function refreshAccessToken(refreshToken: string) {
} }
const newAccessToken = await signJWT({ sub: userId }, { expiresIn: "7d" }); const newAccessToken = await signJWT({ sub: userId }, { expiresIn: "7d" });
const newRefreshToken = await signJWT({ sub: userId, type: "refresh" }, { expiresIn: "30d" }); const newRefreshToken = await signJWT(
{ sub: userId, type: "refresh" },
{ expiresIn: "30d" },
);
return { accessToken: newAccessToken, refreshToken: newRefreshToken }; return { accessToken: newAccessToken, refreshToken: newRefreshToken };
} }
@@ -461,9 +341,7 @@ export async function resetPassword(token: string, newPassword: string) {
*/ */
export async function revokeUserSessions(userId: string) { export async function revokeUserSessions(userId: string) {
const { sessions } = await import("~/server/db/schema/auth"); const { sessions } = await import("~/server/db/schema/auth");
await db await db.delete(sessions).where(eq(sessions.userId, userId));
.delete(sessions)
.where(eq(sessions.userId, userId));
return { success: true }; return { success: true };
} }

8
web/vercel.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"framework": "solidstart",
"buildCommand": "npm run build",
"installCommand": "bun install",
"outputDirectory": ".output/public",
"regions": ["iad1"]
}