Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: vercel log drains 📝 (#272)
Maximilian Kaskeeeb14ec6e4a8
diff --git a/.eslintrc.cjs b/.eslintrc.cjsindex f17447442..d4947918c 100644--- a/.eslintrc.cjs+++ b/.eslintrc.cjs@@ -6,10 +6,7 @@ const config = {parserOptions: {ecmaVersion: "latest",tsconfigRootDir: __dirname,- project: [- "./apps/*/tsconfig.json",- "./packages/*/tsconfig.json",- ],+ project: ["./apps/*/tsconfig.json", "./packages/**/*/tsconfig.json"],},settings: {next: {@@ -18,4 +15,4 @@ const config = {},};-module.exports = config;\ No newline at end of file+module.exports = config;diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex e9d2aab0f..05586dcae 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -52,3 +52,13 @@ VERCEL_AUTH_BEARER_TOKEN=NEXT_PUBLIC_URL=NEXT_PUBLIC_SENTRY_DSN=''++# Vercel Log Drains+INTEGRATION_SECRET=+LOG_DRAIN_SECRET=++# Marketplace Integration+VERCEL_CLIENT_ID=+VERCEL_CLIENT_SECRET=+VERCEL_REDIRECT_URI=+AES_KEY=\ No newline at end of filediff --git a/apps/web/package.json b/apps/web/package.jsonindex 00c161257..5fae4b2a8 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -19,6 +19,7 @@"@openstatus/plans": "workspace:*","@openstatus/tinybird": "workspace:*","@openstatus/upstash": "workspace:*",+ "@openstatus/vercel": "workspace:*","@radix-ui/react-accordion": "1.1.2","@radix-ui/react-alert-dialog": "1.0.4","@radix-ui/react-avatar": "^1.0.3",diff --git a/apps/web/src/app/api/integrations/vercel/callback/route.ts b/apps/web/src/app/api/integrations/vercel/callback/route.tsnew file mode 100644index 000000000..ab1d3263b--- /dev/null+++ b/apps/web/src/app/api/integrations/vercel/callback/route.ts@@ -0,0 +1 @@+export { GET } from "@openstatus/vercel/src/routes/callback";diff --git a/apps/web/src/app/api/integrations/vercel/configure/page.ts b/apps/web/src/app/api/integrations/vercel/configure/page.tsnew file mode 100644index 000000000..a0c36fb6e--- /dev/null+++ b/apps/web/src/app/api/integrations/vercel/configure/page.ts@@ -0,0 +1,3 @@+import { Configure } from "@openstatus/vercel";++export default Configure;diff --git a/apps/web/src/app/api/integrations/vercel/route.ts b/apps/web/src/app/api/integrations/vercel/route.tsnew file mode 100644index 000000000..f5c63b50c--- /dev/null+++ b/apps/web/src/app/api/integrations/vercel/route.ts@@ -0,0 +1 @@+export { config, POST } from "@openstatus/vercel/src/routes/webhook";diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/loading.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/loading.tsxnew file mode 100644index 000000000..86c23b149--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/loading.tsx@@ -0,0 +1,17 @@+import { Header } from "@/components/dashboard/header";+import { Skeleton } from "@/components/ui/skeleton";++export default function Loading() {+ return (+ <div className="grid gap-6 md:grid-cols-1 md:gap-8">+ <div className="col-span-full flex w-full justify-between">+ <Header.Skeleton>+ <Skeleton className="h-9 w-20" />+ </Header.Skeleton>+ </div>+ <Skeleton className="h-4 w-24" />+ <Skeleton className="h-48 w-full" />+ <Skeleton className="h-48 w-full" />+ </div>+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsxnew file mode 100644index 000000000..3b76367a8--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsx@@ -0,0 +1,44 @@+"use client";++import * as React from "react";++import { Container } from "@/components/dashboard/container";+import { Header } from "@/components/dashboard/header";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { api } from "@/trpc/client";++export default async function IncidentPage({+ params,+}: {+ params: { workspaceSlug: string };+}) {+ const workspace = await api.workspace.getWorkspace.query({+ slug: params.workspaceSlug,+ });++ return (+ <div className="grid gap-6 md:grid-cols-2 md:gap-8">+ <Header title="Integrations" description="All our integrations"></Header>++ <Container+ title="Vercel"+ key={"vercel"}+ description="Connect your Vercel Project get insights."+ actions={[+ <a+ href={+ workspace?.id === 1+ ? "https://vercel.com/integrations/openstatus-staging/new"+ : "#"+ }+ target="_blank"+ key={"vercel"}+ >+ <Button>{workspace?.id === 1 ? "Configure" : "Coming soon"}</Button>+ </a>,+ ]}+ ></Container>+ </div>+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/vercel/configure/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/vercel/configure/page.tsxnew file mode 100644index 000000000..75d104cb9--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/vercel/configure/page.tsx@@ -0,0 +1,122 @@+import { revalidatePath } from "next/cache";+import { cookies } from "next/headers";+import { redirect } from "next/navigation";++import { SubmitButton } from "@openstatus/vercel/src/components/submit-button";+import {+ createLogDrain,+ deleteLogDrain,+ getLogDrains,+ getProjects,+} from "@openstatus/vercel/src/libs/client";+import { decrypt } from "@openstatus/vercel/src/libs/crypto";++import { api } from "@/trpc/server";++export default async function Configure({+ params,+}: {+ params: { workspaceSlug: string };+}) {+ const iv = cookies().get("iv")?.value;+ const encryptedToken = cookies().get("token")?.value;+ const teamId = cookies().get("teamId")?.value;++ if (!iv || !encryptedToken) {+ /** Redirect to access new token */+ return redirect("/app");+ }++ const token = decrypt(+ Buffer.from(iv || "", "base64url"),+ Buffer.from(encryptedToken || "", "base64url"),+ ).toString();++ let logDrains = await getLogDrains(token, teamId);++ const projects = await getProjects(token, teamId);++ for (const project of projects.projects) {+ console.log({ project });+ console.log("create integration");+ console.log(project.id);+ api.integration.createIntegration.mutate({+ workspaceSlug: params.workspaceSlug,+ input: {+ name: "Vercel",+ data: JSON.stringify(project),+ externalId: project.id,+ },+ });+ }+ // Create integration project if it doesn't exist++ if (logDrains.length === 0) {+ logDrains = [+ await createLogDrain(+ token,+ // @ts-expect-error We need more data - but this is a demo+ {+ deliveryFormat: "json",+ name: "OpenStatus Log Drain",+ // TODO: update with correct url+ url: "https://6be9-2a0d-3344-2324-1e04-4dc7-d06a-a389-48c0.ngrok-free.app/api/integrations/vercel",+ sources: ["static", "lambda", "build", "edge", "external"],+ // headers: { "key": "value"}+ },+ teamId,+ ),+ ];+ }++ // TODO: automatically create log drain on installation+ // async function create(formData: FormData) {+ // "use server";+ // await createLogDrain(+ // token,+ // // @ts-expect-error We need more data - but this is a demo+ // {+ // deliveryFormat: "json",+ // name: "OpenStatus Log Drain",+ // // TODO: update with correct url+ // url: "https://6be9-2a0d-3344-2324-1e04-4dc7-d06a-a389-48c0.ngrok-free.app/api/integrations/vercel",+ // sources: ["static", "lambda", "edge", "external"],+ // // headers: { "key": "value"}+ // },+ // teamId,+ // );+ // revalidatePath("/");+ // }++ async function _delete(formData: FormData) {+ "use server";+ const id = formData.get("id")?.toString();+ console.log({ id });+ if (id) {+ await deleteLogDrain(token, id, String(teamId));+ revalidatePath("/");+ }+ }++ return (+ <div className="flex w-full flex-col items-center justify-center">+ <div className="border-border m-3 grid w-full max-w-xl gap-3 rounded-lg border p-6 backdrop-blur-[2px]">+ <h1 className="font-cal text-2xl">Configure Vercel Integration</h1>+ <ul>+ {logDrains.map((item) => (+ <li+ key={item.id}+ className="flex items-center justify-between gap-2"+ >+ <p>{item.name}</p>+ <form action={_delete}>+ <input name="id" value={item.id} className="hidden" />+ <SubmitButton>Remove integration</SubmitButton>+ </form>+ </li>+ ))}+ </ul>+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsxindex cd1940e07..03bcaadd3 100644--- a/apps/web/src/components/icons.tsx+++ b/apps/web/src/components/icons.tsx@@ -9,6 +9,7 @@ import {MessageCircle,PanelTop,Pencil,+ Plug,Search,SearchCheck,Siren,@@ -42,6 +43,7 @@ export const Icons = {trash: Trash,twitter: TwitterIcon,globe: Globe,+ plug: Plug,discord: ({ ...props }: LucideProps) => (<svg viewBox="0 0 640 512" {...props}><pathdiff --git a/apps/web/src/config/pages.ts b/apps/web/src/config/pages.tsindex bd7711bcd..45699dadd 100644--- a/apps/web/src/config/pages.ts+++ b/apps/web/src/config/pages.ts@@ -28,5 +28,11 @@ export const pagesConfig: Page[] = [href: "/incidents",icon: "siren",},+ {+ title: "Integrations",+ description: "Where you can see all the integrations.",+ href: "/integrations",+ icon: "plug",+ },// ...];diff --git a/apps/web/src/env.ts b/apps/web/src/env.tsindex da7769001..0550edb12 100644--- a/apps/web/src/env.ts+++ b/apps/web/src/env.ts@@ -3,6 +3,7 @@ import { z } from "zod";import "@openstatus/db/env.mjs";import "@openstatus/analytics/env";+import "@openstatus/vercel/env";export const env = createEnv({server: {diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.tsindex 675e1e954..1accb3cd5 100644--- a/apps/web/src/middleware.ts+++ b/apps/web/src/middleware.ts@@ -42,6 +42,9 @@ export const getValidSubdomain = (host?: string | null) => {subdomain = candidate;}}+ if (host && host.includes("ngrok-free.app")) {+ return null;+ }// In case the host is a custom domainif (host &&@@ -73,6 +76,7 @@ export default authMiddleware({],ignoredRoutes: ["/api/og", "/discord", "github"], // FIXME: we should check the `publicRoutes`beforeAuth: before,+ debug: false,async afterAuth(auth, req) {// handle users who aren't authenticatedif (!auth.userId && !auth.isPublicRoute) {@@ -112,10 +116,42 @@ export default authMiddleware({return NextResponse.redirect(orgSelection);}} else {+ console.log("redirecting to onboarding");// return NextResponse.redirect(new URL("/app/onboarding", req.url));// probably redirect to onboarding// or find a way to wait for the webhook}+ console.log("redirecting to onboarding");+ return;+ }+ if (+ auth.userId &&+ req.nextUrl.pathname === "/app/integrations/vercel/configure"+ ) {+ const userQuery = db+ .select()+ .from(user)+ .where(eq(user.tenantId, auth.userId))+ .as("userQuery");+ const result = await db+ .select()+ .from(usersToWorkspaces)+ .innerJoin(userQuery, eq(userQuery.id, usersToWorkspaces.userId))+ .all();+ if (result.length > 0) {+ const currentWorkspace = await db+ .select()+ .from(workspace)+ .where(eq(workspace.id, result[0].users_to_workspaces.workspaceId))+ .get();+ if (currentWorkspace) {+ const configure = new URL(+ `/app/${currentWorkspace.slug}/integrations/vercel/configure`,+ req.url,+ );+ return NextResponse.redirect(configure);+ }+ }}},});@@ -124,6 +160,7 @@ export const config = {matcher: ["/((?!api|assets|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)","/",+ "/app/integrations/vercel/configure","/(api/webhook|api/trpc)(.*)","/(!api/checker/:path*|!api/og|!api/ping)",],diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.tsindex 9ba8a7156..05e1d38e4 100644--- a/apps/web/tailwind.config.ts+++ b/apps/web/tailwind.config.ts@@ -3,7 +3,11 @@ const { fontFamily } = require("tailwindcss/defaultTheme");/** @type {import('tailwindcss').Config} */module.exports = {darkMode: ["class"],- content: ["src/**/*.{ts,tsx}"],+ content: [+ "src/**/*.{ts,tsx}",+ // for vercel integration+ "../../packages/integrations/**/*.{ts,tsx}",+ ],theme: {container: {center: true,diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.tsindex 543d580e6..4da56f544 100644--- a/packages/api/src/edge.ts+++ b/packages/api/src/edge.ts@@ -1,5 +1,6 @@import { domainRouter } from "./router/domain";import { incidentRouter } from "./router/incident";+import { integrationRouter } from "./router/integration";import { monitorRouter } from "./router/monitor";import { pageRouter } from "./router/page";import { workspaceRouter } from "./router/workspace";@@ -12,4 +13,5 @@ export const edgeRouter = createTRPCRouter({page: pageRouter,incident: incidentRouter,domain: domainRouter,+ integration: integrationRouter,});diff --git a/packages/api/src/router/integration.ts b/packages/api/src/router/integration.tsnew file mode 100644index 000000000..ec5e27907--- /dev/null+++ b/packages/api/src/router/integration.ts@@ -0,0 +1,44 @@+import { z } from "zod";++import { and, eq, inArray } from "@openstatus/db";+import {+ insertIntegrationSchema,+ integration,+} from "@openstatus/db/src/schema";++import { createTRPCRouter, protectedProcedure } from "../trpc";+import { hasUserAccessToWorkspace } from "./utils";++export const integrationRouter = createTRPCRouter({+ createIntegration: protectedProcedure+ .input(+ z.object({ workspaceSlug: z.string(), input: insertIntegrationSchema }),+ )+ .mutation(async (opts) => {+ const result = await hasUserAccessToWorkspace({+ workspaceSlug: opts.input.workspaceSlug,+ ctx: opts.ctx,+ });+ if (!result) return;++ const exists = await opts.ctx.db+ .select()+ .from(integration)+ .where(+ and(+ eq(integration.workspaceId, result.workspace.id),+ eq(integration.externalId, opts.input.input.externalId),+ ),+ )+ .get();++ if (exists) {+ return;+ }+ await opts.ctx.db+ .insert(integration)+ .values({ ...opts.input.input, workspaceId: result.workspace.id })+ .returning()+ .get();+ }),+});diff --git a/packages/db/drizzle/0007_complex_frog_thor.sql b/packages/db/drizzle/0007_complex_frog_thor.sqlnew file mode 100644index 000000000..63d91186c--- /dev/null+++ b/packages/db/drizzle/0007_complex_frog_thor.sql@@ -0,0 +1,11 @@+CREATE TABLE `integration` (+ `id` integer PRIMARY KEY NOT NULL,+ `name` text(256) NOT NULL,+ `workspace_id` integer,+ `credential` text,+ `external_id` text NOT NULL,+ `created_at` integer DEFAULT (strftime('%s', 'now')),+ `updated_at` integer DEFAULT (strftime('%s', 'now')),+ `data` text NOT NULL,+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE no action+);diff --git a/packages/db/drizzle/meta/0006_snapshot.json b/packages/db/drizzle/meta/0006_snapshot.jsonindex 53519fa69..0197ddf75 100644--- a/packages/db/drizzle/meta/0006_snapshot.json+++ b/packages/db/drizzle/meta/0006_snapshot.json@@ -58,12 +58,8 @@"name": "incident_workspace_id_workspace_id_fk","tableFrom": "incident","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -132,12 +128,8 @@"name": "incident_update_incident_id_incident_id_fk","tableFrom": "incident_update","tableTo": "incident",- "columnsFrom": [- "incident_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["incident_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -169,12 +161,8 @@"name": "incidents_to_monitors_monitor_id_monitor_id_fk","tableFrom": "incidents_to_monitors","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -182,22 +170,15 @@"name": "incidents_to_monitors_incident_id_incident_id_fk","tableFrom": "incidents_to_monitors","tableTo": "incident",- "columnsFrom": [- "incident_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["incident_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"incidents_to_monitors_monitor_id_incident_id_pk": {- "columns": [- "incident_id",- "monitor_id"- ]+ "columns": ["incident_id", "monitor_id"]}},"uniqueConstraints": {}@@ -283,9 +264,7 @@"indexes": {"page_slug_unique": {"name": "page_slug_unique",- "columns": [- "slug"- ],+ "columns": ["slug"],"isUnique": true}},@@ -294,12 +273,8 @@"name": "page_workspace_id_workspace_id_fk","tableFrom": "page","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -398,7 +373,7 @@},"method": {"name": "method",- "type": "text(5)",+ "type": "text(2)","primaryKey": false,"notNull": false,"autoincrement": false,@@ -434,12 +409,8 @@"name": "monitor_workspace_id_workspace_id_fk","tableFrom": "monitor","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -471,12 +442,8 @@"name": "monitors_to_pages_monitor_id_monitor_id_fk","tableFrom": "monitors_to_pages","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -484,22 +451,15 @@"name": "monitors_to_pages_page_id_page_id_fk","tableFrom": "monitors_to_pages","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"monitors_to_pages_monitor_id_page_id_pk": {- "columns": [- "monitor_id",- "page_id"- ]+ "columns": ["monitor_id", "page_id"]}},"uniqueConstraints": {}@@ -573,9 +533,7 @@"indexes": {"user_tenant_id_unique": {"name": "user_tenant_id_unique",- "columns": [- "tenant_id"- ],+ "columns": ["tenant_id"],"isUnique": true}},@@ -607,12 +565,8 @@"name": "users_to_workspaces_user_id_user_id_fk","tableFrom": "users_to_workspaces","tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -620,22 +574,15 @@"name": "users_to_workspaces_workspace_id_workspace_id_fk","tableFrom": "users_to_workspaces","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}},"compositePrimaryKeys": {"users_to_workspaces_user_id_workspace_id_pk": {- "columns": [- "user_id",- "workspace_id"- ]+ "columns": ["user_id", "workspace_id"]}},"uniqueConstraints": {}@@ -719,16 +666,12 @@"indexes": {"workspace_slug_unique": {"name": "workspace_slug_unique",- "columns": [- "slug"- ],+ "columns": ["slug"],"isUnique": true},"workspace_stripe_id_unique": {"name": "workspace_stripe_id_unique",- "columns": [- "stripe_id"- ],+ "columns": ["stripe_id"],"isUnique": true}},@@ -743,4 +686,4 @@"tables": {},"columns": {}}-}\ No newline at end of file+}diff --git a/packages/db/drizzle/meta/0007_snapshot.json b/packages/db/drizzle/meta/0007_snapshot.jsonnew file mode 100644index 000000000..2bdda4dbe--- /dev/null+++ b/packages/db/drizzle/meta/0007_snapshot.json@@ -0,0 +1,827 @@+{+ "version": "5",+ "dialect": "sqlite",+ "id": "23bfc90d-3bb1-4077-81d8-8f2e874f9c62",+ "prevId": "fee77e21-b52b-49c0-b109-5ccc37821935",+ "tables": {+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text(4)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "incident_update": {+ "name": "incident_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text(4)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incident_update_incident_id_incident_id_fk": {+ "name": "incident_update_incident_id_incident_id_fk",+ "tableFrom": "incident_update",+ "tableTo": "incident",+ "columnsFrom": [+ "incident_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "incidents_to_monitors": {+ "name": "incidents_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incidents_to_monitors_monitor_id_monitor_id_fk": {+ "name": "incidents_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "incidents_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "incidents_to_monitors_incident_id_incident_id_fk": {+ "name": "incidents_to_monitors_incident_id_incident_id_fk",+ "tableFrom": "incidents_to_monitors",+ "tableTo": "incident",+ "columnsFrom": [+ "incident_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "incidents_to_monitors_monitor_id_incident_id_pk": {+ "columns": [+ "incident_id",+ "monitor_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text(6)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'inactive'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "monitors_to_pages": {+ "name": "monitors_to_pages",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitors_to_pages_monitor_id_monitor_id_fk": {+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitors_to_pages_page_id_page_id_fk": {+ "name": "monitors_to_pages_page_id_page_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitors_to_pages_monitor_id_page_id_pk": {+ "columns": [+ "monitor_id",+ "page_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ }+ },+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 33e867592..c514a6eed 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -50,6 +50,13 @@"when": 1692646649111,"tag": "0006_tired_anita_blake","breakpoints": true+ },+ {+ "idx": 7,+ "version": "5",+ "when": 1694362217174,+ "tag": "0007_complex_frog_thor",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex b8416531a..ba9e25d4c 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -1,4 +1,5 @@export * from "./incident";+export * from "./integration";export * from "./page";export * from "./monitor";export * from "./user";diff --git a/packages/db/src/schema/integration.ts b/packages/db/src/schema/integration.tsnew file mode 100644index 000000000..e8109ade3--- /dev/null+++ b/packages/db/src/schema/integration.ts@@ -0,0 +1,28 @@+import { sql } from "drizzle-orm";+import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";+import { createInsertSchema, createSelectSchema } from "drizzle-zod";++import { workspace } from "./workspace";++export const integration = sqliteTable("integration", {+ id: integer("id").primaryKey(),+ name: text("name", { length: 256 }).notNull(), // Should be vercel or other++ workspaceId: integer("workspace_id").references(() => workspace.id),++ // Not used yet but we might need to get store something for the integration webhook url and or secret+ credential: text("credential", { mode: "json" }),++ externalId: text("external_id").notNull(), // the id of the integration in the external service++ createdAt: integer("created_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),+ updatedAt: integer("updated_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),++ data: text("data", { mode: "json" }).notNull(),+});++export const insertIntegrationSchema = createInsertSchema(integration);diff --git a/packages/integrations/vercel/.env.example b/packages/integrations/vercel/.env.examplenew file mode 100644index 000000000..ef6628e12--- /dev/null+++ b/packages/integrations/vercel/.env.example@@ -0,0 +1,12 @@+# Log Drains+# add from the first form - 'x-vercel-verify'+INTEGRATION_SECRET=+# after verify, in the modal box - 'x-vercel-signature'+LOG_DRAIN_SECRET=+++# Marketplace Integration+VERCEL_CLIENT_ID=+VERCEL_CLIENT_SECRET=+VERCEL_REDIRECT_URI=+AES_KEY=\ No newline at end of filediff --git a/packages/integrations/vercel/README.md b/packages/integrations/vercel/README.mdnew file mode 100644index 000000000..0fe7a2bcd--- /dev/null+++ b/packages/integrations/vercel/README.md@@ -0,0 +1,60 @@+# Log drain integration for Vercel++Seamless installement into Vercel's log drains for your project.++> Inspired by+> [@valeriangalliat/vercel-custom-log-drain](https://github.com/valeriangalliat/vercel-custom-log-drain).++## Description++When integrating the Vercel App into your project. Every request to+[openstatus.dev](https://openstatus.dev) will include the key inside of the+`Headers`.++Once we have the `access_token` token we will be able to `createLogDrain` as+authentificated user. The token is only expires after 30 minutes and is required+for the user to access the integration within vercel.++When creating the log drain, we should include a custom header to it, with an+`OpenStatus-Vercel-TOKEN: "os_xxx-yyy"` token from Unkey. That way, it is easy+to revoke tokens. We can test without but should include it. Check with Andreas+how a good use case an look like.++The new created log drain will point towards our `/api/integrations/vercel`. We+will then be able to filter them and ingest Tinybird the the logs we want to+keep. Maybe, we can start first by ingesting only errors.++1. We can start simple an only create the log drain for the user. nothing else+2. Once clear we will have to create a little `/configure` page where the user,+ authentificated within vercel, can update the log drain integration easily.++The UI for the Integration should be the bare minimum. The UX should be in the+focus. Default shadcn/ui components will do it.++- white background+- `DataTable` filled with `getLogDrains` data:+ - createdAt+ - name+ - projectId+ - dropdown menu: data can be deleted+- 'Connect'-button to add log drains to different projet++<!-- Redirect URL aka callback explaination -->++### Files++- `webhook.ts`: ingests Tinybird with the log drains+- `callback.ts`: callback for getting an access token+- `configure.ts`: simple page to configure your vercel integration authorized as+ vercel user through access token+- `client.ts`: includes all important REST API calls to vercel, updating the+ users project++### API Scopes++The following scopes are necessary:++- Log Drains (Read/Write): be able to send a request with the payload+- Projects (Read): connect log drains with projects++> We might require more scopes.diff --git a/packages/integrations/vercel/env.ts b/packages/integrations/vercel/env.tsnew file mode 100644index 000000000..da33d360a--- /dev/null+++ b/packages/integrations/vercel/env.ts@@ -0,0 +1,13 @@+import { createEnv } from "@t3-oss/env-core";+import { z } from "zod";++export const env = createEnv({+ server: {+ INTEGRATION_SECRET: z.string().min(1),+ TINY_BIRD_API_KEY: z.string().min(1),+ },+ runtimeEnv: {+ INTEGRATION_SECRET: process.env.INTEGRATION_SECRET,+ TINY_BIRD_API_KEY: process.env.TINY_BIRD_API_KEY,+ },+});diff --git a/packages/integrations/vercel/package.json b/packages/integrations/vercel/package.jsonnew file mode 100644index 000000000..a6e475aca--- /dev/null+++ b/packages/integrations/vercel/package.json@@ -0,0 +1,21 @@+{+ "name": "@openstatus/vercel",+ "version": "0.0.0",+ "main": "src/index.ts",+ "description": "Log drains Vercel integration.",+ "dependencies": {+ "@openstatus/tinybird": "workspace:*",+ "@t3-oss/env-core": "0.6.0",+ "react": "18.2.0",+ "react-dom": "18.2.0",+ "zod": "^3.21.4"+ },+ "devDependencies": {+ "@types/node": "20.3.1",+ "@types/react": "18.2.12",+ "@types/react-dom": "18.2.5",+ "next": "13.4.12",+ "tsconfig": "workspace:*",+ "typescript": "5.1.6"+ }+}diff --git a/packages/integrations/vercel/src/components/integration-card.tsx b/packages/integrations/vercel/src/components/integration-card.tsxnew file mode 100644index 000000000..e39bbf67a--- /dev/null+++ b/packages/integrations/vercel/src/components/integration-card.tsx@@ -0,0 +1,3 @@+export const VercelIntegrationCard = () => {+ return <></>;+};diff --git a/packages/integrations/vercel/src/components/submit-button.tsx b/packages/integrations/vercel/src/components/submit-button.tsxnew file mode 100644index 000000000..9fa2a9328--- /dev/null+++ b/packages/integrations/vercel/src/components/submit-button.tsx@@ -0,0 +1,22 @@+"use client";++import { experimental_useFormStatus as useFormStatus } from "react-dom";++export function SubmitButton({+ disabled,+ children,+}: {+ disabled?: boolean;+ children: React.ReactNode;+}) {+ const { pending } = useFormStatus();+ return (+ <button+ type="submit"+ disabled={pending || disabled}+ className="bg-foreground text-background rounded-md px-2 py-1 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {pending ? "Loading" : children}+ </button>+ );+}diff --git a/packages/integrations/vercel/src/index.ts b/packages/integrations/vercel/src/index.tsnew file mode 100644index 000000000..8526d383c--- /dev/null+++ b/packages/integrations/vercel/src/index.ts@@ -0,0 +1,4 @@+export * from "./libs/schema";+export * from "./routes/webhook";+export * from "./routes/callback";+export * from "./pages/configure";diff --git a/packages/integrations/vercel/src/libs/client.ts b/packages/integrations/vercel/src/libs/client.tsnew file mode 100644index 000000000..f5c3160c1--- /dev/null+++ b/packages/integrations/vercel/src/libs/client.ts@@ -0,0 +1,157 @@+// CREDITS: https://github.com/valeriangalliat/vercel-custom-log-drain/blob/43043c095475c9fac279e5fec8976497ee1ea9b6/clients/vercel.ts++import { projectsSchema } from "./schema";++async function fetchOk(+ url: string,+ init?: RequestInit | undefined,+): Promise<Response> {+ const res = await fetch(url, init);++ if (!res.ok) {+ const contentType = res.headers.get("content-type");+ let body: string | object | null;++ try {+ const isJson = contentType && contentType.includes("json");+ body = await (isJson ? res.json() : res.text());+ } catch (err) {+ body = null;+ }++ console.log({ body });++ throw Object.assign(new Error(`Failed to fetch: ${url}`), {+ res,+ body,+ });+ }++ return res;+}++const base = "https://api.vercel.com";++export async function getToken(code: string): Promise<string> {+ const url = `${base}/v2/oauth/access_token`;++ const res = await fetchOk(url, {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ client_id: process.env.VERCEL_CLIENT_ID || "",+ client_secret: process.env.VERCEL_CLIENT_SECRET || "",+ code,+ redirect_uri: process.env.VERCEL_REDIRECT_URI || "",+ }),+ });++ const json = await res.json();++ return json.access_token;+}++// Type from <https://vercel.com/docs/log-drains>+export type LogDrain = {+ /** The oauth2 client application id that created this log drain */+ clientId: string;+ /** The client configuration this log drain was created with */+ configurationId: string;+ /** A timestamp that tells you when the log drain was created */+ createdAt: number;+ /** The unique identifier of the log drain. Always prefixed with `ld_` */+ id: string;+ /** The type of log format */+ deliveryFormat: "json" | "ndjson" | "syslog";+ /** The name of the log drain */+ name: string;+ /** The identifier of the team or user whose events will trigger the log drain */+ ownerId: string;+ /** The identifier of the project this log drain is associated with */+ projectId?: string | null;+ /** The URL to call when logs are generated */+ url: string;+ /** TODO: add correct description and check if correct */+ headers?: Record<string, string>;+ /** The sources from which logs are currently being delivered to this log drain */+ sources?: (+ | "static"+ | "lambda"+ | "build"+ | "edge"+ | "external"+ | "deployment"+ )[]; // REMINDER: creating a log drain with "deployment" source won't work+};++function getQuery(teamId?: string) {+ return teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";+}++export async function getLogDrains(+ token: string,+ teamId?: string,+): Promise<LogDrain[]> {+ const url = `${base}/v2/integrations/log-drains${getQuery(teamId)}`;++ const res = await fetchOk(url, {+ headers: {+ Authorization: `Bearer ${token}`,+ },+ });++ return await res.json();+}++export async function getProjects(token: string, teamId?: string) {+ const url = `${base}/v9/projects${getQuery(teamId)}`;++ const res = await fetchOk(url, {+ headers: {+ Authorization: `Bearer ${token}`,+ },+ });++ const json = await res.json();+ console.log(json);+ return projectsSchema.parse(json);+}++export async function createLogDrain(+ token: string,+ logDrain: LogDrain,+ teamId?: string,+): Promise<LogDrain> {+ const url = `${base}/v2/integrations/log-drains${getQuery(teamId)}`;++ console.log({ token, logDrain, teamId });++ const res = await fetchOk(url, {+ method: "post",+ headers: {+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify(logDrain),+ });++ return await res.json();+}++export async function deleteLogDrain(+ token: string,+ id: string,+ teamId?: string,+): Promise<void> {+ const url = `${base}/v1/integrations/log-drains/${encodeURIComponent(+ id,+ )}${getQuery(teamId)}`;++ await fetchOk(url, {+ method: "delete",+ headers: {+ Authorization: `Bearer ${token}`,+ },+ });+}diff --git a/packages/integrations/vercel/src/libs/crypto.ts b/packages/integrations/vercel/src/libs/crypto.tsnew file mode 100644index 000000000..eb0989cc7--- /dev/null+++ b/packages/integrations/vercel/src/libs/crypto.ts@@ -0,0 +1,16 @@+// CREDITS: https://github.com/valeriangalliat/vercel-custom-log-drain/blob/master/utils/crypto.ts++import crypto from "crypto";++/** generate key via `node -p "crypto.randomBytes(32).toString('base64url')"` */+const key = Buffer.from(process.env.AES_KEY || "", "base64url");++export function encrypt(iv: Buffer, data: Buffer): Buffer {+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);+ return Buffer.concat([cipher.update(data), cipher.final()]);+}++export function decrypt(iv: Buffer, encrypted: Buffer): Buffer {+ const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);+ return Buffer.concat([decipher.update(encrypted), decipher.final()]);+}diff --git a/packages/integrations/vercel/src/libs/schema.ts b/packages/integrations/vercel/src/libs/schema.tsnew file mode 100644index 000000000..1c2d85cb7--- /dev/null+++ b/packages/integrations/vercel/src/libs/schema.ts@@ -0,0 +1,613 @@+import * as z from "zod";++/**+ * If the response of the request returns an HTTP statusCode with a value of -1,+ * that means there was no response returned and the lambda crashed.+ * In the same response, if the value of proxy.statusCode is returned with -1,+ * that means the revalidation occurred in the background.+ */++// https://vercel.com/docs/observability/log-drains-overview/log-drains-reference#json-log-drains+export const logDrainSchema = z.object({+ id: z.string().optional(),+ timestamp: z.number().optional(),+ type: z+ .enum([+ "middleware-invocation",+ "stdout",+ "stderr",+ "edge-function-invocation",+ "fatal",+ ])+ .optional(),+ edgeType: z.enum(["edge-function", "middleware"]).optional(),+ requestId: z.string().optional(),+ statusCode: z.number().optional(),+ message: z.string().optional(),+ projectId: z.string().optional(),+ deploymentId: z.string().optional(),+ buildId: z.string().optional(),+ source: z.enum(["external", "lambda", "edge", "static", "build"]),+ host: z.string().optional(),+ environment: z.string().optional(),+ branch: z.string().optional(),+ destination: z.string().optional(),+ path: z.string().optional(),+ entrypoint: z.string().optional(),+ proxy: z+ .object({+ timestamp: z.number().optional(),+ region: z.string().optional(), // TODO: use regions enum?+ method: z.string().optional(), // TODO: use methods enum?+ vercelCache: z.string().optional(), // TODO: use "HIT" / "MISS" enum?+ statusCode: z.number().optional(),+ path: z.string().optional(),+ host: z.string().optional(),+ scheme: z.string().optional(),+ clientIp: z.string().optional(),+ userAgent: z.array(z.string()).optional(),+ })+ .optional(),+});++export const logDrainSchemaArray = z.array(logDrainSchema);++export const projectSchema = z.object({+ accountId: z.string(),+ analytics: z+ .object({+ id: z.string(),+ canceledAt: z.number().nullable(),+ disabledAt: z.number(),+ enabledAt: z.number(),+ paidAt: z.number().optional(),+ sampleRatePercent: z.number().optional().nullable(),+ spendLimitInDollars: z.number().optional().nullable(),+ })+ .optional(),+ autoExposeSystemEnvs: z.boolean().optional(),+ autoAssignCustomDomains: z.boolean().optional(),+ autoAssignCustomDomainsUpdatedBy: z.string().optional(),+ buildCommand: z.string().optional().nullable(),+ commandForIgnoringBuildStep: z.string().optional().nullable(),+ connectConfigurationId: z.string().optional().nullable(),+ connectBuildsEnabled: z.boolean().optional(),+ createdAt: z.number().optional(),+ customerSupportCodeVisibility: z.boolean().optional(),+ crons: z+ .object({+ enabledAt: z.number(),+ disabledAt: z.number().nullable(),+ updatedAt: z.number(),+ deploymentId: z.string().nullable(),+ definitions: z.array(+ z.object({+ host: z.string(),+ path: z.string(),+ schedule: z.string(),+ }),+ ),+ })+ .optional(),+ dataCache: z+ .object({+ userDisabled: z.boolean(),+ storageSizeBytes: z.number().optional().nullable(),+ unlimited: z.boolean().optional(),+ })+ .optional(),+ devCommand: z.string().optional().nullable(),+ directoryListing: z.boolean(),+ installCommand: z.string().optional().nullable(),+ env: z+ .array(+ z.object({+ target: z+ .union([+ z.array(+ z.union([+ z.literal("production"),+ z.literal("preview"),+ z.literal("development"),+ z.literal("preview"),+ z.literal("development"),+ ]),+ ),+ z.union([+ z.literal("production"),+ z.literal("preview"),+ z.literal("development"),+ z.literal("preview"),+ z.literal("development"),+ ]),+ ])+ .optional(),+ type: z.union([+ z.literal("secret"),+ z.literal("system"),+ z.literal("encrypted"),+ z.literal("plain"),+ z.literal("sensitive"),+ ]),+ id: z.string().optional(),+ key: z.string(),+ value: z.string(),+ configurationId: z.string().optional().nullable(),+ createdAt: z.number().optional(),+ updatedAt: z.number().optional(),+ createdBy: z.string().optional().nullable(),+ updatedBy: z.string().optional().nullable(),+ gitBranch: z.string().optional(),+ edgeConfigId: z.string().optional().nullable(),+ edgeConfigTokenId: z.string().optional().nullable(),+ contentHint: z+ .union([+ z.object({+ type: z.literal("redis-url"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("redis-rest-api-url"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("redis-rest-api-token"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("redis-rest-api-read-only-token"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("blob-read-write-token"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-url"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-url-non-pooling"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-prisma-url"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-user"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-host"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-password"),+ storeId: z.string(),+ }),+ z.object({+ type: z.literal("postgres-database"),+ storeId: z.string(),+ }),+ ])+ .optional(),+ decrypted: z.boolean().optional(),+ }),+ )+ .optional(),+ framework: z+ .union([+ z.literal("blitzjs"),+ z.literal("nextjs"),+ z.literal("gatsby"),+ z.literal("remix"),+ z.literal("astro"),+ z.literal("hexo"),+ z.literal("eleventy"),+ z.literal("docusaurus-2"),+ z.literal("docusaurus"),+ z.literal("preact"),+ z.literal("solidstart"),+ z.literal("dojo"),+ z.literal("ember"),+ z.literal("vue"),+ z.literal("scully"),+ z.literal("ionic-angular"),+ z.literal("angular"),+ z.literal("polymer"),+ z.literal("svelte"),+ z.literal("sveltekit"),+ z.literal("sveltekit-1"),+ z.literal("ionic-react"),+ z.literal("create-react-app"),+ z.literal("gridsome"),+ z.literal("umijs"),+ z.literal("sapper"),+ z.literal("saber"),+ z.literal("stencil"),+ z.literal("nuxtjs"),+ z.literal("redwoodjs"),+ z.literal("hugo"),+ z.literal("jekyll"),+ z.literal("brunch"),+ z.literal("middleman"),+ z.literal("zola"),+ z.literal("hydrogen"),+ z.literal("vite"),+ z.literal("vitepress"),+ z.literal("vuepress"),+ z.literal("parcel"),+ z.literal("sanity"),+ z.literal("storybook"),+ ])+ .optional(),+ gitForkProtection: z.boolean().optional(),+ gitLFS: z.boolean().optional(),+ id: z.string(),+ latestDeployments: z+ .array(+ z.object({+ alias: z.array(z.string()).optional(),+ aliasAssigned: z.union([z.number(), z.boolean(), z.null()]).nullish(),+ aliasError: z+ .object({+ code: z.string(),+ message: z.string(),+ })+ .optional()+ .nullable(),+ aliasFinal: z.string().optional().nullable(),+ automaticAliases: z.array(z.string()).optional(),+ builds: z+ .array(+ z.object({+ use: z.string(),+ src: z.string().optional(),+ dest: z.string().optional(),+ }),+ )+ .optional(),+ connectBuildsEnabled: z.boolean().optional(),+ connectConfigurationId: z.string().optional(),+ createdAt: z.number(),+ createdIn: z.string(),+ creator: z+ .object({+ email: z.string(),+ githubLogin: z.string().optional(),+ gitlabLogin: z.string().optional(),+ uid: z.string(),+ username: z.string(),+ })+ .nullable(),+ deploymentHostname: z.string(),+ name: z.string(),+ forced: z.boolean().optional(),+ id: z.string(),+ meta: z.record(z.string()).optional(),+ monorepoManager: z.string().optional().nullable(),+ plan: z.union([+ z.literal("pro"),+ z.literal("enterprise"),+ z.literal("hobby"),+ z.literal("oss"),+ ]),+ private: z.boolean(),+ readyState: z.union([+ z.literal("BUILDING"),+ z.literal("ERROR"),+ z.literal("INITIALIZING"),+ z.literal("QUEUED"),+ z.literal("READY"),+ z.literal("CANCELED"),+ ]),+ readySubstate: z+ .union([z.literal("STAGED"), z.literal("PROMOTED")])+ .optional(),+ requestedAt: z.number().optional(),+ target: z.string().optional().nullable(),+ teamId: z.string().optional().nullable(),+ type: z.literal("LAMBDAS"),+ url: z.string(),+ userId: z.string(),+ withCache: z.boolean().optional(),+ checksConclusion: z+ .union([+ z.literal("succeeded"),+ z.literal("failed"),+ z.literal("skipped"),+ z.literal("canceled"),+ ])+ .optional(),+ checksState: z+ .union([+ z.literal("registered"),+ z.literal("running"),+ z.literal("completed"),+ ])+ .optional(),+ readyAt: z.number().optional(),+ buildingAt: z.number().optional(),+ previewCommentsEnabled: z.boolean().optional(),+ }),+ )+ .optional(),+ link: z+ .union([+ z.object({+ org: z.string().optional(),+ repo: z.string().optional(),+ repoId: z.number().optional(),+ type: z.literal("github").optional(),+ createdAt: z.number().optional(),+ deployHooks: z.array(+ z.object({+ createdAt: z.number().optional(),+ id: z.string(),+ name: z.string(),+ ref: z.string(),+ url: z.string(),+ }),+ ),+ gitCredentialId: z.string().optional(),+ updatedAt: z.number().optional(),+ sourceless: z.boolean().optional(),+ productionBranch: z.string().optional(),+ }),+ z.object({+ projectId: z.string().optional(),+ projectName: z.string().optional(),+ projectNameWithNamespace: z.string().optional(),+ projectNamespace: z.string().optional(),+ projectUrl: z.string().optional(),+ type: z.literal("gitlab").optional(),+ createdAt: z.number().optional(),+ deployHooks: z.array(+ z.object({+ createdAt: z.number().optional(),+ id: z.string(),+ name: z.string(),+ ref: z.string(),+ url: z.string(),+ }),+ ),+ gitCredentialId: z.string().optional(),+ updatedAt: z.number().optional(),+ sourceless: z.boolean().optional(),+ productionBranch: z.string().optional(),+ }),+ z.object({+ name: z.string().optional(),+ slug: z.string().optional(),+ owner: z.string().optional(),+ type: z.literal("bitbucket").optional(),+ uuid: z.string().optional(),+ workspaceUuid: z.string().optional(),+ createdAt: z.number().optional(),+ deployHooks: z.array(+ z.object({+ createdAt: z.number().optional(),+ id: z.string(),+ name: z.string(),+ ref: z.string(),+ url: z.string(),+ }),+ ),+ gitCredentialId: z.string().optional(),+ updatedAt: z.number().optional(),+ sourceless: z.boolean().optional(),+ productionBranch: z.string().optional(),+ }),+ ])+ .optional(),+ name: z.string(),+ nodeVersion: z.union([+ z.literal("18.x"),+ z.literal("16.x"),+ z.literal("14.x"),+ z.literal("12.x"),+ z.literal("10.x"),+ ]),+ outputDirectory: z.string().optional().nullable(),+ passwordProtection: z.record(z.unknown()).optional().nullable(),+ productionDeploymentsFastLane: z.boolean().optional(),+ publicSource: z.boolean().optional().nullable(),+ rootDirectory: z.string().optional().nullable(),+ serverlessFunctionRegion: z.string().optional().nullable(),+ skipGitConnectDuringLink: z.boolean().optional(),+ sourceFilesOutsideRootDirectory: z.boolean().optional(),+ ssoProtection: z+ .object({+ deploymentType: z.union([+ z.literal("all"),+ z.literal("preview"),+ z.literal("prod_deployment_urls_and_all_previews"),+ ]),+ })+ .optional()+ .nullable(),+ targets: z+ .record(+ z+ .object({+ alias: z.array(z.string()).optional(),+ aliasAssigned: z.union([z.number(), z.boolean(), z.null()]).nullish(),+ aliasError: z+ .object({+ code: z.string(),+ message: z.string(),+ })+ .optional()+ .nullable(),+ aliasFinal: z.string().optional().nullable(),+ automaticAliases: z.array(z.string()).optional(),+ builds: z+ .array(+ z.object({+ use: z.string(),+ src: z.string().optional(),+ dest: z.string().optional(),+ }),+ )+ .optional(),+ connectBuildsEnabled: z.boolean().optional(),+ connectConfigurationId: z.string().optional(),+ createdAt: z.number(),+ createdIn: z.string(),+ creator: z+ .object({+ email: z.string(),+ githubLogin: z.string().optional(),+ gitlabLogin: z.string().optional(),+ uid: z.string(),+ username: z.string(),+ })+ .nullable(),+ deploymentHostname: z.string(),+ name: z.string(),+ forced: z.boolean().optional(),+ id: z.string(),+ meta: z.record(z.string()).optional(),+ monorepoManager: z.string().optional().nullable(),+ plan: z.union([+ z.literal("pro"),+ z.literal("enterprise"),+ z.literal("hobby"),+ z.literal("oss"),+ ]),+ private: z.boolean(),+ readyState: z.union([+ z.literal("BUILDING"),+ z.literal("ERROR"),+ z.literal("INITIALIZING"),+ z.literal("QUEUED"),+ z.literal("READY"),+ z.literal("CANCELED"),+ ]),+ readySubstate: z+ .union([z.literal("STAGED"), z.literal("PROMOTED")])+ .optional(),+ requestedAt: z.number().optional(),+ target: z.string().optional().nullable(),+ teamId: z.string().optional().nullable(),+ type: z.literal("LAMBDAS"),+ url: z.string(),+ userId: z.string(),+ withCache: z.boolean().optional(),+ checksConclusion: z+ .union([+ z.literal("succeeded"),+ z.literal("failed"),+ z.literal("skipped"),+ z.literal("canceled"),+ ])+ .optional(),+ checksState: z+ .union([+ z.literal("registered"),+ z.literal("running"),+ z.literal("completed"),+ ])+ .optional(),+ readyAt: z.number().optional(),+ buildingAt: z.number().optional(),+ previewCommentsEnabled: z.boolean().optional(),+ })+ .nullable(),+ )+ .optional(),+ transferCompletedAt: z.number().optional(),+ transferStartedAt: z.number().optional(),+ transferToAccountId: z.string().optional(),+ transferredFromAccountId: z.string().optional(),+ updatedAt: z.number().optional(),+ live: z.boolean().optional(),+ enablePreviewFeedback: z.boolean().optional().nullable(),+ permissions: z.object({}).optional(),+ lastRollbackTarget: z.record(z.unknown()).optional().nullable(),+ lastAliasRequest: z+ .object({+ fromDeploymentId: z.string(),+ toDeploymentId: z.string(),+ jobStatus: z.union([+ z.literal("succeeded"),+ z.literal("failed"),+ z.literal("skipped"),+ z.literal("pending"),+ z.literal("in-progress"),+ ]),+ requestedAt: z.number(),+ type: z.union([z.literal("promote"), z.literal("rollback")]),+ })+ .optional()+ .nullable(),+ hasFloatingAliases: z.boolean().optional(),+ protectionBypass: z+ .record(+ z.union([+ z.object({+ createdAt: z.number(),+ createdBy: z.string(),+ scope: z.union([+ z.literal("shareable-link"),+ z.literal("automation-bypass"),+ ]),+ }),+ z.object({+ createdAt: z.number(),+ lastUpdatedAt: z.number(),+ lastUpdatedBy: z.string(),+ access: z.union([z.literal("requested"), z.literal("granted")]),+ scope: z.literal("user"),+ }),+ ]),+ )+ .optional(),+ hasActiveBranches: z.boolean().optional(),+ trustedIps: z+ .union([+ z.object({+ deploymentType: z.union([+ z.literal("all"),+ z.literal("preview"),+ z.literal("prod_deployment_urls_and_all_previews"),+ z.literal("production"),+ ]),+ addresses: z.array(+ z.object({+ value: z.string(),+ note: z.string().optional(),+ }),+ ),+ protectionMode: z.union([+ z.literal("additional"),+ z.literal("exclusive"),+ ]),+ }),+ z.object({+ deploymentType: z.union([+ z.literal("all"),+ z.literal("preview"),+ z.literal("prod_deployment_urls_and_all_previews"),+ z.literal("production"),+ ]),+ }),+ ])+ .optional(),+ gitComments: z+ .object({+ onPullRequest: z.boolean(),+ onCommit: z.boolean(),+ })+ .optional(),+});++export const projectsSchema = z.object({+ projects: z.array(projectSchema),+ pagination: z.object({+ count: z.number(),+ next: z.number().nullable(),+ prev: z.number().nullable(),+ }),+});diff --git a/packages/integrations/vercel/src/libs/tinybird.ts b/packages/integrations/vercel/src/libs/tinybird.tsnew file mode 100644index 000000000..cea819c25--- /dev/null+++ b/packages/integrations/vercel/src/libs/tinybird.ts@@ -0,0 +1,12 @@+import { Tinybird } from "@openstatus/tinybird";++import { logDrainSchema } from "./schema";++const tb = new Tinybird({ token: process.env.TINY_BIRD_API_KEY || "" }); // should we use t3-env?++export function publishVercelLogDrain() {+ return tb.buildIngestEndpoint({+ datasource: "vercel_log_drain__v0",+ event: logDrainSchema,+ });+}diff --git a/packages/integrations/vercel/src/pages/configure.tsx b/packages/integrations/vercel/src/pages/configure.tsxnew file mode 100644index 000000000..ca52e8200--- /dev/null+++ b/packages/integrations/vercel/src/pages/configure.tsx@@ -0,0 +1,107 @@+import { revalidatePath } from "next/cache";+import { cookies } from "next/headers";+import { redirect } from "next/navigation";++import { SubmitButton } from "../components/submit-button";+import {+ createLogDrain,+ deleteLogDrain,+ getLogDrains,+ getProjects,+} from "../libs/client";+import { decrypt } from "../libs/crypto";++export async function Configure() {+ const iv = cookies().get("iv")?.value;+ const encryptedToken = cookies().get("token")?.value;+ const teamId = cookies().get("teamId")?.value;++ if (!iv || !encryptedToken) {+ /** Redirect to access new token */+ return redirect("/app");+ }++ const token = decrypt(+ Buffer.from(iv || "", "base64url"),+ Buffer.from(encryptedToken || "", "base64url"),+ ).toString();++ let logDrains = await getLogDrains(token, teamId);++ const projects = await getProjects(token, teamId);++ for (const project of projects.projects) {+ console.log({ project });+ console.log("create integration");+ }+ // Create integration project if it doesn't exist++ if (logDrains.length === 0) {+ logDrains = [+ await createLogDrain(+ token,+ // @ts-expect-error We need more data - but this is a demo+ {+ deliveryFormat: "json",+ name: "OpenStatus Log Drain",+ // TODO: update with correct url+ url: "https://wwww.openstatus.dev/api/integrations/vercel",+ sources: ["static", "lambda", "edge", "external"],+ // headers: { "key": "value"}+ },+ teamId,+ ),+ ];+ }++ // TODO: automatically create log drain on installation+ async function create(formData: FormData) {+ "use server";+ await createLogDrain(+ token,+ // @ts-expect-error We need more data - but this is a demo+ {+ deliveryFormat: "json",+ name: "OpenStatus Log Drain",+ // TODO: update with correct url+ url: "https://wwww.openstatus.dev/api/integrations/vercel",+ sources: ["static", "lambda", "edge", "external"],+ // headers: { "key": "value"}+ },+ teamId,+ );+ revalidatePath("/");+ }++ async function _delete(formData: FormData) {+ "use server";+ const id = formData.get("id")?.toString();+ console.log({ id });+ if (id) {+ await deleteLogDrain(token, id, String(teamId));+ revalidatePath("/");+ }+ }++ return (+ <div className="flex w-full flex-col items-center justify-center">+ <div className="border-border m-3 grid w-full max-w-xl gap-3 rounded-lg border p-6 backdrop-blur-[2px]">+ <h1 className="font-cal text-2xl">Configure Vercel Integration</h1>+ <ul>+ {logDrains.map((item) => (+ <li+ key={item.id}+ className="flex items-center justify-between gap-2"+ >+ <p>{item.name}</p>+ <form action={_delete}>+ <input name="id" value={item.id} className="hidden" />+ <SubmitButton>Remove integration</SubmitButton>+ </form>+ </li>+ ))}+ </ul>+ </div>+ </div>+ );+}diff --git a/packages/integrations/vercel/src/routes/callback.ts b/packages/integrations/vercel/src/routes/callback.tsnew file mode 100644index 000000000..e25dd9005--- /dev/null+++ b/packages/integrations/vercel/src/routes/callback.ts@@ -0,0 +1,54 @@+import crypto from "crypto";+import { NextResponse } from "next/server";+import type { NextRequest } from "next/server";++import { getToken } from "../libs/client";+import { encrypt } from "../libs/crypto";++export async function GET(req: NextRequest) {+ const { searchParams } = new URL(req.url);+ const code = searchParams.get("code");+ const next = searchParams.get("next");+ const teamId = searchParams.get("teamId");+ console.log({ code, next, teamId });+ if (!code || !next) {+ throw new Error("Missing `code` or `next` param");+ }++ /** Get access token from Vercel */+ const token = await getToken(code);++ // TODO: automatically install log drains to the allowed projects++ const iv = crypto.randomBytes(16);+ const encryptedToken = encrypt(iv, Buffer.from(token));++ // redirect to vercel's integration page after installation+ const res = NextResponse.redirect(+ `https://wwww.openstatus.dev/app/integrations/vercel/configure`,+ );++ console.log("Setting cookies");+ /** Encrypt access token and add to Cookies */+ res.cookies.set("token", encryptedToken.toString("base64url"));+ res.cookies.set("iv", iv.toString("base64url"));++ if (teamId) {+ res.cookies.set("teamId", teamId);+ }++ return res;+}++/**+ * The code below is only needed if we allow the user+ * to send the secret link to a team mate e.g.+ */+function getSecretUrl(iv: Buffer, encryptedToken: Buffer) {+ const baseUrl = new URL(process.env.VRCL_REDIRECT_URI!);+ baseUrl.pathname = "/configure";+ baseUrl.searchParams.set("token", encryptedToken.toString("base64url"));+ baseUrl.searchParams.set("iv", iv.toString("base64url"));+ const secretUrl = baseUrl.toString();+ return secretUrl;+}diff --git a/packages/integrations/vercel/src/routes/webhook.ts b/packages/integrations/vercel/src/routes/webhook.tsnew file mode 100644index 000000000..55bd5379d--- /dev/null+++ b/packages/integrations/vercel/src/routes/webhook.ts@@ -0,0 +1,76 @@+import { log } from "console";+import crypto from "crypto";+import { NextResponse } from "next/server";+import * as z from "zod";++import { env } from "../../env";+import { logDrainSchemaArray } from "../libs/schema";+import { publishVercelLogDrain } from "../libs/tinybird";++export const config = {+ api: {+ bodyParser: false,+ },+};++/**+ * Ingest log drains from Vercel.+ */+export async function POST(request: Request) {+ const rawBody = await request.text();+ // const rawBodyBuffer = Buffer.from(rawBody, "utf-8");+ // // const bodySignature = sha1(rawBodyBuffer, "LOG_DRAIN_SECRET");++ // // /**+ // // * Validates the signature of the request+ // // * Uncomment for 'Test Log Drain' in Vercel+ // // */+ // // if (bodySignature !== request.headers.get("x-vercel-signature")) {+ // // return NextResponse.json(+ // // {+ // // code: "invalid_signature",+ // // error: "signature didn't match",+ // // },+ // // { status: 401 },+ // // );+ // // }++ /**+ * Returns a header verification to Vercel, so the route can be added as a log drain+ */+ if (z.object({}).safeParse(JSON.parse(rawBody)).success) {+ return NextResponse.json(+ { code: "ok" },+ { status: 200, headers: { "x-vercel-verify": env.INTEGRATION_SECRET } },+ );+ }++ /**+ * Validates the body of the request+ */+ const logDrains = logDrainSchemaArray.safeParse(JSON.parse(rawBody));++ if (logDrains.success) {+ // We are only pushing the logs that are not stdout or stderr+ const data = logDrains.data.filter(+ (log) => log.type !== "stdout" && log.type !== "stderr",+ );++ for (const event of data) {+ // FIXME: Zod-bird is broken+ await publishVercelLogDrain()(event);+ }++ return NextResponse.json({ code: "ok" }, { status: 200 });+ } else {+ console.error("Error parsing logDrains", logDrains.error);+ }+ return NextResponse.json({ error: logDrains.error }, { status: 500 });+}++/**+ * Creates a sha1 hash from a buffer and a secret+ */+function sha1(data: Buffer, secret: string) {+ return crypto.createHmac("sha1", secret).update(data).digest("hex");+}diff --git a/packages/integrations/vercel/tsconfig.json b/packages/integrations/vercel/tsconfig.jsonnew file mode 100644index 000000000..b5bdcb868--- /dev/null+++ b/packages/integrations/vercel/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "tsconfig/nextjs.json",+ "include": ["src", "*.ts"]+}diff --git a/packages/tinybird/datasources/vercel_log_drain.datasource b/packages/tinybird/datasources/vercel_log_drain.datasourcenew file mode 100644index 000000000..2cc391ad4--- /dev/null+++ b/packages/tinybird/datasources/vercel_log_drain.datasource@@ -0,0 +1,29 @@+VERSION 1++SCHEMA >+`branch` String `json:$.branch` ,+`deploymentId` String `json:$.deploymentId` ,+`environment` String `json:$.environment` ,+`host` String `json:$.host` ,+`id` String `json:$.id` ,+`message` String `json:$.message` ,+`path` String `json:$.path` ,+`projectId` String `json:$.projectId` ,+`proxy_clientIp` String `json:$.proxy.clientIp` ,+`proxy_host` String `json:$.proxy.host` ,+`proxy_method` String `json:$.proxy.method` ,+`proxy_vercelCache` String `json:$.proxy.vercelCache` ,+`proxy_path` String `json:$.proxy.path` ,+`proxy_region` String `json:$.proxy.region` ,+`proxy_scheme` String `json:$.proxy.scheme` ,+`proxy_timestamp` Int64 `json:$.proxy.timestamp` ,+`proxy_status` String `json:$.proxy.status` ,+`proxy_userAgent` Array(String) `json:$.proxy.userAgent[:]` ,+`requestId` String `json:$.requestId` ,+`type` String `json:$.type` ,+`source` String `json:$.source` ,+`timestamp` Int64 `json:$.timestamp` ,++ENGINE "MergeTree"+ENGINE_SORTING_KEY "requestId, projectId"+ENGINE_PARTITION_KEY "toYYYYMMDD(fromUnixTimestamp64Milli(timestamp))"\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 161f7d8ca..fdbab364c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -145,6 +145,9 @@ importers:'@openstatus/upstash':specifier: workspace:*version: link:../../packages/upstash+ '@openstatus/vercel':+ specifier: workspace:*+ version: link:../../packages/integrations/vercel'@radix-ui/react-accordion':specifier: 1.1.2version: 1.1.2(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -578,6 +581,43 @@ importers:specifier: 5.1.6version: 5.1.6+ packages/integrations/vercel:+ dependencies:+ '@openstatus/tinybird':+ specifier: workspace:*+ version: link:../../tinybird+ '@t3-oss/env-core':+ specifier: 0.6.0+ version: 0.6.0([email protected])([email protected])+ react:+ specifier: 18.2.0+ version: 18.2.0+ react-dom:+ specifier: 18.2.0+ version: 18.2.0([email protected])+ zod:+ specifier: ^3.21.4+ version: 3.21.4+ devDependencies:+ '@types/node':+ specifier: 20.3.1+ version: 20.3.1+ '@types/react':+ specifier: 18.2.12+ version: 18.2.12+ '@types/react-dom':+ specifier: 18.2.5+ version: 18.2.5+ next:+ specifier: 13.4.12+ tsconfig:+ specifier: workspace:*+ version: link:../../tsconfig+ typescript:+ specifier: 5.1.6+ version: 5.1.6+packages/plans:dependencies:'@openstatus/db':@@ -2535,7 +2575,6 @@ packages:/@next/[email protected]:resolution: {integrity: sha512-RmHanbV21saP/6OEPBJ7yJMuys68cIf8OBBWd7+uj40LdpmswVAwe1uzeuFyUsd6SfeITWT3XnQfn6wULeKwDQ==}- dev: false/@next/[email protected]:resolution: {integrity: sha512-FsAT5x0jF2kkhNkKkukhsyYOrRqtSxrEhfliniIq0bwWbuXLgyt3Gv0Ml+b91XwjwArmuP7NxCiGd++GGKdNMQ==}@@ -2553,7 +2592,6 @@ packages:cpu: [arm64]os: [darwin]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2571,7 +2609,6 @@ packages:cpu: [x64]os: [darwin]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2589,7 +2626,6 @@ packages:cpu: [arm64]os: [linux]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2607,7 +2643,6 @@ packages:cpu: [arm64]os: [linux]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2625,7 +2660,6 @@ packages:cpu: [x64]os: [linux]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2643,7 +2677,6 @@ packages:cpu: [x64]os: [linux]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2661,7 +2694,6 @@ packages:cpu: [arm64]os: [win32]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2679,7 +2711,6 @@ packages:cpu: [ia32]os: [win32]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -2697,7 +2728,6 @@ packages:cpu: [x64]os: [win32]requiresBuild: true- dev: falseoptional: true/@next/[email protected]:@@ -4999,7 +5029,6 @@ packages:resolution: {integrity: sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==}dependencies:tslib: 2.6.1- dev: falseresolution: {integrity: sha512-JZI8vxlHwtiZO7OYS3qSX9Ngt7UcdqsugLwhBwx7UVi5wp1PtRo2tzMyNoBEGbfHdmkd2QU9IbvYjqtaLUA7TQ==}@@ -6261,7 +6290,6 @@ packages:engines: {node: '>=10.16.0'}dependencies:streamsearch: 1.1.0- dev: falseresolution: {integrity: sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==}@@ -6528,7 +6556,6 @@ packages:resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}- dev: falseresolution: {integrity: sha512-dYFdjLb7y1ajfxQopN05mylEpK9ZX0sO1/RfMXdfmwjlIsPkbh4p7A682x++zFPLDCo1x3p82dtljHf5cW2LKA==}@@ -8717,7 +8744,6 @@ packages:resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==}- dev: falseresolution: {integrity: sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==}@@ -11100,7 +11126,6 @@ packages:transitivePeerDependencies:- '@babel/core'- babel-plugin-macros- dev: false/[email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]):resolution: {integrity: sha512-HuPSzzAbJ1T4BD8e0bs6B9C1kWQ6gv8ykZoRWs5AQoiIuqbGHHdQO7Ljuvg05Q0Z24E2ABozHe6FxDvI6HfyAw==}@@ -11860,7 +11885,6 @@ packages:nanoid: 3.3.6picocolors: 1.0.0source-map-js: 1.0.2- dev: falseresolution: {integrity: sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==}@@ -12214,7 +12238,6 @@ packages:loose-envify: 1.4.0react: 18.2.0scheduler: 0.23.0- dev: falseresolution: {integrity: sha512-DNUQb7xzAlMga2ZppG57bnWhJnqOEcTYzxNvLA4IVCiYJkgPNVukFMOZVG2OuQ0W8ddiF6bLZBKDZHnnIenbpw==}@@ -12908,7 +12931,6 @@ packages:resolution: {integrity: sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==}dependencies:loose-envify: 1.4.0- dev: falseresolution: {integrity: sha512-t44QCeDKAPf1mtQH3fYpWz8IM/DyvHLjs8wUvvwMYxk5moOqCzrMSxK6HQVD0QVmVjXFavoFIPRVrMuJPKAvtg==}@@ -13198,7 +13220,6 @@ packages:resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}engines: {node: '>=10.0.0'}- dev: falseresolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}@@ -13350,7 +13371,6 @@ packages:'@babel/core': 7.22.9client-only: 0.0.1react: 18.2.0- dev: falseresolution: {integrity: sha512-E87pIogpwUsUwXw7dNyU4QDjdgVMy52m+XEOPEKUn161cCzWjjhPSQhByfd1CcNvrOLnXQ6OnnZDwnJrz/Z4YQ==}@@ -14685,7 +14705,6 @@ packages:dependencies:glob-to-regexp: 0.4.1graceful-fs: 4.2.11- dev: falseresolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 37e42c9f7..5807bcefc 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,5 +1,5 @@packages:- "apps/*"- - "packages/*"+ - "packages/**/*"- "packages/config/*"- "packages/emails/.react-email"