WhatsApp/Signal/Formstack/admin updates

This commit is contained in:
Darren Clarke 2025-11-21 14:55:28 +01:00
parent bcecf61a46
commit d0cc5a21de
451 changed files with 16139 additions and 39623 deletions

3
.gitignore vendored
View file

@ -28,3 +28,6 @@ baileys-state
signald-state
project.org
**/.openapi-generator/
apps/bridge-worker/scripts/*
ENVIRONMENT_VARIABLES_MIGRATION.md
local-scripts/*

View file

@ -1,4 +1,4 @@
image: node:20-bookworm-slim
image: node:22-bookworm-slim
stages:
- build
@ -11,10 +11,12 @@ build-all:
TURBO_TOKEN: ${TURBO_TOKEN}
TURBO_TEAM: ${TURBO_TEAM}
ZAMMAD_URL: ${ZAMMAD_URL}
PNPM_HOME: "/pnpm"
script:
- npm install npm@10 -g
- npm install -g turbo
- npm ci
- export PATH="$PNPM_HOME:$PATH"
- corepack enable && corepack prepare pnpm@9.15.4 --activate
- pnpm add -g turbo
- pnpm install --frozen-lockfile
- turbo build
.docker-build:
@ -24,14 +26,14 @@ build-all:
stage: docker-build
variables:
DOCKER_TAG: ${CI_COMMIT_SHORT_SHA}
DOCKER_CONTEXT: .
BUILD_CONTEXT: .
only:
- main
- develop
- tags
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- DOCKER_BUILDKIT=1 docker build --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${DOCKER_CONTEXT}
- DOCKER_BUILDKIT=1 docker build --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${BUILD_CONTEXT}
- docker push ${DOCKER_NS}:${DOCKER_TAG}
.docker-release:
@ -74,17 +76,6 @@ link-docker-release:
variables:
DOCKER_NS: ${CI_REGISTRY}/digiresilience/link/link-stack/link
leafcutter-docker-build:
extends: .docker-build
variables:
DOCKER_NS: ${CI_REGISTRY}/digiresilience/link/link-stack/leafcutter
DOCKERFILE_PATH: ./apps/leafcutter/Dockerfile
leafcutter-docker-release:
extends: .docker-release
variables:
DOCKER_NS: ${CI_REGISTRY}/digiresilience/link/link-stack/leafcutter
bridge-frontend-docker-build:
extends: .docker-build
variables:
@ -200,16 +191,17 @@ zammad-docker-build:
variables:
DOCKER_NS: ${CI_REGISTRY}/digiresilience/link/link-stack/zammad
DOCKERFILE_PATH: ./docker/zammad/Dockerfile
DOCKER_CONTEXT: ./docker/zammad
BUILD_CONTEXT: ./docker/zammad
PNPM_HOME: "/pnpm"
before_script:
- apk --update add nodejs npm
- export PATH="$PNPM_HOME:$PATH"
script:
- npm install npm@10 -g
- npm install -g turbo
- npm ci
- corepack enable && corepack prepare pnpm@9.15.4 --activate
- pnpm add -g turbo
- pnpm install --frozen-lockfile
- turbo build --force --filter @link-stack/zammad-addon-*
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- DOCKER_BUILDKIT=1 docker build --build-arg EMBEDDED=true --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${DOCKER_CONTEXT}
- DOCKER_BUILDKIT=1 docker build --build-arg EMBEDDED=true --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${BUILD_CONTEXT}
- docker push ${DOCKER_NS}:${DOCKER_TAG}
zammad-docker-release:
@ -222,16 +214,17 @@ zammad-standalone-docker-build:
variables:
DOCKER_NS: ${CI_REGISTRY}/digiresilience/link/link-stack/zammad-standalone
DOCKERFILE_PATH: ./docker/zammad/Dockerfile
DOCKER_CONTEXT: ./docker/zammad
BUILD_CONTEXT: ./docker/zammad
PNPM_HOME: "/pnpm"
before_script:
- apk --update add nodejs npm
- export PATH="$PNPM_HOME:$PATH"
script:
- npm install npm@10 -g
- npm install -g turbo
- npm ci
- corepack enable && corepack prepare pnpm@9.15.4 --activate
- pnpm add -g turbo
- pnpm install --frozen-lockfile
- turbo build --force --filter @link-stack/zammad-addon-*
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- DOCKER_BUILDKIT=1 docker build --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${DOCKER_CONTEXT}
- DOCKER_BUILDKIT=1 docker build --pull --no-cache -t ${DOCKER_NS}:${DOCKER_TAG} -f ${DOCKERFILE_PATH} ${BUILD_CONTEXT}
- docker push ${DOCKER_NS}:${DOCKER_TAG}
zammad-standalone-docker-release:

2
.nvmrc
View file

@ -1 +1 @@
v20.2.0
v22.18.0

View file

@ -2,22 +2,28 @@ FROM node:22-bookworm-slim AS base
FROM base AS builder
ARG APP_DIR=/opt/bridge-frontend
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN mkdir -p ${APP_DIR}/
RUN npm i -g turbo
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
RUN pnpm add -g turbo
WORKDIR ${APP_DIR}
COPY . .
RUN turbo prune --scope=@link-stack/bridge-frontend --scope=@link-stack/bridge-migrations --docker
FROM base AS installer
ARG APP_DIR=/opt/bridge-frontend
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
WORKDIR ${APP_DIR}
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
COPY --from=builder ${APP_DIR}/.gitignore .gitignore
COPY --from=builder ${APP_DIR}/out/json/ .
COPY --from=builder ${APP_DIR}/out/package-lock.json ./package-lock.json
RUN npm ci
COPY --from=builder ${APP_DIR}/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN pnpm install --frozen-lockfile
COPY --from=builder ${APP_DIR}/out/full/ .
RUN npm i -g turbo
RUN pnpm add -g turbo
RUN turbo run build --filter=@link-stack/bridge-frontend --filter=@link-stack/bridge-migrations
FROM base AS runner
@ -29,15 +35,15 @@ LABEL maintainer="Darren Clarke <darren@redaranj.com>"
LABEL org.label-schema.build-date=$BUILD_DATE
LABEL org.label-schema.version=$VERSION
ENV APP_DIR ${APP_DIR}
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
RUN DEBIAN_FRONTEND=noninteractive apt-get update && \
apt-get install -y --no-install-recommends \
dumb-init
RUN mkdir -p ${APP_DIR}
WORKDIR ${APP_DIR}
COPY --from=installer ${APP_DIR}/node_modules/ ./node_modules/
COPY --from=installer ${APP_DIR}/apps/bridge-frontend/ ./apps/bridge-frontend/
COPY --from=installer ${APP_DIR}/apps/bridge-migrations/ ./apps/bridge-migrations/
COPY --from=installer ${APP_DIR}/package.json ./package.json
COPY --from=installer ${APP_DIR} ./
RUN chown -R node:node ${APP_DIR}/
WORKDIR ${APP_DIR}/apps/bridge-frontend/
RUN chmod +x docker-entrypoint.sh

View file

@ -1,36 +1,133 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
# Bridge Frontend
## Getting Started
Frontend application for managing communication bridges between various messaging platforms and the CDR Link system.
First, run the development server:
## Overview
Bridge Frontend provides a web interface for configuring and managing communication channels including Signal, WhatsApp, Facebook, and Voice integrations. It handles bot registration, webhook configuration, and channel settings.
## Features
- **Channel Management**: Configure Signal, WhatsApp, Facebook, and Voice channels
- **Bot Registration**: Register and manage bots for each communication platform
- **Webhook Configuration**: Set up webhooks for message routing
- **Settings Management**: Configure channel-specific settings and behaviors
- **User Authentication**: Secure access with NextAuth.js
## Development
### Prerequisites
- Node.js >= 20
- npm >= 10
- PostgreSQL database
- Running bridge-worker service
### Setup
```bash
# Install dependencies
npm install
# Run database migrations
npm run migrate:latest
# Run development server
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
# Build for production
npm run build
# Start production server
npm run start
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
### Environment Variables
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
Required environment variables:
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
- `DATABASE_URL` - PostgreSQL connection string
- `DATABASE_HOST` - Database host
- `DATABASE_NAME` - Database name
- `DATABASE_USER` - Database username
- `DATABASE_PASSWORD` - Database password
- `NEXTAUTH_URL` - Application URL
- `NEXTAUTH_SECRET` - NextAuth.js secret
- `GOOGLE_CLIENT_ID` - Google OAuth client ID
- `GOOGLE_CLIENT_SECRET` - Google OAuth client secret
## Learn More
### Available Scripts
To learn more about Next.js, take a look at the following resources:
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm run start` - Start production server
- `npm run lint` - Run ESLint
- `npm run migrate:latest` - Run all pending migrations
- `npm run migrate:down` - Rollback last migration
- `npm run migrate:up` - Run next migration
- `npm run migrate:make` - Create new migration
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
## Architecture
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
### Database Schema
## Deploy on Vercel
The application manages the following main entities:
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
- **Bots**: Communication channel bot configurations
- **Webhooks**: Webhook endpoints for external integrations
- **Settings**: Channel-specific configuration settings
- **Users**: User accounts with role-based permissions
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
### API Routes
- `/api/auth` - Authentication endpoints
- `/api/[service]/bots` - Bot management for each service
- `/api/[service]/webhooks` - Webhook configuration
### Page Structure
- `/` - Dashboard/home page
- `/login` - Authentication page
- `/[...segment]` - Dynamic routing for CRUD operations
- `@create` - Create new entities
- `@detail` - View entity details
- `@edit` - Edit existing entities
## Integration
### Database Access
Uses Kysely ORM for type-safe database queries:
```typescript
import { db } from '@link-stack/database'
const bots = await db
.selectFrom('bots')
.selectAll()
.execute()
```
### Authentication
Integrated with NextAuth.js using database adapter:
```typescript
import { authOptions } from '@link-stack/auth'
```
## Docker Support
```bash
# Build image
docker build -t link-stack/bridge-frontend .
# Run with docker-compose
docker-compose -f docker/compose/bridge.yml up
```
## Related Services
- **bridge-worker**: Processes messages from configured channels
- **bridge-whatsapp**: WhatsApp-specific integration service
- **bridge-migrations**: Database schema management

View file

@ -1,10 +1,11 @@
import { Create } from "@link-stack/bridge-ui";
type PageProps = {
params: { segment: string[] };
params: Promise<{ segment: string[] }>;
};
export default function Page({ params: { segment } }: PageProps) {
export default async function Page({ params }: PageProps) {
const { segment } = await params;
const service = segment[0];
return <Create service={service} />;

View file

@ -1,11 +1,12 @@
import { db } from "@link-stack/bridge-common";
import { serviceConfig, Detail } from "@link-stack/bridge-ui";
type Props = {
params: { segment: string[] };
type PageProps = {
params: Promise<{ segment: string[] }>;
};
export default async function Page({ params: { segment } }: Props) {
export default async function Page({ params }: PageProps) {
const { segment } = await params;
const service = segment[0];
const id = segment?.[1];

View file

@ -2,10 +2,11 @@ import { db } from "@link-stack/bridge-common";
import { serviceConfig, Edit } from "@link-stack/bridge-ui";
type PageProps = {
params: { segment: string[] };
params: Promise<{ segment: string[] }>;
};
export default async function Page({ params: { segment } }: PageProps) {
export default async function Page({ params }: PageProps) {
const { segment } = await params;
const service = segment[0];
const id = segment?.[1];

View file

@ -2,12 +2,13 @@ import { db } from "@link-stack/bridge-common";
import { serviceConfig, List } from "@link-stack/bridge-ui";
type PageProps = {
params: {
params: Promise<{
segment: string[];
};
}>;
};
export default async function Page({ params: { segment } }: PageProps) {
export default async function Page({ params }: PageProps) {
const { segment } = await params;
const service = segment[0];
if (!service) return null;

View file

@ -1,10 +1,6 @@
import GoogleProvider from "next-auth/providers/google";
import { KyselyAdapter } from "@auth/kysely-adapter";
import { db } from "@link-stack/bridge-common";
export const authOptions = {
// @ts-ignore
adapter: KyselyAdapter(db),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,

View file

@ -0,0 +1 @@
export { relinkBot as POST } from "@link-stack/bridge-ui";

View file

@ -1,6 +1,9 @@
import NextAuth from "next-auth";
import { authOptions } from "@/app/_lib/authentication";
// Force this route to be dynamic (not statically generated at build time)
export const dynamic = 'force-dynamic';
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View file

@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { LicenseInfo } from "@mui/x-license";
LicenseInfo.setLicenseKey(
"c787ac6613c5f2aa0494c4285fe3e9f2Tz04OTY1NyxFPTE3NDYzNDE0ODkwMDAsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI=",
"2a7dd73ee59e3e028b96b0d2adee1ad8Tz0xMTMwOTUsRT0xNzc5MDYyMzk5MDAwLFM9cHJvLExNPXN1YnNjcmlwdGlvbixQVj1pbml0aWFsLEtWPTI=",
);
export const metadata: Metadata = {

View file

@ -2,6 +2,6 @@
set -e
echo "running migrations"
(cd ../bridge-migrations/ && npm run migrate:up:all)
(cd ../bridge-migrations/ && pnpm run migrate:up:all)
echo "starting bridge-frontend"
exec dumb-init npm run start
exec dumb-init pnpm run start

View file

@ -1,23 +1,81 @@
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth({
pages: {
signIn: `/login`,
export default withAuth(
function middleware(req) {
const isDev = process.env.NODE_ENV === "development";
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
// Allow digiresilience.org for embedding documentation
const frameSrcDirective = `frame-src 'self' https://digiresilience.org;`;
const cspHeader = `
default-src 'self';
${frameSrcDirective}
connect-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ""};
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
upgrade-insecure-requests;
`;
const contentSecurityPolicyHeaderValue = cspHeader
.replace(/\s{2,}/g, " ")
.trim();
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set(
"Content-Security-Policy",
contentSecurityPolicyHeaderValue,
);
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
response.headers.set(
"Content-Security-Policy",
contentSecurityPolicyHeaderValue,
);
// Additional security headers
response.headers.set("X-Frame-Options", "SAMEORIGIN");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("X-XSS-Protection", "1; mode=block");
response.headers.set(
"Permissions-Policy",
"camera=(), microphone=(), geolocation=()"
);
return response;
},
callbacks: {
authorized: ({ token }) => {
if (process.env.SETUP_MODE === "true") {
return true;
}
if (token?.email) {
return true;
}
return false;
{
pages: {
signIn: `/login`,
},
},
});
callbacks: {
authorized: ({ token }) => {
if (process.env.SETUP_MODE === "true") {
return true;
}
if (token?.email) {
return true;
}
return false;
},
},
}
);
export const config = {
matcher: ["/((?!ws|wss|api|_next/static|_next/image|favicon.ico).*)"],

View file

@ -1,6 +1,6 @@
{
"name": "@link-stack/bridge-frontend",
"version": "2.2.0",
"version": "3.3.0",
"type": "module",
"scripts": {
"dev": "next dev",
@ -13,28 +13,28 @@
"migrate:down:one": "tsx database/migrate.ts down:one"
},
"dependencies": {
"@auth/kysely-adapter": "^1.5.2",
"@link-stack/bridge-common": "*",
"@link-stack/bridge-ui": "*",
"@link-stack/ui": "*",
"@mui/icons-material": "^5",
"@mui/material": "^5",
"@mui/material-nextjs": "^5",
"@mui/x-license": "^7.18.0",
"next": "^14.2.25",
"next-auth": "^4.24.8",
"react": "18.3.1",
"react-dom": "18.3.1",
"sharp": "^0.33.5",
"tsx": "^4.19.1"
"@auth/kysely-adapter": "^1.10.0",
"@mui/icons-material": "^6",
"@mui/material": "^6",
"@mui/material-nextjs": "^6",
"@mui/x-license": "^7",
"@link-stack/bridge-common": "workspace:*",
"@link-stack/bridge-ui": "workspace:*",
"next": "15.5.4",
"next-auth": "^4.24.11",
"react": "19.2.0",
"react-dom": "19.2.0",
"sharp": "^0.34.4",
"tsx": "^4.20.6",
"@link-stack/ui": "workspace:*"
},
"devDependencies": {
"@link-stack/eslint-config": "*",
"@link-stack/typescript-config": "*",
"@types/node": "^22",
"@types/pg": "^8.11.10",
"@types/react": "^18",
"@types/react-dom": "^18",
"@link-stack/eslint-config": "workspace:*",
"@link-stack/typescript-config": "workspace:*",
"@types/node": "^24",
"@types/pg": "^8.15.5",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5"
}
}

View file

@ -0,0 +1,2 @@
User-agent: *
Disallow: /

View file

@ -1,6 +1,10 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@ -14,14 +18,24 @@
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./*"]
"@/*": [
"./*"
]
},
"plugins": [
{
"name": "next"
}
]
],
"target": "ES2017"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}

View file

@ -0,0 +1,158 @@
# Bridge Migrations
Database migration management for the CDR Link bridge system.
## Overview
Bridge Migrations handles database schema versioning and migrations for all bridge-related tables using Kysely migration framework. It manages the database structure for authentication, messaging channels, webhooks, and settings.
## Features
- **Schema Versioning**: Track and apply database schema changes
- **Up/Down Migrations**: Support for rolling forward and backward
- **Type-Safe Migrations**: TypeScript-based migration files
- **Migration History**: Track applied migrations in the database
- **Multiple Migration Strategies**: Run all, run one, or rollback migrations
## Migration Files
Current migrations in order:
1. **0001-add-next-auth.ts** - NextAuth.js authentication tables
2. **0002-add-signal.ts** - Signal messenger integration
3. **0003-add-whatsapp.ts** - WhatsApp integration
4. **0004-add-voice.ts** - Voice/Twilio integration
5. **0005-add-facebook.ts** - Facebook Messenger integration
6. **0006-add-webhooks.ts** - Webhook configuration
7. **0007-add-settings.ts** - Application settings
8. **0008-add-user-role.ts** - User role management
## Development
### Prerequisites
- Node.js >= 20
- npm >= 10
- PostgreSQL database
- Database connection credentials
### Setup
```bash
# Install dependencies
npm install
# Run all pending migrations
npm run migrate:latest
# Check migration status
npm run migrate:list
```
### Environment Variables
Required environment variables:
- `DATABASE_URL` - PostgreSQL connection string
- `DATABASE_HOST` - Database host
- `DATABASE_NAME` - Database name
- `DATABASE_USER` - Database username
- `DATABASE_PASSWORD` - Database password
### Available Scripts
- `npm run migrate:latest` - Run all pending migrations
- `npm run migrate:up` - Run next pending migration
- `npm run migrate:down` - Rollback last migration
- `npm run migrate:up:all` - Run all migrations (alias)
- `npm run migrate:up:one` - Run one migration
- `npm run migrate:down:all` - Rollback all migrations
- `npm run migrate:down:one` - Rollback one migration
- `npm run migrate:list` - List migration status
- `npm run migrate:make <name>` - Create new migration file
## Creating New Migrations
To create a new migration:
```bash
npm run migrate:make add-new-feature
```
This creates a new timestamped migration file in the `migrations/` directory.
Example migration structure:
```typescript
import { Kysely } from 'kysely'
export async function up(db: Kysely<any>): Promise<void> {
await db.schema
.createTable('new_table')
.addColumn('id', 'serial', (col) => col.primaryKey())
.addColumn('name', 'varchar', (col) => col.notNull())
.addColumn('created_at', 'timestamp', (col) =>
col.defaultTo('now()').notNull()
)
.execute()
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable('new_table').execute()
}
```
## Database Schema
### Core Tables
- **users** - User accounts with roles
- **accounts** - OAuth account connections
- **sessions** - User sessions
- **verification_tokens** - Email verification
### Communication Tables
- **bots** - Bot configurations for each service
- **signal_messages** - Signal message history
- **whatsapp_messages** - WhatsApp message history
- **voice_messages** - Voice/call records
- **facebook_messages** - Facebook message history
### Configuration Tables
- **webhooks** - External webhook endpoints
- **settings** - Application settings
## Best Practices
1. **Test Migrations**: Always test migrations in development first
2. **Backup Database**: Create backups before running migrations in production
3. **Review Changes**: Review migration files before applying
4. **Atomic Operations**: Keep migrations focused and atomic
5. **Rollback Plan**: Ensure down() methods properly reverse changes
## Troubleshooting
### Common Issues
1. **Migration Failed**: Check error logs and database permissions
2. **Locked Migrations**: Check for concurrent migration processes
3. **Missing Tables**: Ensure all previous migrations have run
4. **Connection Issues**: Verify DATABASE_URL and network access
### Recovery
If migrations fail:
1. Check migration history table
2. Manually verify database state
3. Run specific migrations as needed
4. Use rollback if necessary
## Integration
Migrations are used by:
- **bridge-frontend** - Requires migrated schema
- **bridge-worker** - Depends on message tables
- **bridge-whatsapp** - Uses bot configuration tables

View file

@ -10,6 +10,9 @@ import {
CamelCasePlugin,
} from "kysely";
import pkg from "pg";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-migrations-migrate');
const { Pool } = pkg;
import * as dotenv from "dotenv";
@ -72,17 +75,17 @@ export const migrate = async (arg: string) => {
results?.forEach((it) => {
if (it.status === "Success") {
console.log(
logger.info(
`Migration "${it.migrationName} ${it.direction.toLowerCase()}" was executed successfully`,
);
} else if (it.status === "Error") {
console.error(`Failed to execute migration "${it.migrationName}"`);
logger.error(`Failed to execute migration "${it.migrationName}"`);
}
});
if (error) {
console.error("Failed to migrate");
console.error(error);
logger.error("Failed to migrate");
logger.error(error);
process.exit(1);
}

View file

@ -1,6 +1,6 @@
{
"name": "@link-stack/bridge-migrations",
"version": "2.2.0",
"version": "3.3.0",
"type": "module",
"scripts": {
"migrate:up:all": "tsx migrate.ts up:all",
@ -9,16 +9,17 @@
"migrate:down:one": "tsx migrate.ts down:one"
},
"dependencies": {
"dotenv": "^16.4.5",
"kysely": "0.26.1",
"pg": "^8.13.0",
"tsx": "^4.19.1"
"@link-stack/logger": "workspace:*",
"dotenv": "^17.2.3",
"kysely": "0.27.5",
"pg": "^8.16.3",
"tsx": "^4.20.6"
},
"devDependencies": {
"@types/node": "^22",
"@types/pg": "^8.11.10",
"@link-stack/eslint-config": "*",
"@link-stack/typescript-config": "*",
"@types/node": "^24",
"@types/pg": "^8.15.5",
"@link-stack/eslint-config": "workspace:*",
"@link-stack/typescript-config": "workspace:*",
"typescript": "^5"
}
}

View file

@ -2,30 +2,39 @@ FROM node:22-bookworm-slim AS base
FROM base AS builder
ARG APP_DIR=/opt/bridge-whatsapp
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN mkdir -p ${APP_DIR}/
RUN npm i -g turbo
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
RUN pnpm add -g turbo
WORKDIR ${APP_DIR}
COPY . .
RUN turbo prune --scope=@link-stack/bridge-whatsapp --docker
FROM base AS installer
ARG APP_DIR=/opt/bridge-whatsapp
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
WORKDIR ${APP_DIR}
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
COPY --from=builder ${APP_DIR}/out/json/ .
COPY --from=builder ${APP_DIR}/out/full/ .
COPY --from=builder ${APP_DIR}/out/package-lock.json ./package-lock.json
RUN npm ci
RUN npm i -g turbo
COPY --from=builder ${APP_DIR}/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN pnpm install --frozen-lockfile
RUN pnpm add -g turbo
RUN turbo run build --filter=@link-stack/bridge-whatsapp
FROM base as runner
ARG BUILD_DATE
ARG VERSION
ARG APP_DIR=/opt/bridge-whatsapp
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN mkdir -p ${APP_DIR}/
RUN DEBIAN_FRONTEND=noninteractive apt-get update && \
apt-get install -y --no-install-recommends \
dumb-init
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
WORKDIR ${APP_DIR}
COPY --from=installer ${APP_DIR} ./
RUN chown -R node:node ${APP_DIR}

View file

@ -0,0 +1,172 @@
# Bridge WhatsApp
WhatsApp integration service for the CDR Link communication bridge system.
## Overview
Bridge WhatsApp provides a REST API for sending and receiving WhatsApp messages using the Baileys library (WhatsApp Web API). It handles bot session management, message routing, and media processing for WhatsApp communication channels.
## Features
- **Bot Management**: Register and manage multiple WhatsApp bot sessions
- **Message Handling**: Send and receive text messages with formatting
- **Media Support**: Handle images, documents, audio, and video files
- **QR Code Authentication**: Web-based WhatsApp authentication
- **REST API**: Simple HTTP endpoints for integration
## Development
### Prerequisites
- Node.js >= 20
- npm >= 10
- PostgreSQL database (for bot configuration)
### Setup
```bash
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run development server
npm run dev
# Start production server
npm run start
```
### Environment Variables
- `PORT` - Server port (default: 5000)
- `DATABASE_URL` - PostgreSQL connection string (optional)
- Additional WhatsApp-specific configuration as needed
### Available Scripts
- `npm run build` - Compile TypeScript
- `npm run dev` - Development mode with auto-reload
- `npm run start` - Start production server
## API Endpoints
### Bot Management
- `POST /api/bots/:token` - Register/initialize a bot
- `GET /api/bots/:token` - Get bot status and QR code
### Messaging
- `POST /api/bots/:token/send` - Send a message
- `POST /api/bots/:token/receive` - Webhook for incoming messages
### Request/Response Format
#### Send Message
```json
{
"to": "1234567890@s.whatsapp.net",
"message": "Hello World",
"media": {
"url": "https://example.com/image.jpg",
"type": "image"
}
}
```
#### Receive Message Webhook
```json
{
"from": "1234567890@s.whatsapp.net",
"message": "Hello",
"timestamp": "2024-01-01T00:00:00Z",
"media": {
"url": "https://...",
"type": "image",
"mimetype": "image/jpeg"
}
}
```
## Architecture
### Server Framework
Built with Hapi.js for:
- Route validation
- Plugin architecture
- Error handling
- Request lifecycle
### WhatsApp Integration
Uses @whiskeysockets/baileys:
- WhatsApp Web protocol
- Multi-device support
- Message encryption
- Media handling
### Session Management
- File-based session storage
- Automatic reconnection
- QR code regeneration
- Session cleanup
## Media Handling
Supported media types:
- **Images**: JPEG, PNG, GIF
- **Documents**: PDF, DOC, DOCX
- **Audio**: MP3, OGG, WAV
- **Video**: MP4, AVI
Media is processed and uploaded before sending.
## Error Handling
- Connection errors trigger reconnection
- Invalid sessions regenerate QR codes
- API errors return appropriate HTTP status codes
- Comprehensive logging for debugging
## Security
- Token-based bot authentication
- Message validation
- Rate limiting (configurable)
- Secure session storage
## Integration
Designed to work with:
- **bridge-worker**: Processes WhatsApp message jobs
- **bridge-frontend**: Manages bot configuration
- External webhooks for message routing
## Docker Support
```bash
# Build image
docker build -t link-stack/bridge-whatsapp .
# Run container
docker run -p 5000:5000 link-stack/bridge-whatsapp
```
## Testing
While test configuration exists (jest.config.json), tests should be implemented for:
- API endpoint validation
- Message processing logic
- Session management
- Error scenarios

View file

@ -2,4 +2,4 @@
set -e
echo "starting bridge-whatsapp"
exec dumb-init npm run start
exec dumb-init pnpm run start

View file

@ -1,26 +1,29 @@
{
"name": "@link-stack/bridge-whatsapp",
"version": "2.2.0",
"version": "3.3.0",
"main": "build/main/index.js",
"author": "Darren Clarke <darren@redaranj.com>",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@adiwajshing/keyed-db": "0.2.4",
"@hapi/hapi": "^21.3.10",
"@hapi/hapi": "^21.4.3",
"@hapipal/schmervice": "^3.0.0",
"@hapipal/toys": "^4.0.0",
"@whiskeysockets/baileys": "^6.7.8",
"hapi-pino": "^12.1.0",
"link-preview-js": "^3.0.5"
"@link-stack/bridge-common": "workspace:*",
"@link-stack/logger": "workspace:*",
"@whiskeysockets/baileys": "^6.7.21",
"hapi-pino": "^13.0.0",
"link-preview-js": "^3.1.0"
},
"devDependencies": {
"@link-stack/eslint-config": "*",
"@link-stack/jest-config": "*",
"@link-stack/typescript-config": "*",
"@link-stack/eslint-config": "workspace:*",
"@link-stack/jest-config": "workspace:*",
"@link-stack/typescript-config": "workspace:*",
"@types/long": "^5",
"@types/node": "*",
"dotenv-cli": "^7.4.2",
"tsx": "^4.19.1",
"typescript": "^5.6.2"
"dotenv-cli": "^10.0.0",
"tsx": "^4.20.6",
"typescript": "^5.9.3"
},
"scripts": {
"build": "tsc -p tsconfig.json",

View file

@ -9,6 +9,9 @@ import {
SendMessageRoute,
ReceiveMessageRoute,
} from "./routes.js";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-whatsapp-index');
const server = Hapi.server({ port: 5000 });
@ -34,6 +37,6 @@ const main = async () => {
};
main().catch((err) => {
console.error(err);
logger.error(err);
process.exit(1);
});

View file

@ -17,6 +17,7 @@ const getService = (request: Hapi.Request): WhatsappService => {
interface MessageRequest {
phoneNumber: string;
message: string;
attachments?: Array<{ data: string; filename: string; mime_type: string }>;
}
export const SendMessageRoute = withDefaults({
@ -26,11 +27,23 @@ export const SendMessageRoute = withDefaults({
description: "Send a message",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
console.log({ payload: request.payload });
const { phoneNumber, message } = request.payload as MessageRequest;
const { phoneNumber, message, attachments } =
request.payload as MessageRequest;
const whatsappService = getService(request);
await whatsappService.send(id, phoneNumber, message as string);
request.logger.info({ id }, "Sent a message at %s", new Date());
await whatsappService.send(
id,
phoneNumber,
message as string,
attachments,
);
request.logger.info(
{
id,
attachmentCount: attachments?.length || 0,
},
"Sent a message at %s",
new Date().toISOString(),
);
return _h
.response({
@ -56,7 +69,7 @@ export const ReceiveMessageRoute = withDefaults({
const date = new Date();
const twoDaysAgo = new Date(date.getTime());
twoDaysAgo.setDate(date.getDate() - 2);
request.logger.info({ id }, "Received messages at %s", new Date());
request.logger.info({ id }, "Received messages at %s", new Date().toISOString());
return whatsappService.receive(id, twoDaysAgo);
},

View file

@ -11,6 +11,14 @@ import makeWASocket, {
useMultiFileAuthState,
} from "@whiskeysockets/baileys";
import fs from "fs";
import { createLogger } from "@link-stack/logger";
import {
getMaxAttachmentSize,
getMaxTotalAttachmentSize,
MAX_ATTACHMENTS,
} from "@link-stack/bridge-common";
const logger = createLogger("bridge-whatsapp-service");
export type AuthCompleteCallback = (error?: string) => void;
@ -33,7 +41,24 @@ export default class WhatsappService extends Service {
}
getBotDirectory(id: string): string {
return `${this.getBaseDirectory()}/${id}`;
// Validate that ID contains only safe characters (alphanumeric, dash, underscore)
if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
throw new Error(`Invalid bot ID format: ${id}`);
}
// Prevent path traversal by checking for suspicious patterns
if (id.includes('..') || id.includes('/') || id.includes('\\')) {
throw new Error(`Path traversal detected in bot ID: ${id}`);
}
const botPath = `${this.getBaseDirectory()}/${id}`;
// Ensure the resolved path is still within the base directory
if (!botPath.startsWith(this.getBaseDirectory())) {
throw new Error(`Invalid bot path: ${botPath}`);
}
return botPath;
}
getAuthDirectory(id: string): string {
@ -57,7 +82,7 @@ export default class WhatsappService extends Service {
try {
connection.end(null);
} catch (error) {
console.log(error);
logger.error({ error }, "Connection reset error");
}
}
this.connections = {};
@ -92,27 +117,27 @@ export default class WhatsappService extends Service {
isNewLogin,
} = update;
if (qr) {
console.log("got qr code");
logger.info("got qr code");
const botDirectory = this.getBotDirectory(botID);
const qrPath = `${botDirectory}/qr.txt`;
fs.writeFileSync(qrPath, qr, "utf8");
} else if (isNewLogin) {
console.log("got new login");
logger.info("got new login");
const botDirectory = this.getBotDirectory(botID);
const verifiedFile = `${botDirectory}/verified`;
fs.writeFileSync(verifiedFile, "");
} else if (connectionState === "open") {
console.log("opened connection");
logger.info("opened connection");
} else if (connectionState === "close") {
console.log("connection closed due to ", lastDisconnect?.error);
logger.info({ lastDisconnect }, "connection closed");
const disconnectStatusCode = (lastDisconnect?.error as any)?.output
?.statusCode;
if (disconnectStatusCode === DisconnectReason.restartRequired) {
console.log("reconnecting after got new login");
logger.info("reconnecting after got new login");
await this.createConnection(botID, server, options);
authCompleteCallback?.();
} else if (disconnectStatusCode !== DisconnectReason.loggedOut) {
console.log("reconnecting");
logger.info("reconnecting");
await this.sleep(pause);
pause *= 2;
this.createConnection(botID, server, options);
@ -121,12 +146,12 @@ export default class WhatsappService extends Service {
}
if (events["creds.update"]) {
console.log("creds update");
logger.info("creds update");
await saveCreds();
}
if (events["messages.upsert"]) {
console.log("messages upsert");
logger.info("messages upsert");
const upsert = events["messages.upsert"];
const { messages } = upsert;
if (messages) {
@ -143,13 +168,16 @@ export default class WhatsappService extends Service {
const baseDirectory = this.getBaseDirectory();
const botIDs = fs.readdirSync(baseDirectory);
console.log({ botIDs });
for await (const botID of botIDs) {
const directory = this.getBotDirectory(botID);
const verifiedFile = `${directory}/verified`;
if (fs.existsSync(verifiedFile)) {
const { version, isLatest } = await fetchLatestBaileysVersion();
console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);
logger.info(
{ version: version.join("."), isLatest },
"using WA version",
);
await this.createConnection(botID, this.server, {
browser: WhatsappService.browserDescription,
@ -169,7 +197,13 @@ export default class WhatsappService extends Service {
message,
messageTimestamp,
} = webMessageInfo;
console.log(webMessageInfo);
logger.info("Message type debug");
for (const key in message) {
logger.info(
{ key, exists: !!message[key as keyof proto.IMessage] },
"Message field",
);
}
const isValidMessage =
message && remoteJid !== "status@broadcast" && !fromMe;
if (isValidMessage) {
@ -186,19 +220,22 @@ export default class WhatsappService extends Service {
if (isMediaMessage) {
if (audioMessage) {
messageType = "audio";
filename = id + "." + audioMessage.mimetype?.split("/").pop();
const extension = audioMessage.mimetype?.split("/").pop() || "audio";
filename = `${id}.${extension}`;
mimeType = audioMessage.mimetype;
} else if (documentMessage) {
messageType = "document";
filename = documentMessage.fileName;
filename = documentMessage.fileName || `${id}.bin`;
mimeType = documentMessage.mimetype;
} else if (imageMessage) {
messageType = "image";
filename = id + "." + imageMessage.mimetype?.split("/").pop();
const extension = imageMessage.mimetype?.split("/").pop() || "jpg";
filename = `${id}.${extension}`;
mimeType = imageMessage.mimetype;
} else if (videoMessage) {
messageType = "video";
filename = id + "." + videoMessage.mimetype?.split("/").pop();
const extension = videoMessage.mimetype?.split("/").pop() || "mp4";
filename = `${id}.${extension}`;
mimeType = videoMessage.mimetype;
}
@ -271,8 +308,30 @@ export default class WhatsappService extends Service {
}
async unverify(botID: string): Promise<void> {
// Step 1: Close and remove the active connection if it exists
const connection = this.connections[botID];
if (connection?.socket) {
try {
// Properly close the WebSocket connection
await connection.socket.logout();
} catch (error) {
logger.warn({ botID, error }, "Error during logout, forcing disconnect");
try {
connection.socket.end(undefined);
} catch (endError) {
logger.warn({ botID, endError }, "Error ending socket connection");
}
}
}
// Step 2: Remove from in-memory connections
delete this.connections[botID];
// Step 3: Remove the bot directory (auth state, QR code, verified marker)
const botDirectory = this.getBotDirectory(botID);
fs.rmSync(botDirectory, { recursive: true, force: true });
if (fs.existsSync(botDirectory)) {
fs.rmSync(botDirectory, { recursive: true, force: true });
}
}
async register(
@ -293,10 +352,75 @@ export default class WhatsappService extends Service {
botID: string,
phoneNumber: string,
message: string,
attachments?: Array<{ data: string; filename: string; mime_type: string }>,
): Promise<void> {
const connection = this.connections[botID]?.socket;
const recipient = `${phoneNumber.replace(/\D+/g, "")}@s.whatsapp.net`;
await connection.sendMessage(recipient, { text: message });
// Send text message if provided
if (message) {
await connection.sendMessage(recipient, { text: message });
}
// Send attachments if provided with size validation
if (attachments && attachments.length > 0) {
const MAX_ATTACHMENT_SIZE = getMaxAttachmentSize();
const MAX_TOTAL_SIZE = getMaxTotalAttachmentSize();
if (attachments.length > MAX_ATTACHMENTS) {
throw new Error(`Too many attachments: ${attachments.length} (max ${MAX_ATTACHMENTS})`);
}
let totalSize = 0;
for (const attachment of attachments) {
// Calculate size before converting to buffer
const estimatedSize = (attachment.data.length * 3) / 4;
if (estimatedSize > MAX_ATTACHMENT_SIZE) {
logger.warn({
filename: attachment.filename,
size: estimatedSize,
maxSize: MAX_ATTACHMENT_SIZE
}, 'Attachment exceeds size limit, skipping');
continue;
}
totalSize += estimatedSize;
if (totalSize > MAX_TOTAL_SIZE) {
logger.warn({
totalSize,
maxTotalSize: MAX_TOTAL_SIZE
}, 'Total attachment size exceeds limit, skipping remaining');
break;
}
const buffer = Buffer.from(attachment.data, "base64");
if (attachment.mime_type.startsWith("image/")) {
await connection.sendMessage(recipient, {
image: buffer,
caption: attachment.filename,
});
} else if (attachment.mime_type.startsWith("video/")) {
await connection.sendMessage(recipient, {
video: buffer,
caption: attachment.filename,
});
} else if (attachment.mime_type.startsWith("audio/")) {
await connection.sendMessage(recipient, {
audio: buffer,
mimetype: attachment.mime_type,
});
} else {
await connection.sendMessage(recipient, {
document: buffer,
fileName: attachment.filename,
mimetype: attachment.mime_type,
});
}
}
}
}
async receive(

View file

@ -8,7 +8,7 @@
"outDir": "build/main",
"rootDir": "src",
"skipLibCheck": true,
"types": ["node", "long"],
"types": ["node"],
"lib": ["es2020", "DOM"],
"composite": true
},

View file

@ -2,26 +2,35 @@ FROM node:22-bookworm-slim AS base
FROM base AS builder
ARG APP_DIR=/opt/bridge-worker
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN mkdir -p ${APP_DIR}/
RUN npm i -g turbo
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
RUN pnpm add -g turbo
WORKDIR ${APP_DIR}
COPY . .
RUN turbo prune --scope=@link-stack/bridge-worker --docker
FROM base AS installer
ARG APP_DIR=/opt/bridge-worker
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
WORKDIR ${APP_DIR}
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
COPY --from=builder ${APP_DIR}/out/json/ .
COPY --from=builder ${APP_DIR}/out/full/ .
COPY --from=builder ${APP_DIR}/out/package-lock.json ./package-lock.json
RUN npm ci
RUN npm i -g turbo
COPY --from=builder ${APP_DIR}/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN pnpm install --frozen-lockfile
RUN pnpm add -g turbo
RUN turbo run build --filter=@link-stack/bridge-worker
FROM base as runner
ARG BUILD_DATE
ARG VERSION
ARG APP_DIR=/opt/bridge-worker
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
RUN mkdir -p ${APP_DIR}/
RUN DEBIAN_FRONTEND=noninteractive apt-get update && \
apt-get install -y --no-install-recommends \

View file

@ -0,0 +1,144 @@
# Bridge Worker
Background job processor for handling asynchronous tasks in the CDR Link communication bridge system.
## Overview
Bridge Worker uses Graphile Worker to process queued jobs for message handling, media conversion, webhook notifications, and scheduled tasks. It manages the flow of messages between various communication channels (Signal, WhatsApp, Facebook, Voice) and the Zammad ticketing system.
## Features
- **Message Processing**: Handle incoming/outgoing messages for all supported channels
- **Media Conversion**: Convert audio/video files between formats
- **Webhook Notifications**: Notify external systems of events
- **Scheduled Tasks**: Cron-based job scheduling
- **Job Queue Management**: Reliable job processing with retries
- **Multi-Channel Support**: Signal, WhatsApp, Facebook, Voice (Twilio)
## Development
### Prerequisites
- Node.js >= 20
- npm >= 10
- PostgreSQL database
- Redis (for caching)
- FFmpeg (for media conversion)
### Setup
```bash
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run development server with auto-reload
npm run dev
# Start production worker
npm run start
```
### Environment Variables
Required environment variables:
- `DATABASE_URL` - PostgreSQL connection string
- `GRAPHILE_WORKER_CONCURRENCY` - Number of concurrent jobs (default: 10)
- `GRAPHILE_WORKER_POLL_INTERVAL` - Job poll interval in ms (default: 1000)
- `ZAMMAD_URL` - Zammad instance URL
- `ZAMMAD_API_TOKEN` - Zammad API token
- `TWILIO_ACCOUNT_SID` - Twilio account SID
- `TWILIO_AUTH_TOKEN` - Twilio auth token
- `SIGNAL_CLI_URL` - Signal CLI REST API URL
- `WHATSAPP_SERVICE_URL` - WhatsApp bridge service URL
- `FACEBOOK_APP_SECRET` - Facebook app secret
- `FACEBOOK_PAGE_ACCESS_TOKEN` - Facebook page token
### Available Scripts
- `npm run build` - Compile TypeScript
- `npm run dev` - Development mode with watch
- `npm run start` - Start production worker
## Task Types
### Signal Tasks
- `receive-signal-message` - Process incoming Signal messages
- `send-signal-message` - Send outgoing Signal messages
- `fetch-signal-messages` - Fetch messages from Signal CLI
### WhatsApp Tasks
- `receive-whatsapp-message` - Process incoming WhatsApp messages
- `send-whatsapp-message` - Send outgoing WhatsApp messages
### Facebook Tasks
- `receive-facebook-message` - Process incoming Facebook messages
- `send-facebook-message` - Send outgoing Facebook messages
### Voice Tasks
- `receive-voice-message` - Process incoming voice calls/messages
- `send-voice-message` - Send voice messages via Twilio
- `twilio-recording` - Handle Twilio call recordings
- `voice-line-audio-update` - Update voice line audio
- `voice-line-delete` - Delete voice line
- `voice-line-provider-update` - Update voice provider settings
### Common Tasks
- `notify-webhooks` - Send webhook notifications
- `import-label-studio` - Import Label Studio annotations
## Architecture
### Job Processing
Jobs are queued in PostgreSQL using Graphile Worker:
```typescript
await addJob('send-signal-message', {
to: '+1234567890',
message: 'Hello world'
})
```
### Cron Schedule
Scheduled tasks are configured in `crontab`:
- Periodic message fetching
- Cleanup tasks
- Health checks
### Error Handling
- Automatic retries with exponential backoff
- Dead letter queue for failed jobs
- Comprehensive logging with winston
## Media Handling
Supports conversion between formats:
- Audio: MP3, OGG, WAV, M4A
- Uses fluent-ffmpeg for processing
- Automatic format detection
## Integration Points
- **Zammad**: Creates/updates tickets via API
- **Signal CLI**: REST API for Signal messaging
- **WhatsApp Bridge**: HTTP API for WhatsApp
- **Twilio**: Voice and SMS capabilities
- **Facebook**: Graph API for Messenger
## Docker Support
```bash
# Build image
docker build -t link-stack/bridge-worker .
# Run with docker-compose
docker-compose -f docker/compose/bridge.yml up
```
The worker includes cron support via built-in crontab.

View file

@ -1 +1,2 @@
*/1 * * * * fetch-signal-messages ?max=1&id=fetchSignalMessagesCron {"scheduleTasks": "true"}
*/2 * * * * check-group-membership ?max=1&id=checkGroupMembershipCron {}

View file

@ -2,4 +2,4 @@
set -e
echo "starting bridge-worker"
exec dumb-init npm run start
exec dumb-init pnpm run start

View file

@ -1,11 +1,14 @@
import type {} from "graphile-config";
import type {} from "graphile-worker";
const preset: GraphileConfig.Preset = {
const preset: any = {
worker: {
connectionString: process.env.DATABASE_URL,
maxPoolSize: 10,
pollInterval: 2000,
maxPoolSize: process.env.BRIDGE_WORKER_POOL_SIZE
? parseInt(process.env.BRIDGE_WORKER_POOL_SIZE, 10)
: 10,
pollInterval: process.env.BRIDGE_WORKER_POLL_INTERVAL
? parseInt(process.env.BRIDGE_WORKER_POLL_INTERVAL, 10)
: 2000,
fileExtensions: [".ts"],
},
};

View file

@ -1,18 +1,27 @@
import { run } from "graphile-worker";
import { createLogger } from "@link-stack/logger";
import * as path from "path";
import { fileURLToPath } from "url";
const logger = createLogger("bridge-worker");
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const startWorker = async () => {
console.log("Starting worker...");
console.log(process.env);
logger.info("Starting worker...");
await run({
connectionString: process.env.DATABASE_URL,
concurrency: 10,
noHandleSignals: false,
pollInterval: 1000,
concurrency: process.env.BRIDGE_WORKER_CONCURRENCY
? parseInt(process.env.BRIDGE_WORKER_CONCURRENCY, 10)
: 10,
maxPoolSize: process.env.BRIDGE_WORKER_POOL_SIZE
? parseInt(process.env.BRIDGE_WORKER_POOL_SIZE, 10)
: 10,
pollInterval: process.env.BRIDGE_WORKER_POLL_INTERVAL
? parseInt(process.env.BRIDGE_WORKER_POLL_INTERVAL, 10)
: 1000,
taskDirectory: `${__dirname}/tasks`,
crontabFile: `${__dirname}/crontab`,
});
@ -23,6 +32,15 @@ const main = async () => {
};
main().catch((err) => {
console.error(err);
logger.error(
{
error: err,
message: err.message,
stack: err.stack,
name: err.name,
},
"Worker failed to start",
);
console.error("Full error:", err);
process.exit(1);
});

View file

@ -1,8 +1,6 @@
/* eslint-disable camelcase */
// import { SavedVoiceProvider } from "@digiresilience/bridge-db";
import Twilio from "twilio";
import { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
import { Zammad, getOrCreateUser } from "./zammad.js";
type SavedVoiceProvider = any;
@ -20,52 +18,3 @@ export const twilioClientFor = (
});
};
export const createZammadTicket = async (
call: CallInstance,
mp3: Buffer,
): Promise<void> => {
const title = `Call from ${call.fromFormatted} at ${call.startTime}`;
const body = `<ul>
<li>Caller: ${call.fromFormatted}</li>
<li>Service Number: ${call.toFormatted}</li>
<li>Call Duration: ${call.duration} seconds</li>
<li>Start Time: ${call.startTime}</li>
<li>End Time: ${call.endTime}</li>
</ul>
<p>See the attached recording.</p>`;
const filename = `${call.sid}-${call.startTime}.mp3`;
const zammad = Zammad(
{
token: "EviH_WL0p6YUlCoIER7noAZEAPsYA_fVU4FZCKdpq525Vmzzvl8d7dNuP_8d-Amb",
},
"https://demo.digiresilience.org",
);
try {
const customer = await getOrCreateUser(zammad, call.fromFormatted);
await zammad.ticket.create({
title,
group: "Finances",
note: "This ticket was created automaticaly from a recorded phone call.",
customer_id: customer.id,
article: {
body,
subject: title,
content_type: "text/html",
type: "note",
attachments: [
{
filename,
data: mp3.toString("base64"),
"mime-type": "audio/mpeg",
},
],
},
});
} catch (error: any) {
console.log(Object.keys(error));
if (error.isBoom) {
console.log(error.output);
throw new Error("Failed to create zamamd ticket");
}
}
};

View file

@ -0,0 +1,272 @@
import { createLogger } from "@link-stack/logger";
const logger = createLogger('formstack-field-mapping');
/**
* Field mapping configuration for Formstack to Zammad integration
*
* This configuration is completely flexible - you define your own internal field names
* and map them to both Formstack source fields and Zammad custom fields.
*/
export interface FieldMappingConfig {
/**
* Map internal field keys to Formstack field names
*
* Required keys (system):
* - formId: The Formstack Form ID field
* - uniqueId: The Formstack submission unique ID field
*
* Optional keys with special behavior:
* - email: Used for user lookup/creation (if provided)
* - phone: Used for user lookup/creation (if provided)
* - signalAccount: Used for Signal-based user lookup (tried first before phone)
* - name: User's full name (can be nested object with first/last, used in user creation)
* - organization: Used in ticket title template placeholder {organization}
* - typeOfSupport: Used in ticket title template placeholder {typeOfSupport}
* - descriptionOfIssue: Used as article subject (defaults to "Support Request" if not provided)
*
* All other keys are completely arbitrary and defined by your form.
*/
sourceFields: Record<string, string>;
/**
* Map Zammad custom field names to internal field keys (from sourceFields)
*
* Example:
* {
* "us_state": "state", // Zammad field "us_state" gets value from sourceFields["state"]
* "zip_code": "zipCode", // Zammad field "zip_code" gets value from sourceFields["zipCode"]
* "custom_field": "myField" // Any custom field mapping
* }
*
* The values in this object must correspond to keys in sourceFields.
*/
zammadFields: Record<string, string>;
/**
* Configuration for ticket creation
*/
ticket: {
/** Zammad group name to assign tickets to */
group: string;
/** Article type name (e.g., "note", "cdr_signal", "email") */
defaultArticleType: string;
/**
* Template for ticket title
* Supports placeholders: {name}, {organization}, {typeOfSupport}
* Placeholders reference internal field keys from sourceFields
*/
titleTemplate?: string;
};
/**
* Configuration for extracting nested field values
*/
nestedFields?: {
/**
* How to extract first/last name from a nested Name field
* Example: { firstNamePath: "first", lastNamePath: "last" }
* for a field like { "Name": { "first": "John", "last": "Doe" } }
*/
name?: {
firstNamePath?: string;
lastNamePath?: string;
};
};
}
let cachedMapping: FieldMappingConfig | null = null;
/**
* Load field mapping configuration from environment variable (REQUIRED)
*/
export function loadFieldMapping(): FieldMappingConfig {
if (cachedMapping) {
return cachedMapping;
}
const configJson = process.env.FORMSTACK_FIELD_MAPPING;
if (!configJson) {
throw new Error(
'FORMSTACK_FIELD_MAPPING environment variable is required. ' +
'Please set it to a JSON string containing your field mapping configuration.'
);
}
logger.info('Loading Formstack field mapping from environment variable');
try {
const config = JSON.parse(configJson) as FieldMappingConfig;
// Validate required sections exist
if (!config.sourceFields || typeof config.sourceFields !== 'object') {
throw new Error('Invalid field mapping configuration: sourceFields must be an object');
}
if (!config.zammadFields || typeof config.zammadFields !== 'object') {
throw new Error('Invalid field mapping configuration: zammadFields must be an object');
}
if (!config.ticket || typeof config.ticket !== 'object') {
throw new Error('Invalid field mapping configuration: ticket must be an object');
}
// Validate required ticket fields
if (!config.ticket.group) {
throw new Error('Invalid field mapping configuration: ticket.group is required');
}
if (!config.ticket.defaultArticleType) {
throw new Error('Invalid field mapping configuration: ticket.defaultArticleType is required');
}
// Validate required source fields
const systemRequiredFields = ['formId', 'uniqueId'];
for (const field of systemRequiredFields) {
if (!config.sourceFields[field]) {
throw new Error(`Invalid field mapping configuration: sourceFields.${field} is required (system field)`);
}
}
// Validate zammadFields reference valid sourceFields
for (const [zammadField, sourceKey] of Object.entries(config.zammadFields)) {
if (!config.sourceFields[sourceKey]) {
logger.warn(
{ zammadField, sourceKey },
'Zammad field maps to non-existent source field key'
);
}
}
logger.info('Successfully loaded Formstack field mapping configuration');
cachedMapping = config;
return cachedMapping;
} catch (error) {
logger.error({
error: error instanceof Error ? error.message : error,
jsonLength: configJson.length
}, 'Failed to parse field mapping configuration');
throw new Error(
`Failed to parse Formstack field mapping JSON: ${error instanceof Error ? error.message : error}`
);
}
}
/**
* Get a field value from formData using the source field name mapping
*/
export function getFieldValue(
formData: any,
internalFieldKey: string,
mapping?: FieldMappingConfig
): any {
const config = mapping || loadFieldMapping();
const sourceFieldName = config.sourceFields[internalFieldKey];
if (!sourceFieldName) {
return undefined;
}
return formData[sourceFieldName];
}
/**
* Get a nested field value (e.g., Name.first)
*/
export function getNestedFieldValue(
fieldValue: any,
path: string | undefined
): any {
if (!path || !fieldValue) {
return undefined;
}
const parts = path.split('.');
let current = fieldValue;
for (const part of parts) {
if (current && typeof current === 'object') {
current = current[part];
} else {
return undefined;
}
}
return current;
}
/**
* Format field value (handle arrays, objects, etc.)
*/
export function formatFieldValue(value: any): string | undefined {
if (value === null || value === undefined || value === '') {
return undefined;
}
if (Array.isArray(value)) {
return value.join(', ');
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
}
/**
* Build ticket title from template and data
* Replaces placeholders like {name}, {organization}, {typeOfSupport} with provided values
*/
export function buildTicketTitle(
mapping: FieldMappingConfig,
data: Record<string, string | undefined>
): string {
const template = mapping.ticket.titleTemplate || '{name}';
let title = template;
// Replace all placeholders in the template
for (const [key, value] of Object.entries(data)) {
const placeholder = `{${key}}`;
if (title.includes(placeholder)) {
if (value) {
title = title.replace(placeholder, value);
} else {
// Remove empty placeholder and surrounding separators
title = title.replace(` - ${placeholder}`, '').replace(`${placeholder} - `, '').replace(placeholder, '');
}
}
}
return title.trim();
}
/**
* Get all Zammad field values from form data using the mapping
* Returns an object with Zammad field names as keys and formatted values
*/
export function getZammadFieldValues(
formData: any,
mapping?: FieldMappingConfig
): Record<string, string> {
const config = mapping || loadFieldMapping();
const result: Record<string, string> = {};
for (const [zammadFieldName, sourceKey] of Object.entries(config.zammadFields)) {
const value = getFieldValue(formData, sourceKey, config);
const formatted = formatFieldValue(value);
if (formatted !== undefined) {
result[zammadFieldName] = formatted;
}
}
return result;
}
/**
* Reset cached mapping (useful for testing)
*/
export function resetMappingCache(): void {
cachedMapping = null;
}

View file

@ -1,11 +0,0 @@
//import { defState } from "@digiresilience/montar";
//import { configureLogger } from "@digiresilience/bridge-common";
// import config from "@digiresilience/bridge-config";
//export const logger = defState("workerLogger", {
// start: async () => configureLogger(config),
//});
//export default logger;
export const logger = {};
export default logger;

View file

@ -1,6 +1,9 @@
import { Readable } from "stream";
import ffmpeg from "fluent-ffmpeg";
import * as R from "remeda";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-worker-media-convert');
const requiredCodecs = ["mp3", "webm", "wav"];
@ -25,7 +28,7 @@ const defaultAudioConvertOpts = {
**/
export const convert = (
input: Buffer,
opts?: AudioConvertOpts
opts?: AudioConvertOpts,
): Promise<Buffer> => {
const settings = { ...defaultAudioConvertOpts, ...opts };
return new Promise((resolve, reject) => {
@ -35,12 +38,8 @@ export const convert = (
.audioCodec(settings.audioCodec)
.audioBitrate(settings.bitrate)
.toFormat(settings.format)
.on("error", (err, stdout, stderr) => {
console.error(err.message);
console.log("FFMPEG OUTPUT");
console.log(stdout);
console.log("FFMPEG ERROR");
console.log(stderr);
.on("error", (err, _stdout, _stderr) => {
logger.error({ error: err }, 'FFmpeg conversion error');
reject(err);
})
.on("end", () => {
@ -62,12 +61,16 @@ export const selfCheck = (): Promise<boolean> => {
return new Promise((resolve) => {
ffmpeg.getAvailableFormats((err, codecs) => {
if (err) {
console.error("FFMPEG error:", err);
logger.error({ error: err }, 'FFMPEG error');
resolve(false);
}
const preds = R.map(requiredCodecs, (codec) => (available: any) =>
available[codec] && available[codec].canDemux && available[codec].canMux
const preds = R.map(
requiredCodecs,
(codec) => (available: any) =>
available[codec] &&
available[codec].canDemux &&
available[codec].canMux,
);
resolve(R.allPass(codecs, preds));
@ -79,6 +82,6 @@ export const assertFfmpegAvailable = async (): Promise<void> => {
const r = await selfCheck();
if (!r)
throw new Error(
`ffmpeg is not installed, could not be located, or does not support the required codecs: ${requiredCodecs}`
`ffmpeg is not installed, could not be located, or does not support the required codecs: ${requiredCodecs}`,
);
};

View file

@ -19,11 +19,13 @@ export interface Ticket {
export interface ZammadClient {
ticket: {
create: (data: any) => Promise<Ticket>;
update: (id: number, data: any) => Promise<Ticket>;
};
user: {
search: (data: any) => Promise<User[]>;
create: (data: any) => Promise<User>;
};
get: (path: string) => Promise<any>;
}
export type ZammadCredentials =
@ -39,7 +41,7 @@ const formatAuth = (credentials: any) => {
return (
"Basic " +
Buffer.from(`${credentials.username}:${credentials.password}`).toString(
"base64"
"base64",
)
);
}
@ -54,7 +56,7 @@ const formatAuth = (credentials: any) => {
export const Zammad = (
credentials: ZammadCredentials,
host: string,
opts?: ZammadClientOpts
opts?: ZammadClientOpts,
): ZammadClient => {
const extraHeaders = (opts && opts.headers) || {};
@ -73,6 +75,12 @@ export const Zammad = (
const { payload: result } = await wreck.post("tickets", { payload });
return result as Ticket;
},
update: async (id, payload) => {
const { payload: result } = await wreck.put(`tickets/${id}`, {
payload,
});
return result as Ticket;
},
},
user: {
search: async (query) => {
@ -85,22 +93,79 @@ export const Zammad = (
return result as User;
},
},
get: async (path) => {
const { payload: result } = await wreck.get(path);
return result;
},
};
};
/**
* Sanitizes phone number to E.164 format: +15554446666
* Strips all non-digit characters except +, ensures + prefix
* @param phoneNumber - Raw phone number (e.g., "(555) 444-6666", "5554446666", "+1 555 444 6666")
* @returns E.164 formatted phone number (e.g., "+15554446666")
* @throws Error if phone number is invalid
*/
export const sanitizePhoneNumber = (phoneNumber: string): string => {
// Remove all characters except digits and +
let cleaned = phoneNumber.replace(/[^\d+]/g, "");
// Ensure it starts with +
if (!cleaned.startsWith("+")) {
// Assume US/Canada if no country code (11 digits starting with 1, or 10 digits)
if (cleaned.length === 10) {
cleaned = "+1" + cleaned;
} else if (cleaned.length === 11 && cleaned.startsWith("1")) {
cleaned = "+" + cleaned;
} else if (cleaned.length >= 10) {
// International number without +, add it
cleaned = "+" + cleaned;
}
}
// Validate E.164 format: + followed by 10-15 digits
if (!/^\+\d{10,15}$/.test(cleaned)) {
throw new Error(`Invalid phone number format: ${phoneNumber}`);
}
return cleaned;
};
export const getUser = async (zammad: ZammadClient, phoneNumber: string) => {
const mungedNumber = phoneNumber.replace("+", "");
const results = await zammad.user.search(`phone:${mungedNumber}`);
// Sanitize to E.164 format
const sanitized = sanitizePhoneNumber(phoneNumber);
// Remove + for Zammad search query
const searchNumber = sanitized.replace("+", "");
// Try sanitized format first (e.g., "6464229653" for "+16464229653")
let results = await zammad.user.search(`phone:${searchNumber}`);
if (results.length > 0) return results[0];
// Fall back to searching for original input (handles legacy formatted numbers)
// This ensures we can find users with "(646) 422-9653" format in database
const originalCleaned = phoneNumber.replace(/[^\d+]/g, "").replace("+", "");
if (originalCleaned !== searchNumber) {
results = await zammad.user.search(`phone:${originalCleaned}`);
if (results.length > 0) return results[0];
}
return undefined;
};
export const getOrCreateUser = async (zammad: ZammadClient, phoneNumber: string) => {
export const getOrCreateUser = async (
zammad: ZammadClient,
phoneNumber: string,
) => {
const customer = await getUser(zammad, phoneNumber);
if (customer) return customer;
// Sanitize phone number to E.164 format before storing
const sanitized = sanitizePhoneNumber(phoneNumber);
return zammad.user.create({
phone: phoneNumber,
note: "User created by Grabadora from incoming voice call",
phone: sanitized,
note: "User created from incoming voice call",
});
};

View file

@ -1,6 +1,6 @@
{
"name": "@link-stack/bridge-worker",
"version": "2.2.0",
"version": "3.3.0",
"type": "module",
"main": "build/main/index.js",
"author": "Darren Clarke <darren@redaranj.com>",
@ -12,18 +12,19 @@
},
"dependencies": {
"@hapi/wreck": "^18.1.0",
"@link-stack/bridge-common": "*",
"@link-stack/signal-api": "*",
"@link-stack/bridge-common": "workspace:*",
"@link-stack/logger": "workspace:*",
"@link-stack/signal-api": "workspace:*",
"fluent-ffmpeg": "^2.1.3",
"graphile-worker": "^0.16.6",
"remeda": "^2.14.0",
"twilio": "^5.3.2"
"remeda": "^2.32.0",
"twilio": "^5.10.2"
},
"devDependencies": {
"@types/fluent-ffmpeg": "^2.1.26",
"dotenv-cli": "^7.4.2",
"@link-stack/eslint-config": "*",
"@link-stack/typescript-config": "*",
"typescript": "^5.6.2"
"@types/fluent-ffmpeg": "^2.1.27",
"dotenv-cli": "^10.0.0",
"@link-stack/eslint-config": "workspace:*",
"@link-stack/typescript-config": "workspace:*",
"typescript": "^5.9.3"
}
}

View file

@ -0,0 +1,121 @@
#!/usr/bin/env node
/**
* Check Signal group membership status and update Zammad tickets
*
* This task queries the Signal CLI API to check if users have joined
* their assigned groups. When a user joins (moves from pendingInvites to members),
* it updates the ticket's group_joined flag in Zammad.
*
* Note: This task sends webhooks for all group members every time it runs.
* The Zammad webhook handler is idempotent and will ignore duplicate notifications
* if group_joined is already true.
*/
import { db, getWorkerUtils } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
import * as signalApi from "@link-stack/signal-api";
const logger = createLogger("check-group-membership");
const { Configuration, GroupsApi } = signalApi;
interface CheckGroupMembershipTaskOptions {
// Optional: Check specific group. If not provided, checks all groups with group_joined=false
groupId?: string;
botToken?: string;
}
const checkGroupMembershipTask = async (
options: CheckGroupMembershipTaskOptions = {},
): Promise<void> => {
const config = new Configuration({
basePath: process.env.BRIDGE_SIGNAL_URL,
});
const groupsClient = new GroupsApi(config);
const worker = await getWorkerUtils();
// Get all Signal bots
const bots = await db.selectFrom("SignalBot").selectAll().execute();
for (const bot of bots) {
try {
logger.debug(
{ botId: bot.id, phoneNumber: bot.phoneNumber },
"Checking groups for bot",
);
// Get all groups for this bot
const groups = await groupsClient.v1GroupsNumberGet({
number: bot.phoneNumber,
});
logger.debug(
{ botId: bot.id, groupCount: groups.length },
"Retrieved groups from Signal CLI",
);
// For each group, check if we have tickets waiting for members to join
for (const group of groups) {
if (!group.id || !group.internalId) {
logger.debug({ groupName: group.name }, "Skipping group without ID");
continue;
}
// Log info about each group temporarily for debugging
logger.info(
{
groupId: group.id,
groupName: group.name,
membersCount: group.members?.length || 0,
members: group.members,
pendingInvitesCount: group.pendingInvites?.length || 0,
pendingInvites: group.pendingInvites,
pendingRequestsCount: group.pendingRequests?.length || 0,
},
"Checking group membership",
);
// Notify Zammad about each member who has joined
// This handles both cases:
// 1. New contacts who must accept invite (they move from pendingInvites to members)
// 2. Existing contacts who are auto-added (they appear directly in members)
if (group.members && group.members.length > 0) {
for (const memberPhone of group.members) {
// Check if this member was previously pending
// We'll send the webhook and let Zammad decide if it needs to update
await worker.addJob("common/notify-webhooks", {
backendId: bot.id,
payload: {
event: "group_member_joined",
group_id: group.id,
member_phone: memberPhone,
timestamp: new Date().toISOString(),
},
});
logger.info(
{
groupId: group.id,
memberPhone,
},
"Notified Zammad about group member",
);
}
}
}
} catch (error: any) {
logger.error(
{
botId: bot.id,
error: error.message,
stack: error.stack,
},
"Error checking group membership for bot",
);
}
}
logger.info("Completed group membership check");
};
export default checkGroupMembershipTask;

View file

@ -1,4 +1,7 @@
import { db } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('notify-webhooks');
export interface NotifyWebhooksOptions {
backendId: string;
@ -9,6 +12,11 @@ const notifyWebhooksTask = async (
options: NotifyWebhooksOptions,
): Promise<void> => {
const { backendId, payload } = options;
logger.debug({
backendId,
payloadKeys: Object.keys(payload),
}, 'Processing webhook notification');
const webhooks = await db
.selectFrom("Webhook")
@ -16,16 +24,48 @@ const notifyWebhooksTask = async (
.where("backendId", "=", backendId)
.execute();
logger.debug({ count: webhooks.length, backendId }, 'Found webhooks');
for (const webhook of webhooks) {
const { endpointUrl, httpMethod, headers } = webhook;
const finalHeaders = { "Content-Type": "application/json", ...headers };
console.log({ endpointUrl, httpMethod, headers, finalHeaders });
const result = await fetch(endpointUrl, {
const body = JSON.stringify(payload);
logger.debug({
url: endpointUrl,
method: httpMethod,
headers: finalHeaders,
body: JSON.stringify(payload),
});
console.log(result);
bodyLength: body.length,
headerKeys: Object.keys(finalHeaders),
}, 'Sending webhook');
try {
const result = await fetch(endpointUrl, {
method: httpMethod,
headers: finalHeaders,
body,
});
logger.debug({
url: endpointUrl,
status: result.status,
statusText: result.statusText,
ok: result.ok,
}, 'Webhook response');
if (!result.ok) {
const responseText = await result.text();
logger.error({
url: endpointUrl,
status: result.status,
responseSample: responseText.substring(0, 500),
}, 'Webhook error response');
}
} catch (error) {
logger.error({
url: endpointUrl,
error: error instanceof Error ? error.message : error,
}, 'Webhook request failed');
}
}
};

View file

@ -1,4 +1,7 @@
import { db } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-worker-send-facebook-message');
interface SendFacebookMessageTaskOptions {
token: string;
@ -31,9 +34,8 @@ const sendFacebookMessageTask = async (
headers: { "Content-Type": "application/json" },
body: JSON.stringify(outgoingMessage),
});
console.log({ response });
} catch (error) {
console.error({ error });
logger.error({ error });
throw error;
}
};

View file

@ -1,6 +1,9 @@
import { db, getWorkerUtils } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
import * as signalApi from "@link-stack/signal-api";
const logger = createLogger("fetch-signal-messages");
const { Configuration, MessagesApi, AttachmentsApi } = signalApi;
const config = new Configuration({
basePath: process.env.BRIDGE_SIGNAL_URL,
@ -21,8 +24,23 @@ const fetchAttachments = async (attachments: any[] | undefined) => {
const arrayBuffer = await blob.arrayBuffer();
const base64Attachment = Buffer.from(arrayBuffer).toString("base64");
// Generate default filename if not provided by Signal API
let defaultFilename = name;
if (!defaultFilename) {
// Check if id already has an extension
const hasExtension = id.includes(".");
if (hasExtension) {
// ID already includes extension
defaultFilename = id;
} else {
// Add extension based on content type
const extension = contentType?.split("/")[1] || "bin";
defaultFilename = `${id}.${extension}`;
}
}
const formattedAttachment = {
filename: name,
filename: defaultFilename,
mimeType: contentType,
attachment: base64Attachment,
};
@ -46,21 +64,109 @@ const processMessage = async ({
message: msg,
}: ProcessMessageArgs): Promise<Record<string, any>[]> => {
const { envelope } = msg;
console.log(envelope);
const { source, sourceUuid, dataMessage } = envelope;
const { source, sourceUuid, dataMessage, syncMessage, receiptMessage, typingMessage } =
envelope;
// Log all envelope types to understand what events we're receiving
logger.info(
{
source,
sourceUuid,
hasDataMessage: !!dataMessage,
hasSyncMessage: !!syncMessage,
hasReceiptMessage: !!receiptMessage,
hasTypingMessage: !!typingMessage,
envelopeKeys: Object.keys(envelope),
},
"Received Signal envelope",
);
const isGroup = !!(
dataMessage?.groupV2 ||
dataMessage?.groupContext ||
dataMessage?.groupInfo
);
// Check if this is a group membership change event
const groupInfo = dataMessage?.groupInfo;
if (groupInfo) {
logger.info(
{
type: groupInfo.type,
groupId: groupInfo.groupId,
source,
groupInfoKeys: Object.keys(groupInfo),
fullGroupInfo: groupInfo,
},
"Received group info event",
);
// If user joined the group, notify Zammad
if (groupInfo.type === "JOIN" || groupInfo.type === "JOINED") {
const worker = await getWorkerUtils();
const groupId = groupInfo.groupId
? `group.${Buffer.from(groupInfo.groupId).toString("base64")}`
: null;
if (groupId) {
await worker.addJob("common/notify-webhooks", {
backendId: id,
payload: {
event: "group_member_joined",
group_id: groupId,
member_phone: source,
timestamp: new Date().toISOString(),
},
});
logger.info(
{
groupId,
memberPhone: source,
},
"User joined Signal group, notifying Zammad",
);
}
}
}
if (!dataMessage) return [];
const { attachments } = dataMessage;
const rawTimestamp = dataMessage?.timestamp;
logger.debug(
{
sourceUuid,
source,
rawTimestamp,
hasGroupV2: !!dataMessage?.groupV2,
hasGroupContext: !!dataMessage?.groupContext,
hasGroupInfo: !!dataMessage?.groupInfo,
isGroup,
groupV2Id: dataMessage?.groupV2?.id,
groupContextType: dataMessage?.groupContext?.type,
groupInfoType: dataMessage?.groupInfo?.type,
},
"Processing message",
);
const timestamp = new Date(rawTimestamp);
const formattedAttachments = await fetchAttachments(attachments);
const primaryAttachment = formattedAttachments[0] ?? {};
const additionalAttachments = formattedAttachments.slice(1);
const groupId =
dataMessage?.groupV2?.id ||
dataMessage?.groupContext?.id ||
dataMessage?.groupInfo?.groupId;
const toRecipient = groupId
? `group.${Buffer.from(groupId).toString("base64")}`
: phoneNumber;
const primaryMessage = {
token: id,
to: phoneNumber,
to: toRecipient,
from: source,
messageId: `${sourceUuid}-${rawTimestamp}`,
message: dataMessage?.message,
@ -68,6 +174,7 @@ const processMessage = async ({
attachment: primaryAttachment.attachment,
filename: primaryAttachment.filename,
mimeType: primaryAttachment.mimeType,
isGroup,
};
const formattedMessages = [primaryMessage];
@ -119,19 +226,29 @@ const fetchSignalMessagesTask = async ({
number: phoneNumber,
});
logger.debug({ botId: id, phoneNumber }, "Fetching messages for bot");
for (const message of messages) {
const formattedMessages = await processMessage({
id,
phoneNumber,
message,
});
console.log({ formattedMessages });
for (const formattedMessage of formattedMessages) {
if (formattedMessage.to !== formattedMessage.from) {
await worker.addJob(
"signal/receive-signal-message",
formattedMessage,
logger.debug(
{
messageId: formattedMessage.messageId,
from: formattedMessage.from,
to: formattedMessage.to,
isGroup: formattedMessage.isGroup,
hasMessage: !!formattedMessage.message,
hasAttachment: !!formattedMessage.attachment,
},
"Creating job for message",
);
await worker.addJob("signal/receive-signal-message", formattedMessage);
}
}
}

View file

@ -0,0 +1,436 @@
import { createLogger } from "@link-stack/logger";
import { db } from "@link-stack/bridge-common";
import { Zammad, getUser, sanitizePhoneNumber } from "../../lib/zammad.js";
import {
loadFieldMapping,
getFieldValue,
getNestedFieldValue,
formatFieldValue,
buildTicketTitle,
getZammadFieldValues,
type FieldMappingConfig,
} from "../../lib/formstack-field-mapping.js";
const logger = createLogger("create-ticket-from-form");
export interface CreateTicketFromFormOptions {
formData: any;
receivedAt: string;
}
const createTicketFromFormTask = async (
options: CreateTicketFromFormOptions,
): Promise<void> => {
const { formData, receivedAt } = options;
// Load field mapping configuration
const mapping = loadFieldMapping();
// Log only non-PII metadata using configured field names
const formId = getFieldValue(formData, "formId", mapping);
const uniqueId = getFieldValue(formData, "uniqueId", mapping);
logger.info(
{
formId,
uniqueId,
receivedAt,
fieldCount: Object.keys(formData).length,
},
"Processing Formstack form submission",
);
// Extract fields using dynamic mapping
const nameField = getFieldValue(formData, "name", mapping);
const firstName = mapping.nestedFields?.name?.firstNamePath
? getNestedFieldValue(nameField, mapping.nestedFields.name.firstNamePath) || ""
: "";
const lastName = mapping.nestedFields?.name?.lastNamePath
? getNestedFieldValue(nameField, mapping.nestedFields.name.lastNamePath) || ""
: "";
const fullName =
firstName && lastName
? `${firstName} ${lastName}`.trim()
: firstName || lastName || "Unknown";
// Extract well-known fields used for special logic (all optional)
const email = getFieldValue(formData, "email", mapping);
const rawPhone = getFieldValue(formData, "phone", mapping);
const rawSignalAccount = getFieldValue(formData, "signalAccount", mapping);
const organization = getFieldValue(formData, "organization", mapping);
const typeOfSupport = getFieldValue(formData, "typeOfSupport", mapping);
const descriptionOfIssue = getFieldValue(formData, "descriptionOfIssue", mapping);
// Sanitize phone numbers to E.164 format (+15554446666)
let phone: string | undefined;
if (rawPhone) {
try {
phone = sanitizePhoneNumber(rawPhone);
logger.info({ rawPhone, sanitized: phone }, "Sanitized phone number");
} catch (error: any) {
logger.warn({ rawPhone, error: error.message }, "Invalid phone number format, ignoring");
phone = undefined;
}
}
let signalAccount: string | undefined;
if (rawSignalAccount) {
try {
signalAccount = sanitizePhoneNumber(rawSignalAccount);
logger.info({ rawSignalAccount, sanitized: signalAccount }, "Sanitized signal account");
} catch (error: any) {
logger.warn({ rawSignalAccount, error: error.message }, "Invalid signal account format, ignoring");
signalAccount = undefined;
}
}
// Validate that at least one contact method is provided
if (!email && !phone && !signalAccount) {
logger.error(
{ formId, uniqueId },
"No contact information provided - at least one of email, phone, or signalAccount is required",
);
throw new Error(
"At least one contact method (email, phone, or signalAccount) is required for ticket creation",
);
}
// Build ticket title using configured template
// Pass all potentially used fields - the template determines which are actually used
const title = buildTicketTitle(mapping, {
name: fullName,
organization: formatFieldValue(organization),
typeOfSupport: formatFieldValue(typeOfSupport),
});
// Build article body - format all fields as HTML
const formatAllFields = (data: any): string => {
let html = "";
// Add formatted name field first if we have it
if (fullName && fullName !== "Unknown") {
html += `<strong>Name:</strong><br>${fullName}<br>`;
}
for (const [key, value] of Object.entries(data)) {
// Skip metadata fields and name field (we already formatted it above)
const skipFields = [
mapping.sourceFields.formId,
mapping.sourceFields.uniqueId,
mapping.sourceFields.name, // Skip raw name field
"HandshakeKey",
].filter(Boolean);
if (skipFields.includes(key)) continue;
if (value === null || value === undefined || value === "") continue;
const displayValue = Array.isArray(value)
? value.join(", ")
: typeof value === "object"
? JSON.stringify(value)
: value;
html += `<strong>${key}:</strong><br>${displayValue}<br>`;
}
return html;
};
const body = formatAllFields(formData);
// Get Zammad configuration from environment
const zammadUrl = process.env.ZAMMAD_URL || "http://zammad-nginx:8080";
const zammadToken = process.env.ZAMMAD_API_TOKEN;
if (!zammadToken) {
logger.error("ZAMMAD_API_TOKEN environment variable is not configured");
throw new Error("ZAMMAD_API_TOKEN is required");
}
const zammad = Zammad({ token: zammadToken }, zammadUrl);
try {
// Look up the configured article type
let articleTypeId: number | undefined;
try {
const articleTypes = await zammad.get("ticket_article_types");
const configuredType = articleTypes.find(
(t: any) => t.name === mapping.ticket.defaultArticleType,
);
articleTypeId = configuredType?.id;
if (articleTypeId) {
logger.info(
{ articleTypeId, typeName: mapping.ticket.defaultArticleType },
"Found configured article type",
);
} else {
logger.warn(
{ typeName: mapping.ticket.defaultArticleType },
"Configured article type not found, ticket will use default type",
);
}
} catch (error: any) {
logger.warn({ error: error.message }, "Failed to look up article type");
}
// Get or create user
// Try to find existing user by: phone -> email
// Note: We can't search by Signal account since Signal group IDs aren't phone numbers
let customer;
// Try phone if provided
if (phone) {
customer = await getUser(zammad, phone);
if (customer) {
logger.info(
{ customerId: customer.id, method: "phone" },
"Found existing user by phone",
);
}
}
// Fall back to email if no customer found yet
if (!customer && email) {
// Validate email format before using in search
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (emailRegex.test(email)) {
const emailResults = await zammad.user.search(`email:${email}`);
if (emailResults.length > 0) {
customer = emailResults[0];
logger.info(
{ customerId: customer.id, method: "email" },
"Found existing user by email",
);
}
} else {
logger.warn({ email }, "Invalid email format provided, skipping email search");
}
}
if (!customer) {
// Create new user
logger.info("Creating new user from form submission");
// Build user data with whatever contact info we have
const userData: any = {
firstname: firstName,
lastname: lastName,
roles: ["Customer"],
};
// Add contact info only if provided
if (email) {
userData.email = email;
}
// Use phone number if provided (don't use Signal group ID as phone)
if (phone) {
userData.phone = phone;
}
customer = await zammad.user.create(userData);
}
logger.info(
{
customerId: customer.id,
email: customer.email,
},
"Using customer for ticket",
);
// Look up the configured group
const groups = await zammad.get("groups");
const targetGroup = groups.find((g: any) => g.name === mapping.ticket.group);
if (!targetGroup) {
logger.error({ groupName: mapping.ticket.group }, "Configured group not found");
throw new Error(`Zammad group "${mapping.ticket.group}" not found`);
}
logger.info(
{ groupId: targetGroup.id, groupName: targetGroup.name },
"Using configured group",
);
// Build custom fields using Zammad field mapping
// This dynamically maps all configured fields without hardcoding
const customFields = getZammadFieldValues(formData, mapping);
// Check if this is a Signal ticket
let signalArticleType = null;
let signalChannelId = null;
let signalBotToken = null;
if (signalAccount) {
try {
logger.info({ signalAccount }, "Looking up Signal channel and article type");
// Look up Signal channels from Zammad (admin-only endpoint)
// Note: bot_token is NOT included in this response for security reasons
const channels = await zammad.get("cdr_signal_channels");
if (channels.length > 0) {
const zammadChannel = channels[0]; // Use first active Signal channel
signalChannelId = zammadChannel.id;
logger.info(
{
channelId: zammadChannel.id,
phoneNumber: zammadChannel.phone_number,
},
"Found active Signal channel from Zammad",
);
// Look up the bot_token from our own cdr database using the phone number
const signalBot = await db
.selectFrom("SignalBot")
.selectAll()
.where("phoneNumber", "=", zammadChannel.phone_number)
.executeTakeFirst();
if (signalBot) {
signalBotToken = signalBot.token;
logger.info(
{ botId: signalBot.id, phoneNumber: signalBot.phoneNumber },
"Found Signal bot token from cdr database",
);
} else {
logger.warn(
{ phoneNumber: zammadChannel.phone_number },
"Signal bot not found in cdr database",
);
}
} else {
logger.warn("No active Signal channels found");
}
// Look up cdr_signal article type
const articleTypes = await zammad.get("ticket_article_types");
signalArticleType = articleTypes.find((t: any) => t.name === "cdr_signal");
if (!signalArticleType) {
logger.warn("Signal article type (cdr_signal) not found, using default type");
} else {
logger.info(
{ articleTypeId: signalArticleType.id },
"Found Signal article type",
);
}
} catch (error: any) {
logger.warn(
{ error: error.message },
"Failed to look up Signal article type, creating regular ticket",
);
}
}
// Create the ticket
const articleData: any = {
subject: descriptionOfIssue || "Support Request",
body,
content_type: "text/html",
internal: false,
};
// Use Signal article type if available, otherwise use configured default
if (signalArticleType) {
articleData.type_id = signalArticleType.id;
logger.info({ typeId: signalArticleType.id }, "Using Signal article type");
// IMPORTANT: Set sender to "Customer" for Signal tickets created from Formstack
// This prevents the article from being echoed back to the user via Signal
// (enqueue_communicate_cdr_signal_job only sends if sender != 'Customer')
articleData.sender = "Customer";
} else if (articleTypeId) {
articleData.type_id = articleTypeId;
}
const ticketData: any = {
title,
group_id: targetGroup.id,
customer_id: customer.id,
article: articleData,
...customFields,
};
// Add Signal preferences if we have Signal channel and article type
// Note: signalAccount from Formstack is the phone number the user typed in
// Groups are added later via update_group webhook from bridge-worker
if (signalChannelId && signalBotToken && signalArticleType && signalAccount) {
ticketData.preferences = {
channel_id: signalChannelId,
cdr_signal: {
bot_token: signalBotToken,
chat_id: signalAccount, // Use Signal phone number as chat_id
},
};
logger.info(
{
channelId: signalChannelId,
chatId: signalAccount,
},
"Adding Signal preferences to ticket",
);
}
logger.info(
{
title,
groupId: targetGroup.id,
customerId: customer.id,
hasArticleType: !!articleTypeId || !!signalArticleType,
isSignalTicket: !!signalArticleType && !!signalAccount,
customFieldCount: Object.keys(customFields).length,
},
"Creating ticket",
);
const ticket = await zammad.ticket.create(ticketData);
// Set create_article_type_id for Signal tickets to enable proper replies
if (signalArticleType && signalChannelId) {
try {
await zammad.ticket.update(ticket.id, {
create_article_type_id: signalArticleType.id,
});
logger.info(
{
ticketId: ticket.id,
articleTypeId: signalArticleType.id,
},
"Set create_article_type_id for Signal ticket",
);
} catch (error: any) {
logger.warn(
{
error: error.message,
ticketId: ticket.id,
},
"Failed to set create_article_type_id, ticket may not support Signal replies",
);
}
}
logger.info(
{
ticketId: ticket.id,
ticketNumber: ticket.id,
title,
isSignalTicket: !!signalChannelId,
},
"Successfully created ticket from Formstack submission",
);
} catch (error: any) {
logger.error(
{
error: error.message,
stack: error.stack,
formId,
uniqueId,
},
"Failed to create ticket from Formstack submission",
);
throw error;
}
};
export default createTicketFromFormTask;

View file

@ -1,213 +0,0 @@
/* eslint-disable camelcase */
/*
import { convert } from "html-to-text";
import { URLSearchParams } from "url";
import { withDb, AppDatabase } from "../../lib/db.js";
// import { loadConfig } from "@digiresilience/bridge-config";
import { tagMap } from "../../lib/tag-map.js";
const config: any = {};
type FormattedZammadTicket = {
data: Record<string, unknown>;
predictions: Record<string, unknown>[];
};
const getZammadTickets = async (
page: number,
minUpdatedTimestamp: Date,
): Promise<[boolean, FormattedZammadTicket[]]> => {
const {
leafcutter: { zammadApiUrl, zammadApiKey, contributorName, contributorId },
} = config;
const headers = { Authorization: `Token ${zammadApiKey}` };
let shouldContinue = false;
const docs = [];
const ticketsQuery = new URLSearchParams({
expand: "true",
sort_by: "updated_at",
order_by: "asc",
query: "state.name: closed",
per_page: "25",
page: `${page}`,
});
const rawTickets = await fetch(
`${zammadApiUrl}/tickets/search?${ticketsQuery}`,
{ headers },
);
const tickets: any = await rawTickets.json();
console.log({ tickets });
if (!tickets || tickets.length === 0) {
return [shouldContinue, docs];
}
for await (const ticket of tickets) {
const { id: source_id, created_at, updated_at, close_at } = ticket;
const source_created_at = new Date(created_at);
const source_updated_at = new Date(updated_at);
const source_closed_at = new Date(close_at);
shouldContinue = true;
if (source_closed_at <= minUpdatedTimestamp) {
console.log(`Skipping ticket`, {
source_id,
source_updated_at,
source_closed_at,
minUpdatedTimestamp,
});
continue;
}
console.log(`Processing ticket`, {
source_id,
source_updated_at,
source_closed_at,
minUpdatedTimestamp,
});
const rawArticles = await fetch(
`${zammadApiUrl}/ticket_articles/by_ticket/${source_id}`,
{ headers },
);
const articles: any = await rawArticles.json();
let articleText = "";
for (const article of articles) {
const { content_type: contentType, body } = article;
if (contentType === "text/html") {
const cleanArticleText = convert(body);
articleText += cleanArticleText + "\n\n";
} else {
articleText += body + "\n\n";
}
}
const tagsQuery = new URLSearchParams({
object: "Ticket",
o_id: source_id,
});
const rawTags = await fetch(`${zammadApiUrl}/tags?${tagsQuery}`, {
headers,
});
const { tags }: any = await rawTags.json();
const transformedTags = [];
for (const tag of tags) {
const outputs = tagMap[tag];
if (outputs) {
transformedTags.push(...outputs);
}
}
const doc: FormattedZammadTicket = {
data: {
ticket: articleText,
contributor_id: contributorId,
source_id,
source_closed_at,
source_created_at,
source_updated_at,
},
predictions: [],
};
const result = transformedTags.map((tag) => {
return {
type: "choices",
value: {
choices: [tag.value],
},
to_name: "ticket",
from_name: tag.field,
};
});
if (result.length > 0) {
doc.predictions.push({
model_version: `${contributorName}TranslatorV1`,
result,
});
}
docs.push(doc);
}
return [shouldContinue, docs];
};
const fetchFromZammad = async (
minUpdatedTimestamp: Date,
): Promise<FormattedZammadTicket[]> => {
const pages = [...Array.from({ length: 10000 }).keys()];
const allTickets: FormattedZammadTicket[] = [];
for await (const page of pages) {
const [shouldContinue, tickets] = await getZammadTickets(
page + 1,
minUpdatedTimestamp,
);
if (!shouldContinue) {
break;
}
if (tickets.length > 0) {
allTickets.push(...tickets);
}
}
return allTickets;
};
const sendToLabelStudio = async (tickets: FormattedZammadTicket[]) => {
const {
leafcutter: { labelStudioApiUrl, labelStudioApiKey },
} = config;
const headers = {
Authorization: `Token ${labelStudioApiKey}`,
"Content-Type": "application/json",
Accept: "application/json",
};
for await (const ticket of tickets) {
const res = await fetch(`${labelStudioApiUrl}/projects/1/import`, {
method: "POST",
headers,
body: JSON.stringify([ticket]),
});
const importResult = await res.json();
console.log(JSON.stringify(importResult, undefined, 2));
}
};
*/
const importLabelStudioTask = async (): Promise<void> => {
/*
withDb(async (db: AppDatabase) => {
const {
leafcutter: { contributorName },
} = config;
const settingName = `${contributorName}ImportLabelStudioTask`;
const res: any = await db.settings.findByName(settingName);
const startTimestamp = res?.value?.minUpdatedTimestamp
? new Date(res.value.minUpdatedTimestamp as string)
: new Date("2023-03-01");
const tickets = await fetchFromZammad(startTimestamp);
if (tickets.length > 0) {
await sendToLabelStudio(tickets);
const lastTicket = tickets.pop();
const newLastTimestamp = lastTicket.data.source_closed_at;
console.log({ newLastTimestamp });
await db.settings.upsert(settingName, {
minUpdatedTimestamp: newLastTimestamp,
});
}
});
*/
};
export default importLabelStudioTask;

View file

@ -1,177 +0,0 @@
/* eslint-disable camelcase */
/*
import { URLSearchParams } from "url";
import { withDb, AppDatabase } from "../../lib/db.js";
// import { loadConfig } from "@digiresilience/bridge-config";
const config: any = {};
type LabelStudioTicket = {
id: string;
is_labeled: boolean;
annotations: Record<string, unknown>[];
data: Record<string, unknown>;
updated_at: string;
};
type LeafcutterTicket = {
id: string;
incident: string[];
technology: string[];
targeted_group: string[];
country: string[];
region: string[];
continent: string[];
date: Date;
origin: string;
origin_id: string;
source_created_at: string;
source_updated_at: string;
};
const getLabelStudioTickets = async (
page: number,
): Promise<LabelStudioTicket[]> => {
const {
leafcutter: { labelStudioApiUrl, labelStudioApiKey },
} = config;
const headers = {
Authorization: `Token ${labelStudioApiKey}`,
Accept: "application/json",
};
const ticketsQuery = new URLSearchParams({
page_size: "50",
page: `${page}`,
});
console.log({ url: `${labelStudioApiUrl}/projects/1/tasks?${ticketsQuery}` });
const res = await fetch(
`${labelStudioApiUrl}/projects/1/tasks?${ticketsQuery}`,
{ headers },
);
console.log({ res });
const tasksResult: any = await res.json();
console.log({ tasksResult });
return tasksResult;
};
const fetchFromLabelStudio = async (
minUpdatedTimestamp: Date,
): Promise<LabelStudioTicket[]> => {
const pages = [...Array.from({ length: 10000 }).keys()];
const allDocs: LabelStudioTicket[] = [];
for await (const page of pages) {
const docs = await getLabelStudioTickets(page + 1);
console.log({ page, docs });
if (docs && docs.length > 0) {
for (const doc of docs) {
const updatedAt = new Date(doc.updated_at);
console.log({ updatedAt, minUpdatedTimestamp });
if (updatedAt > minUpdatedTimestamp) {
console.log(`Adding doc`, { doc });
allDocs.push(doc);
}
}
} else {
break;
}
}
console.log({ allDocs });
return allDocs;
};
const sendToLeafcutter = async (tickets: LabelStudioTicket[]) => {
const {
leafcutter: {
contributorId,
opensearchApiUrl,
opensearchUsername,
opensearchPassword,
},
} = config;
console.log({ tickets });
const filteredTickets = tickets.filter((ticket) => ticket.is_labeled);
console.log({ filteredTickets });
const finalTickets: LeafcutterTicket[] = filteredTickets.map((ticket) => {
const {
id,
annotations,
data: { source_id, source_created_at, source_updated_at },
} = ticket;
const getTags = (tags: Record<string, any>[], name: string) =>
tags
.filter((tag) => tag.from_name === name)
.map((tag) => tag.value.choices)
.flat();
const allTags = annotations.map(({ result }) => result).flat();
const incident = getTags(allTags, "incidentType tag");
const technology = getTags(allTags, "platform tag");
const country = getTags(allTags, "country tag");
const targetedGroup = getTags(allTags, "targetedGroup tag");
return {
id,
incident,
technology,
targeted_group: targetedGroup,
country,
region: [],
continent: [],
date: new Date(source_created_at as string),
origin: contributorId,
origin_id: source_id as string,
source_created_at: source_created_at as string,
source_updated_at: source_updated_at as string,
};
});
console.log("Sending to Leafcutter");
console.log({ finalTickets });
const result = await fetch(opensearchApiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${Buffer.from(`${opensearchUsername}:${opensearchPassword}`).toString("base64")}`,
},
body: JSON.stringify({ tickets: finalTickets }),
});
};
*/
const importLeafcutterTask = async (): Promise<void> => {
/*
withDb(async (db: AppDatabase) => {
const {
leafcutter: { contributorName },
} = config;
const settingName = `${contributorName}ImportLeafcutterTask`;
const res: any = await db.settings.findByName(settingName);
const startTimestamp = res?.value?.minUpdatedTimestamp
? new Date(res.value.minUpdatedTimestamp as string)
: new Date("2023-03-01");
const newLastTimestamp = new Date();
console.log({
contributorName,
settingName,
res,
startTimestamp,
newLastTimestamp,
});
const tickets = await fetchFromLabelStudio(startTimestamp);
console.log({ tickets });
await sendToLeafcutter(tickets);
await db.settings.upsert(settingName, {
minUpdatedTimestamp: newLastTimestamp,
});
});
*/
};
export default importLeafcutterTask;

View file

@ -1,4 +1,9 @@
import { db, getWorkerUtils } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
import * as signalApi from "@link-stack/signal-api";
const { Configuration, GroupsApi } = signalApi;
const logger = createLogger('bridge-worker-receive-signal-message');
interface ReceiveSignalMessageTaskOptions {
token: string;
@ -10,6 +15,7 @@ interface ReceiveSignalMessageTaskOptions {
attachment?: string;
filename?: string;
mimeType?: string;
isGroup?: boolean;
}
const receiveSignalMessageTask = async ({
@ -22,8 +28,17 @@ const receiveSignalMessageTask = async ({
attachment,
filename,
mimeType,
isGroup,
}: ReceiveSignalMessageTaskOptions): Promise<void> => {
console.log({ token, to, from });
logger.debug({
messageId,
from,
to,
isGroup,
hasMessage: !!message,
hasAttachment: !!attachment,
token,
}, 'Processing incoming message');
const worker = await getWorkerUtils();
const row = await db
.selectFrom("SignalBot")
@ -32,8 +47,170 @@ const receiveSignalMessageTask = async ({
.executeTakeFirstOrThrow();
const backendId = row.id;
let finalTo = to;
let createdInternalId: string | undefined;
// Check if auto-group creation is enabled and this is NOT already a group message
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
logger.debug({
enableAutoGroups,
isGroup,
shouldCreateGroup: enableAutoGroups && !isGroup && from && to,
}, 'Auto-groups config');
// If this is already a group message and auto-groups is enabled,
// use group provided in 'to'
if (enableAutoGroups && isGroup && to) {
// Signal sends the internal ID (base64) in group messages
// We should NOT add "group." prefix - that's for sending messages, not receiving
logger.debug('Message is from existing group with internal ID');
finalTo = to;
} else if (enableAutoGroups && !isGroup && from && to) {
try {
const config = new Configuration({
basePath: process.env.BRIDGE_SIGNAL_URL,
});
const groupsClient = new GroupsApi(config);
// Always create a new group for direct messages to the helpdesk
// This ensures each conversation gets its own group/ticket
logger.info({ from }, 'Creating new group for user');
// Include timestamp to make each group unique
const timestamp = new Date()
.toISOString()
.replace(/[:.]/g, "-")
.substring(0, 19);
const groupName = `Support: ${from} (${timestamp})`;
// Create new group for this conversation
const createGroupResponse = await groupsClient.v1GroupsNumberPost({
number: row.phoneNumber,
data: {
name: groupName,
members: [from],
description: "Private support conversation",
},
});
logger.debug({ createGroupResponse }, 'Group creation response from Signal API');
if (createGroupResponse.id) {
// The createGroupResponse.id already contains the full group identifier (group.BASE64)
finalTo = createGroupResponse.id;
// Fetch the group details to get the actual internalId
// The base64 part of the ID is NOT the same as the internalId!
try {
logger.debug('Fetching group details to get internalId');
const groups = await groupsClient.v1GroupsNumberGet({
number: row.phoneNumber,
});
logger.debug({ groupsSample: groups.slice(0, 3) }, 'Groups for bot');
const createdGroup = groups.find((g) => g.id === finalTo);
if (createdGroup) {
logger.debug({ createdGroup }, 'Found created group details');
}
if (createdGroup && createdGroup.internalId) {
createdInternalId = createdGroup.internalId;
logger.debug({ createdInternalId }, 'Got actual internalId');
} else {
// Fallback: extract base64 part from ID
if (finalTo.startsWith("group.")) {
createdInternalId = finalTo.substring(6);
}
}
} catch (fetchError) {
logger.debug('Could not fetch group details, using ID base64 part');
// Fallback: extract base64 part from ID
if (finalTo.startsWith("group.")) {
createdInternalId = finalTo.substring(6);
}
}
logger.debug({
fullGroupId: finalTo,
internalId: createdInternalId,
}, 'Group created successfully');
logger.debug({
groupId: finalTo,
internalId: createdInternalId,
groupName,
forPhoneNumber: from,
botNumber: row.phoneNumber,
response: createGroupResponse,
}, 'Created new Signal group');
}
// Now handle notifications and message forwarding for both new and existing groups
if (finalTo && finalTo.startsWith("group.")) {
// Forward the user's initial message to the group using quote feature
try {
logger.debug('Forwarding initial message to group using quote feature');
const attributionMessage = `Message from ${from}:\n"${message}"\n\n---\nSupport team: Your request has been received. An agent will respond shortly.`;
await worker.addJob("signal/send-signal-message", {
token: row.token,
to: finalTo,
message: attributionMessage,
conversationId: null,
quoteMessage: message,
quoteAuthor: from,
quoteTimestamp: Date.parse(sentAt),
});
logger.debug({ finalTo }, 'Successfully forwarded initial message to group');
} catch (forwardError) {
logger.error({ error: forwardError }, 'Error forwarding message to group');
}
// Send a response to the original DM informing about the group
try {
logger.debug('Sending group notification to original DM');
const dmNotification = `Hello! A private support group has been created for your conversation.\n\nGroup name: ${groupName}\n\nPlease look for the new group in your Signal app to continue the conversation. Our support team will respond there shortly.\n\nThank you for contacting support!`;
await worker.addJob("signal/send-signal-message", {
token: row.token,
to: from,
message: dmNotification,
conversationId: null,
});
logger.debug('Successfully sent group notification to user DM');
} catch (dmError) {
logger.error({ error: dmError }, 'Error sending DM notification');
}
}
} catch (error: any) {
// Check if error is because group already exists
const errorMessage =
error?.response?.data?.error || error?.message || error;
const isAlreadyExists =
errorMessage?.toString().toLowerCase().includes("already") ||
errorMessage?.toString().toLowerCase().includes("exists");
if (isAlreadyExists) {
logger.debug({ from }, 'Group might already exist, continuing with original recipient');
} else {
logger.error({
error: errorMessage,
from,
to,
botNumber: row.phoneNumber,
}, 'Error creating Signal group');
}
}
}
const payload = {
to,
to: finalTo,
from,
message_id: messageId,
sent_at: sentAt,
@ -41,6 +218,7 @@ const receiveSignalMessageTask = async ({
attachment,
filename,
mime_type: mimeType,
is_group: finalTo.startsWith("group"),
};
await worker.addJob("common/notify-webhooks", { backendId, payload });

View file

@ -1,19 +1,51 @@
import { db } from "@link-stack/bridge-common";
import {
db,
getWorkerUtils,
getMaxAttachmentSize,
getMaxTotalAttachmentSize,
MAX_ATTACHMENTS,
buildSignalGroupName,
} from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
import * as signalApi from "@link-stack/signal-api";
const { Configuration, MessagesApi } = signalApi;
const { Configuration, MessagesApi, GroupsApi } = signalApi;
const logger = createLogger("bridge-worker-send-signal-message");
interface SendSignalMessageTaskOptions {
token: string;
to: string;
message: any;
conversationId?: string; // Zammad ticket/conversation ID for callback
quoteMessage?: string; // Optional: message text to quote
quoteAuthor?: string; // Optional: author of quoted message (phone number)
quoteTimestamp?: number; // Optional: timestamp of quoted message in milliseconds
attachments?: Array<{
data: string; // base64
filename: string;
mime_type: string;
}>;
}
const sendSignalMessageTask = async ({
token,
to,
message,
conversationId,
quoteMessage,
quoteAuthor,
quoteTimestamp,
attachments,
}: SendSignalMessageTaskOptions): Promise<void> => {
console.log({ token, to });
logger.debug(
{
token,
to,
conversationId,
messageLength: message?.length,
},
"Processing outgoing message",
);
const bot = await db
.selectFrom("SignalBot")
.selectAll()
@ -25,18 +57,255 @@ const sendSignalMessageTask = async ({
basePath: process.env.BRIDGE_SIGNAL_URL,
});
const messagesClient = new MessagesApi(config);
const groupsClient = new GroupsApi(config);
const worker = await getWorkerUtils();
let finalTo = to;
let groupCreated = false;
try {
const response = await messagesClient.v2SendPost({
data: {
number,
recipients: [to],
message,
// Check if 'to' is a group ID (UUID format, group.base64 format, or base64) vs phone number
const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
to,
);
const isGroupPrefix = to.startsWith("group.");
const isBase64 = /^[A-Za-z0-9+/]+=*$/.test(to) && to.length > 20; // Base64 internal_id
const isGroupId = isUUID || isGroupPrefix || isBase64;
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
logger.debug(
{
to,
isGroupId,
enableAutoGroups,
shouldCreateGroup: enableAutoGroups && !isGroupId && to && conversationId,
},
"Recipient analysis",
);
// If sending to a phone number and auto-groups is enabled, create a group first
if (enableAutoGroups && !isGroupId && to && conversationId) {
try {
const groupName = buildSignalGroupName(conversationId);
const createGroupResponse = await groupsClient.v1GroupsNumberPost({
number: bot.phoneNumber,
data: {
name: groupName,
members: [to],
description: "Private support conversation",
},
});
if (createGroupResponse.id) {
// The createGroupResponse.id already contains the full group identifier (group.BASE64)
finalTo = createGroupResponse.id;
groupCreated = true;
// Fetch the group details to get the actual internalId
let internalId: string | undefined;
try {
const groups = await groupsClient.v1GroupsNumberGet({
number: bot.phoneNumber,
});
const createdGroup = groups.find((g) => g.id === finalTo);
if (createdGroup && createdGroup.internalId) {
internalId = createdGroup.internalId;
logger.debug({ internalId }, "Got actual internalId");
} else {
// Fallback: extract base64 part from ID
if (finalTo.startsWith("group.")) {
internalId = finalTo.substring(6);
}
}
} catch (fetchError) {
logger.debug("Could not fetch group details, using ID base64 part");
// Fallback: extract base64 part from ID
if (finalTo.startsWith("group.")) {
internalId = finalTo.substring(6);
}
}
logger.debug(
{
groupId: finalTo,
internalId,
groupName,
conversationId,
originalRecipient: to,
botNumber: bot.phoneNumber,
},
"Created new Signal group",
);
// Notify Zammad about the new group ID via webhook
// Set group_joined: false initially - will be updated when user accepts invitation
await worker.addJob("common/notify-webhooks", {
backendId: bot.id,
payload: {
event: "group_created",
conversation_id: conversationId,
original_recipient: to,
group_id: finalTo,
internal_group_id: internalId,
group_joined: false,
timestamp: new Date().toISOString(),
},
});
}
} catch (groupError) {
logger.error(
{
error: groupError instanceof Error ? groupError.message : groupError,
to,
conversationId,
},
"Error creating Signal group",
);
// Continue with original recipient if group creation fails
}
}
logger.debug(
{
fromNumber: number,
toRecipient: finalTo,
originalTo: to,
recipientChanged: to !== finalTo,
groupCreated,
isGroupRecipient: finalTo.startsWith("group."),
},
"Sending message via API",
);
// Build the message data with optional quote parameters
const messageData: signalApi.ApiSendMessageV2 = {
number,
recipients: [finalTo],
message,
};
logger.debug(
{
number,
recipients: [finalTo],
messageLength: message?.length,
hasQuoteParams: !!(quoteMessage && quoteAuthor && quoteTimestamp),
},
"Message data being sent",
);
// Add quote parameters if all are provided
if (quoteMessage && quoteAuthor && quoteTimestamp) {
messageData.quoteTimestamp = quoteTimestamp;
messageData.quoteAuthor = quoteAuthor;
messageData.quoteMessage = quoteMessage;
logger.debug(
{
quoteAuthor,
quoteMessageLength: quoteMessage?.length,
quoteTimestamp,
},
"Including quote in message",
);
}
// Add attachments if provided with size validation
if (attachments && attachments.length > 0) {
const MAX_ATTACHMENT_SIZE = getMaxAttachmentSize();
const MAX_TOTAL_SIZE = getMaxTotalAttachmentSize();
if (attachments.length > MAX_ATTACHMENTS) {
throw new Error(
`Too many attachments: ${attachments.length} (max ${MAX_ATTACHMENTS})`,
);
}
let totalSize = 0;
const validatedAttachments = [];
for (const attachment of attachments) {
// Calculate size from base64 string (rough estimate: length * 3/4)
const estimatedSize = (attachment.data.length * 3) / 4;
if (estimatedSize > MAX_ATTACHMENT_SIZE) {
logger.warn(
{
filename: attachment.filename,
size: estimatedSize,
maxSize: MAX_ATTACHMENT_SIZE,
},
"Attachment exceeds size limit, skipping",
);
continue;
}
totalSize += estimatedSize;
if (totalSize > MAX_TOTAL_SIZE) {
logger.warn(
{
totalSize,
maxTotalSize: MAX_TOTAL_SIZE,
},
"Total attachment size exceeds limit, skipping remaining",
);
break;
}
validatedAttachments.push(attachment.data);
}
if (validatedAttachments.length > 0) {
messageData.base64Attachments = validatedAttachments;
logger.debug(
{
attachmentCount: validatedAttachments.length,
attachmentNames: attachments
.slice(0, validatedAttachments.length)
.map((att) => att.filename),
totalSizeBytes: totalSize,
},
"Including attachments in message",
);
}
}
const response = await messagesClient.v2SendPost({
data: messageData,
});
console.log({ response });
} catch (error) {
console.error({ error });
logger.debug(
{
to: finalTo,
groupCreated,
response: response?.timestamp || "no timestamp",
},
"Message sent successfully",
);
} catch (error: any) {
// Try to get the actual error message from the response
if (error.response) {
try {
const errorBody = await error.response.text();
logger.error(
{
status: error.response.status,
statusText: error.response.statusText,
body: errorBody,
sentTo: finalTo,
messageDetails: {
fromNumber: number,
toRecipients: [finalTo],
hasQuote: !!quoteMessage,
},
},
"Signal API error",
);
} catch (e) {
logger.error("Could not parse error response");
}
}
logger.error({ error }, "Full error details");
throw error;
}
};

View file

@ -3,6 +3,9 @@ import { withDb, AppDatabase } from "../../lib/db.js";
import { twilioClientFor } from "../../lib/common.js";
import { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
import workerUtils from "../../lib/utils.js";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-worker-twilio-recording');
interface WebhookPayload {
startTime: string;
@ -20,7 +23,7 @@ const getTwilioRecording = async (url: string) => {
const { payload } = await Wreck.get(url);
return { recording: payload as Buffer };
} catch (error: any) {
console.error(error.output);
logger.error(error.output);
return { error: error.output };
}
};

View file

@ -23,8 +23,6 @@ const receiveWhatsappMessageTask = async ({
filename,
mimeType,
}: ReceiveWhatsappMessageTaskOptions): Promise<void> => {
console.log({ token, to, from });
const worker = await getWorkerUtils();
const row = await db
.selectFrom("WhatsappBot")

View file

@ -1,15 +1,24 @@
import { db } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
const logger = createLogger("bridge-worker-send-whatsapp-message");
interface SendWhatsappMessageTaskOptions {
token: string;
to: string;
message: any;
attachments?: Array<{
data: string;
filename: string;
mime_type: string;
}>;
}
const sendWhatsappMessageTask = async ({
message,
to,
token,
attachments,
}: SendWhatsappMessageTaskOptions): Promise<void> => {
const bot = await db
.selectFrom("WhatsappBot")
@ -18,16 +27,40 @@ const sendWhatsappMessageTask = async ({
.executeTakeFirstOrThrow();
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${bot.id}/send`;
const params = { message, phoneNumber: to };
const params: any = { message, phoneNumber: to };
if (attachments && attachments.length > 0) {
params.attachments = attachments;
logger.debug(
{
attachmentCount: attachments.length,
attachmentNames: attachments.map((att) => att.filename),
},
"Sending WhatsApp message with attachments",
);
}
try {
const result = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
});
console.log({ result });
if (!result.ok) {
const errorText = await result.text();
logger.error(
{
status: result.status,
errorText,
url,
},
"WhatsApp send failed",
);
throw new Error(`Failed to send message: ${result.status}`);
}
} catch (error) {
console.error({ error });
logger.error({ error });
throw new Error("Failed to send message");
}
};

View file

@ -1,13 +0,0 @@
.git
.idea
**/node_modules
!/node_modules
**/build
**/dist
**/tmp
**/.env*
**/coverage
**/.next
**/amigo.*.json
**/cypress/videos
**/cypress/screenshots

View file

@ -1,38 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
/storybook-static
*.tgz
.vscode

View file

@ -1,51 +0,0 @@
FROM node:22-bookworm-slim AS base
FROM base AS builder
ARG APP_DIR=/opt/leafcutter
RUN mkdir -p ${APP_DIR}/
RUN npm i -g turbo
WORKDIR ${APP_DIR}
COPY . .
RUN turbo prune --scope=@link-stack/leafcutter --docker
FROM base AS installer
ARG APP_DIR=/opt/leafcutter
WORKDIR ${APP_DIR}
COPY --from=builder ${APP_DIR}/.gitignore .gitignore
COPY --from=builder ${APP_DIR}/out/json/ .
COPY --from=builder ${APP_DIR}/out/package-lock.json ./package-lock.json
RUN npm ci
COPY --from=builder ${APP_DIR}/out/full/ .
ARG LINK_EMBEDDED=true
RUN npm i -g turbo
RUN turbo run build --filter=@link-stack/leafcutter
FROM base AS runner
ARG APP_DIR=/opt/leafcutter
WORKDIR ${APP_DIR}/
ARG BUILD_DATE
ARG VERSION
LABEL maintainer="Darren Clarke <darren@redaranj.com>"
LABEL org.label-schema.build-date=$BUILD_DATE
LABEL org.label-schema.version=$VERSION
ENV APP_DIR ${APP_DIR}
RUN DEBIAN_FRONTEND=noninteractive apt-get update && \
apt-get install -y --no-install-recommends \
dumb-init
RUN mkdir -p ${APP_DIR}
RUN chown -R node ${APP_DIR}/
USER node
WORKDIR ${APP_DIR}
COPY --from=installer ${APP_DIR}/node_modules/ ./node_modules/
COPY --from=installer ${APP_DIR}/apps/leafcutter/ ./apps/leafcutter/
COPY --from=installer ${APP_DIR}/package.json ./package.json
USER root
WORKDIR ${APP_DIR}/apps/leafcutter/
RUN chmod +x docker-entrypoint.sh
USER node
EXPOSE 3000
ENV PORT 3000
ENV NODE_ENV production
ENTRYPOINT ["/opt/leafcutter/apps/leafcutter/docker-entrypoint.sh"]

View file

@ -1,616 +0,0 @@
### GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing
under this license.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public
License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your
version supports such interaction) an opportunity to receive the
Corresponding Source of your version by providing access to the
Corresponding Source from a network server at no charge, through some
standard or customary means of facilitating copying of software. This
Corresponding Source shall include the Corresponding Source for any
work covered by version 3 of the GNU General Public License that is
incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View file

@ -1,32 +0,0 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View file

@ -1,114 +0,0 @@
"use client";
import { FC } from "react";
import Link from "next/link";
import Image from "next/legacy/image";
import { Box, Grid, Container, IconButton } from "@mui/material";
import { Apple as AppleIcon, Google as GoogleIcon } from "@mui/icons-material";
import { useTranslate } from "react-polyglot";
import { LanguageSelect } from "app/_components/LanguageSelect";
import LeafcutterLogoLarge from "images/leafcutter-logo-large.png";
import { signIn } from "next-auth/react";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui";
type LoginProps = {
session: any;
};
export const Login: FC<LoginProps> = ({ session }) => {
const t = useTranslate();
const {
colors: { leafcutterElectricBlue, lightGray },
typography: { h1, h4 },
} = useLeafcutterContext();
const buttonStyles = {
backgroundColor: lightGray,
borderRadius: 500,
width: "100%",
fontSize: "16px",
fontWeight: "bold",
};
return (
<>
<Grid container direction="row-reverse" sx={{ p: 3 }}>
<Grid item>
<LanguageSelect />
</Grid>
</Grid>
<Container maxWidth="md" sx={{ mt: 3, mb: 20 }}>
<Grid container spacing={2} direction="column" alignItems="center">
<Grid item>
<Box sx={{ maxWidth: 200 }}>
<Image src={LeafcutterLogoLarge} alt="" objectFit="fill" />
</Box>
</Grid>
<Grid item sx={{ textAlign: "center" }}>
<Box component="h1" sx={{ ...h1, color: leafcutterElectricBlue }}>
{t("welcomeToLeafcutter")}
</Box>
<Box component="h4" sx={{ ...h4, mt: 1 }}>
{t("welcomeToLeafcutterDescription")}
</Box>
</Grid>
<Grid item>
{!session ? (
<Grid
container
spacing={3}
direction="column"
alignItems="center"
sx={{ width: 450, mt: 1 }}
>
<Grid item sx={{ width: "100%" }}>
<IconButton
sx={buttonStyles}
onClick={() =>
signIn("google", {
callbackUrl: `${window.location.origin}/setup`,
})
}
>
<GoogleIcon sx={{ mr: 1 }} />
{`${t("signInWith")} Google`}
</IconButton>
</Grid>
<Grid item sx={{ width: "100%" }}>
<IconButton
sx={buttonStyles}
onClick={() =>
signIn("apple", {
callbackUrl: `${window.location.origin}/setup`,
})
}
>
<AppleIcon sx={{ mr: 1 }} />
{`${t("signInWith")} Apple`}
</IconButton>
</Grid>
<Grid item sx={{ mt: 2 }}>
<Box>
{t("dontHaveAccount")}{" "}
<Link href="mailto:info@digiresilience.org">
{t("requestAccessHere")}
</Link>
</Box>
</Grid>
</Grid>
) : null}
{session ? (
<>
<Box component="h4" sx={h4}>
{`${t("welcome")}, ${
session.user.name ?? session.user.email
}.`}
</Box>
<Link href="/">{t("goHome")}</Link>
</>
) : null}
</Grid>
</Grid>
</Container>
</>
);
};

View file

@ -1,16 +0,0 @@
import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "app/_lib/auth";
import { Login } from "./_components/Login";
export const metadata: Metadata = {
title: "Login",
};
export default async function Page() {
const session = await getServerSession(authOptions);
return <Login session={session} />;
}

View file

@ -1,5 +0,0 @@
import { About } from "@link-stack/leafcutter-ui";
export default function Page() {
return <About />;
}

View file

@ -1,10 +0,0 @@
import { getTemplates } from "app/_lib/opensearch";
import { Create } from "@link-stack/leafcutter-ui";
export default async function Page() {
const templates = await getTemplates(100);
return <Create templates={templates} />;
}
export const dynamic = "force-dynamic";

View file

@ -1,5 +0,0 @@
import { FAQ } from "@link-stack/leafcutter-ui";
export default function Page() {
return <FAQ />;
}

View file

@ -1,11 +0,0 @@
import { ReactNode } from "react";
import "app/_styles/global.css";
import { InternalLayout } from "../_components/InternalLayout";
type LayoutProps = {
children: ReactNode;
};
export default function Layout({ children }: LayoutProps) {
return <InternalLayout embedded={false}>{children}</InternalLayout>;
}

View file

@ -1,14 +0,0 @@
import { getServerSession } from "next-auth";
import { authOptions } from "app/_lib/auth";
import { getUserVisualizations } from "app/_lib/opensearch";
import { Home } from "@link-stack/leafcutter-ui";
export default async function Page() {
const session = await getServerSession(authOptions);
const {
user: { email },
}: any = session;
const visualizations = await getUserVisualizations(email ?? "none", 20);
return <Home visualizations={visualizations} />;
}

View file

@ -1,89 +0,0 @@
/* eslint-disable no-underscore-dangle */
// import { Client } from "@opensearch-project/opensearch";
import { Preview } from "@link-stack/leafcutter-ui";
// import { createVisualization } from "lib/opensearch";
export default function Page() {
return <Preview visualization={undefined} visualizationType={""} data={[]} />;
}
/*
export const getServerSideProps: GetServerSideProps = async (
context: GetServerSidePropsContext
) => {
const {
visualizationID,
searchQuery,
visualizationType = "table",
} = context.query;
const node = `https://${process.env.OPENSEARCH_USERNAME}:${process.env.OPENSEARCH_PASSWORD}@${process.env.OPENSEARCH_URL}`;
const client = new Client({
node,
ssl: {
rejectUnauthorized: false,
},
});
res.props.visualizationType = visualizationType as string;
if (visualizationType !== "rawData") {
await createVisualization({
id: visualizationID as string,
query: await JSON.parse(decodeURI(searchQuery as string)),
kind: visualizationType as string,
});
const rawResponse = await client.search({
index: ".kibana_1",
size: 200,
});
const response = rawResponse.body;
const hits = response.hits.hits.filter(
(hit) => hit._id.split(":")[1] === visualizationID[0]
);
const hit = hits[0];
res.props.visualization = {
id: hit._id.split(":")[1],
title: hit._source.visualization.title,
description: hit._source.visualization.description,
url: `/app/visualize?security_tenant=global#/edit/${
hit._id.split(":")[1]
}?embed=true`,
};
}
const rawQuery = await JSON.parse(decodeURI(searchQuery as string));
const query = {
bool: {
should: [],
must_not: [],
},
};
if (rawQuery.impactedTechnology.values.length > 0) {
rawQuery.impactedTechnology.values.forEach((value) => {
query.bool.should.push({
match: { technology: value },
});
});
}
console.log({ query });
const dataResponse = await client.search({
index: "demo_data",
size: 200,
body: { query },
});
console.log({ dataResponse });
res.props.data = dataResponse.body.hits.hits.map((hit) => ({
id: hit._id,
...hit._source,
}));
console.log({ data: res.props.data });
console.log(res.props.data[0]);
return res;
};
*/

View file

@ -1,50 +0,0 @@
"use client";
import { FC } from "react";
import { useLayoutEffect } from "react";
import { useRouter } from "next/navigation";
import { Grid, CircularProgress } from "@mui/material";
import Iframe from "react-iframe";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
export const Setup: FC = () => {
const {
colors: { leafcutterElectricBlue },
} = useLeafcutterContext();
const router = useRouter();
useLayoutEffect(() => {
setTimeout(() => router.push("/"), 4000);
}, [router]);
return (
<Grid
sx={{ width: "100%", height: 700 }}
direction="row"
container
justifyContent="space-around"
alignItems="center"
alignContent="center"
>
<Grid
item
xs={12}
sx={{
width: "200px",
height: 700,
textAlign: "center",
margin: "0 auto",
pt: 30,
}}
>
<Iframe url="/app/home" height="1" width="1" frameBorder={0} />
<CircularProgress
size={80}
thickness={5}
sx={{ color: leafcutterElectricBlue }}
/>
</Grid>
</Grid>
);
};
export default Setup;

View file

@ -1,5 +0,0 @@
import { Setup } from "./_components/Setup";
export default function Page() {
return <Setup />;
}

View file

@ -1,10 +0,0 @@
import { getTrends } from "app/_lib/opensearch";
import { Trends } from "@link-stack/leafcutter-ui";
export default async function Page() {
const visualizations = await getTrends(25);
return <Trends visualizations={visualizations} />;
}
export const dynamic = "force-dynamic";

View file

@ -1,46 +0,0 @@
/* eslint-disable no-underscore-dangle */
import { Client } from "@opensearch-project/opensearch";
import { VisualizationDetail } from "@link-stack/leafcutter-ui";
const getVisualization = async (visualizationID: string) => {
const node = `https://${process.env.OPENSEARCH_USERNAME}:${process.env.OPENSEARCH_PASSWORD}@${process.env.OPENSEARCH_URL}`;
const client = new Client({
node,
ssl: {
rejectUnauthorized: false,
},
});
const rawResponse = await client.search({
index: ".kibana_1",
size: 200,
});
const response = rawResponse.body;
const hits = response.hits.hits.filter(
(hit: any) => hit._id.split(":")[1] === visualizationID[0],
);
const hit = hits[0];
const visualization = {
id: hit._id.split(":")[1],
title: hit._source.visualization.title,
description: hit._source.visualization.description,
url: `/app/visualize?security_tenant=global#/edit/${
hit._id.split(":")[1]
}?embed=true`,
};
return visualization;
};
type PageProps = {
params: {
visualizationID: string;
};
};
export default async function Page({ params: { visualizationID } }: PageProps) {
const visualization = await getVisualization(visualizationID);
return <VisualizationDetail {...visualization} editing={false} />;
}

View file

@ -1,55 +0,0 @@
"use client";
import { FC } from "react";
import Image from "next/legacy/image";
import { signOut } from "next-auth/react";
import { Button, Box, Menu, MenuItem } from "@mui/material";
import { useTranslate } from "react-polyglot";
import UserIcon from "images/user-icon.png";
import {
usePopupState,
bindTrigger,
bindMenu,
} from "material-ui-popup-state/hooks";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
export const AccountButton: FC = () => {
const t = useTranslate();
const {
colors: { leafcutterElectricBlue },
} = useLeafcutterContext();
const popupState = usePopupState({ variant: "popover", popupId: "account" });
return (
<>
<Button
{...bindTrigger(popupState)}
color="secondary"
sx={{
backgroundColor: leafcutterElectricBlue,
width: "40px",
height: "40px",
minWidth: "40px",
p: 0,
borderRadius: "500px",
":hover": {
backgroundColor: leafcutterElectricBlue,
opacity: 0.8,
},
}}
>
<Image src={UserIcon} alt="account" width={30} height={30} />
</Button>
<Menu {...bindMenu(popupState)}>
<MenuItem
onClick={() => {
popupState.close();
signOut({ callbackUrl: "/" });
}}
>
<Box sx={{ width: "100%" }}>{t("signOut")}</Box>
</MenuItem>
</Menu>
</>
);
};

View file

@ -1,161 +0,0 @@
"use client";
import {
FC,
createContext,
useContext,
useReducer,
useState,
PropsWithChildren,
} from "react";
import { colors, typography } from "@link-stack/leafcutter-ui/styles/theme";
const basePath = process.env.GITLAB_CI
? "/link/link-stack/apps/leafcutter"
: "";
const imageURL = (image: any) =>
typeof image === "string" ? `${basePath}${image}` : `${basePath}${image.src}`;
const AppContext = createContext({
colors,
typography,
imageURL,
query: null as any,
updateQuery: null as any,
updateQueryType: null as any,
replaceQuery: null as any,
clearQuery: null as any,
foundCount: 0,
setFoundCount: null as any,
});
export const LeafcutterProvider: FC<PropsWithChildren> = ({ children }) => {
const initialState = {
incidentType: {
display: "Incident Type",
queryType: "include",
values: [],
},
relativeDate: {
display: "Relative Date",
queryType: null,
values: [],
},
startDate: {
display: "Start Date",
queryType: null,
values: [],
},
endDate: {
display: "End Date",
queryType: null,
values: [],
},
targetedGroup: {
display: "Targeted Group",
queryType: "include",
values: [],
},
platform: {
display: "Platform",
queryType: "include",
values: [],
},
device: {
display: "Device",
queryType: "include",
values: [],
},
service: {
display: "Service",
queryType: "include",
values: [],
},
maker: {
display: "Maker",
queryType: "include",
values: [],
},
country: {
display: "Country",
queryType: "include",
values: [],
},
subregion: {
display: "Subregion",
queryType: "include",
values: [],
},
continent: {
display: "Continent",
queryType: "include",
values: [],
},
};
const reducer = (state: any, action: any) => {
const key = action.payload?.[0];
if (!key) {
throw new Error("Unknown key");
}
const newState = { ...state };
switch (action.type) {
case "UPDATE":
newState[key].values = action.payload[key].values;
return newState;
case "UPDATE_TYPE":
newState[key].queryType = action.payload[key].queryType;
return newState;
case "REPLACE":
return Object.keys(action.payload).reduce((acc: any, cur: string) => {
if (["startDate", "endDate"].includes(cur)) {
const rawDate = action.payload[cur].values[0];
const date = new Date(rawDate);
acc[cur] = {
...action.payload[cur],
values: rawDate && date ? [date] : [],
};
} else {
acc[cur] = action.payload[cur];
}
return acc;
}, {});
case "CLEAR":
return initialState;
default:
throw new Error("Unknown action type");
}
};
const [query, dispatch] = useReducer(reducer, initialState);
const updateQuery = (payload: any) => dispatch({ type: "UPDATE", payload });
const updateQueryType = (payload: any) =>
dispatch({ type: "UPDATE_TYPE", payload });
const replaceQuery = (payload: any) => dispatch({ type: "REPLACE", payload });
const clearQuery = () => dispatch({ type: "CLEAR" });
const [foundCount, setFoundCount] = useState(0);
return (
<AppContext.Provider
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{
colors,
typography,
imageURL,
query,
updateQuery,
updateQueryType,
replaceQuery,
clearQuery,
foundCount,
setFoundCount,
}}
>
{children}
</AppContext.Provider>
);
};
export function useLeafcutterContext() {
return useContext(AppContext);
}

View file

@ -1,45 +0,0 @@
"use client";
import { FC, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Button } from "@mui/material";
import { QuestionMark as QuestionMarkIcon } from "@mui/icons-material";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
export const HelpButton: FC = () => {
const router = useRouter();
const pathname = usePathname() ?? "";
const [helpActive, setHelpActive] = useState(false);
const {
colors: { leafcutterElectricBlue },
} = useLeafcutterContext();
const onClick = () => {
if (helpActive) {
router.push(pathname);
} else {
router.push("/?tooltip=welcome");
}
setHelpActive(!helpActive);
};
return (
<Button
color="primary"
onClick={onClick}
sx={{
backgroundColor: leafcutterElectricBlue,
width: "40px",
height: "40px",
minWidth: "40px",
p: 0,
borderRadius: "500px",
":hover": {
backgroundColor: leafcutterElectricBlue,
opacity: 0.8,
},
}}
>
<QuestionMarkIcon width="30px" height="30px" htmlColor="white" />
</Button>
);
};

View file

@ -1,75 +0,0 @@
"use client";
import { FC, PropsWithChildren } from "react";
import getConfig from "next/config";
import { Grid, Container } from "@mui/material";
import CookieConsent from "react-cookie-consent";
import { useCookies } from "react-cookie";
import { TopNav } from "./TopNav";
import { Sidebar } from "./Sidebar";
import { GettingStartedDialog } from "@link-stack/leafcutter-ui";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
// import { Footer } from "./Footer";
type LayoutProps = PropsWithChildren<{
embedded?: boolean;
}>;
export const InternalLayout: FC<LayoutProps> = ({
embedded = false,
children,
}: any) => {
const [cookies, setCookie] = useCookies(["cookieConsent"]);
const consentGranted = cookies.cookieConsent === "true";
const {
colors: {
white,
almostBlack,
leafcutterElectricBlue,
cdrLinkOrange,
helpYellow,
},
} = useLeafcutterContext();
return (
<>
<Grid container direction="column">
{!embedded && (
<Grid item>
<TopNav />
</Grid>
)}
{!embedded && <Sidebar open />}
<Grid
item
sx={{ mt: embedded ? 0 : "100px", ml: embedded ? 0 : "310px" }}
>
<Container sx={{ padding: 2 }}>{children}</Container>
</Grid>
</Grid>
{!consentGranted ? (
<CookieConsent
style={{
zIndex: 1500,
backgroundColor: helpYellow,
color: almostBlack,
borderTop: `1px solid ${leafcutterElectricBlue}`,
}}
onAccept={() => setCookie("cookieConsent", "true", { path: "/" })}
buttonStyle={{
borderRadius: 500,
backgroundColor: cdrLinkOrange,
color: white,
textTransform: "uppercase",
padding: "10px 20px",
fontWeight: "bold",
fontSize: 14,
}}
>
Leafcutter uses cookies for core funtionality.
</CookieConsent>
) : null}
<GettingStartedDialog />
</>
);
};

View file

@ -1,68 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { IconButton, Menu, MenuItem, Box } from "@mui/material";
import { KeyboardArrowDown as KeyboardArrowDownIcon } from "@mui/icons-material";
import {
usePopupState,
bindTrigger,
bindMenu,
} from "material-ui-popup-state/hooks";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
// import { Tooltip } from "./Tooltip";
export const LanguageSelect = () => {
const {
colors: { white, leafcutterElectricBlue },
} = useLeafcutterContext();
const router = useRouter();
const locales: any = { en: "English", fr: "Français" };
const locale = "en";
const popupState = usePopupState({ variant: "popover", popupId: "language" });
return (
<Box>
<IconButton
{...bindTrigger(popupState)}
sx={{
fontSize: 14,
borderRadius: 500,
color: white,
backgroundColor: leafcutterElectricBlue,
fontWeight: "bold",
textTransform: "uppercase",
pl: 4,
pr: 3,
":hover": {
backgroundColor: leafcutterElectricBlue,
opacity: 0.8,
},
}}
>
{locales[locale as any] ?? locales.en}
<KeyboardArrowDownIcon />
</IconButton>
<Menu {...bindMenu(popupState)}>
{Object.keys(locales).map((locale) => (
<MenuItem
key={locale}
onClick={() => {
// router.push(router.route, router.route, { locale });
popupState.close();
}}
>
<Box sx={{ width: 130 }}>{locales[locale]}</Box>
</MenuItem>
))}
</Menu>
</Box>
);
};
/* <Tooltip
title={t("languageTooltipTitle")}
description={t("languageTooltipDescription")}
color="#fff"
backgroundColor="#a5a6f6"
placement="top"
> </Tooltip> */

View file

@ -1,43 +0,0 @@
"use client";
/* eslint-disable react/jsx-props-no-spreading */
import { FC, PropsWithChildren } from "react";
import { SessionProvider } from "next-auth/react";
import { CssBaseline } from "@mui/material";
import { CookiesProvider } from "react-cookie";
import { I18n } from "react-polyglot";
import { AdapterDateFns } from "@mui/x-date-pickers-pro/AdapterDateFnsV3";
import { LocalizationProvider } from "@mui/x-date-pickers-pro";
import { LeafcutterProvider } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
import { AppRouterCacheProvider } from "@mui/material-nextjs/v14-appRouter";
import en from "@link-stack/leafcutter-ui/locales/en.json";
import fr from "@link-stack/leafcutter-ui/locales/fr.json";
import { LicenseInfo } from "@mui/x-license";
LicenseInfo.setLicenseKey(
"c787ac6613c5f2aa0494c4285fe3e9f2Tz04OTY1NyxFPTE3NDYzNDE0ODkwMDAsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI=",
);
const messages: any = { en, fr };
export const MultiProvider: FC<PropsWithChildren> = ({ children }: any) => {
// const { locale = "en" } = useRouter();
const locale = "en";
return (
<AppRouterCacheProvider>
<SessionProvider>
<CookiesProvider>
<CssBaseline />
<LeafcutterProvider>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<I18n locale={locale} messages={messages[locale]}>
{children}
</I18n>
</LocalizationProvider>
</LeafcutterProvider>
</CookiesProvider>
</SessionProvider>
</AppRouterCacheProvider>
);
};

View file

@ -1,255 +0,0 @@
"use client";
import { FC } from "react";
import DashboardMenuIcon from "images/dashboard-menu.png";
import AboutMenuIcon from "images/about-menu.png";
import TrendsMenuIcon from "images/trends-menu.png";
import SearchCreateMenuIcon from "images/search-create-menu.png";
import FAQMenuIcon from "images/faq-menu.png";
import Image from "next/legacy/image";
import {
Box,
Grid,
Typography,
List,
ListItem,
ListItemIcon,
ListItemText,
Drawer,
} from "@mui/material";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslate } from "react-polyglot";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
import { Tooltip } from "@link-stack/leafcutter-ui";
// import { ArrowCircleRight as ArrowCircleRightIcon } from "@mui/icons-material";
const MenuItem = ({
name,
href,
selected,
icon,
iconSize,
}: // tooltipTitle,
// tooltipDescription,
{
name: string;
href: string;
selected: boolean;
icon: any;
iconSize: number;
// tooltipTitle: string;
// tooltipDescription: string;
}) => {
const {
colors: { leafcutterLightBlue, black },
} = useLeafcutterContext();
return (
<Link href={href} passHref>
<ListItem
button
sx={{
paddingLeft: "62px",
backgroundColor: selected ? leafcutterLightBlue : "transparent",
mt: "6px",
"& :hover": { backgroundColor: leafcutterLightBlue },
}}
>
<ListItemIcon
sx={{
color: `${black} !important`,
}}
>
<Box
sx={{
width: iconSize,
height: iconSize,
ml: `${(20 - iconSize) / 2}px`,
mr: `${(20 - iconSize) / 2}px`,
}}
>
<Image src={icon} alt="" />
</Box>
<ListItemText
primary={
<Typography
variant="body1"
style={{
color: "#000 !important",
fontSize: 14,
fontFamily: "Roboto",
fontWeight: 400,
marginLeft: 10,
marginTop: -3,
}}
>
{name}
</Typography>
}
/>
</ListItemIcon>
</ListItem>
</Link>
);
};
interface SidebarProps {
open: boolean;
}
export const Sidebar: FC<SidebarProps> = ({ open }) => {
const t = useTranslate();
const pathname = usePathname() ?? "";
const section = pathname?.split("/")[1];
const {
colors: { white }, // leafcutterElectricBlue, leafcutterLightBlue,
} = useLeafcutterContext();
// const [recentUpdates, setRecentUpdates] = useState([]);
/*
useEffect(() => {
const getRecentUpdates = async () => {
const result = await fetch(`/api/trends/recent`);
const json = await result.json();
setRecentUpdates(json);
};
getRecentUpdates();
}, []);
*/
return (
<Drawer
sx={{ width: 300, flexShrink: 0 }}
color="secondary"
variant="permanent"
anchor="left"
open={open}
PaperProps={{
sx: {
width: 300,
border: 0,
mt: "90px",
mb: "200px",
},
}}
>
<Grid
container
direction="column"
justifyContent="space-between"
wrap="nowrap"
sx={{ backgroundColor: white, height: "100%" }}
>
<Grid item container direction="column" sx={{ mt: "6px" }} flexGrow={1}>
<Tooltip
title={t("dashboardNavigationCardTitle")}
description={t("dashboardNavigationCardDescription")}
tooltipID="navigation"
placement="right"
nextURL="/?tooltip=recentUpdates"
previousURL="/?tooltip=welcome"
>
<List component="nav">
<MenuItem
name={t("dashboardMenuItem")}
href="/"
icon={DashboardMenuIcon}
iconSize={20}
selected={section === ""}
/>
<MenuItem
name={t("searchAndCreateMenuItem")}
href="/create"
icon={SearchCreateMenuIcon}
iconSize={20}
selected={section === "create"}
/>
<MenuItem
name={t("trendsMenuItem")}
href="/trends"
icon={TrendsMenuIcon}
iconSize={13}
selected={section === "trends"}
/>
<MenuItem
name={t("faqMenuItem")}
href="/faq"
icon={FAQMenuIcon}
iconSize={20}
selected={section === "faq"}
/>
<MenuItem
name={t("aboutMenuItem")}
href="/about"
icon={AboutMenuIcon}
iconSize={20}
selected={section === "about"}
/>
</List>
</Tooltip>
</Grid>
{/*
<Tooltip
title={t("recentUpdatesCardTitle")}
description={t("recentUpdatesCardDescription")}
tooltipID="recentUpdates"
nextURL="/?tooltip=profile"
previousURL="/?tooltip=navigation"
placement="right"
>
<Grid
item
sx={{
overflow: "hidden",
backgroundColor: leafcutterLightBlue,
height: 350,
}}
>
<Typography
variant="body1"
sx={{
fontWeight: 700,
fontSize: 14,
backgroundColor: leafcutterElectricBlue,
color: white,
p: 2,
}}
>
{t("recentUpdatesTitle")}
</Typography>
{recentUpdates.map((trend, index) => (
<Link href={`/visualizations/${trend.id}`} passHref key={index}>
<Box
key={index}
sx={{
p: 2,
cursor: "pointer",
}}
>
<Typography
variant="body2"
sx={{ color: leafcutterElectricBlue, fontWeight: 700 }}
>
{trend.title}
</Typography>
<Typography
variant="body2"
sx={{ color: leafcutterElectricBlue }}
>
{trend.description}{" "}
<ArrowCircleRightIcon
sx={{ height: 16, width: 16, mb: "-4px" }}
/>
</Typography>
</Box>
</Link>
))}
</Grid>
</Tooltip> */}
</Grid>
</Drawer>
);
};

View file

@ -1,121 +0,0 @@
"use client";
import { FC } from "react";
import Link from "next/link";
import Image from "next/legacy/image";
import { AppBar, Grid, Box } from "@mui/material";
import { useTranslate } from "react-polyglot";
import LeafcutterLogo from "images/leafcutter-logo.png";
import { AccountButton } from "./AccountButton";
import { HelpButton } from "./HelpButton";
import { Tooltip } from "@link-stack/leafcutter-ui";
import { useLeafcutterContext } from "@link-stack/leafcutter-ui/components/LeafcutterProvider";
// import { LanguageSelect } from "./LanguageSelect";
export const TopNav: FC = () => {
const t = useTranslate();
const {
colors: { white, leafcutterElectricBlue, cdrLinkOrange },
typography: { h5, h6 },
} = useLeafcutterContext();
return (
<AppBar
position="fixed"
elevation={1}
sx={{
backgroundColor: white,
marginBottom: 180,
opacity: 0.95,
pt: 2,
pb: 2,
pr: 3,
pl: 6,
backdropFilter: "blur(10px)",
}}
>
<Grid
container
justifyContent="space-between"
alignItems="center"
alignContent="center"
direction="row"
wrap="nowrap"
spacing={4}
>
<Grid
item
container
direction="row"
justifyContent="flex-start"
alignItems="center"
alignContent="center"
spacing={1}
wrap="nowrap"
sx={{ cursor: "pointer" }}
>
<Grid item sx={{ pr: 1 }}>
<Image src={LeafcutterLogo} alt="" width={56} height={52} />
</Grid>
<Grid item container direction="column" alignContent="flex-start">
<Grid item sx={{ mt: -1 }}>
<Box
sx={{
...h5,
color: leafcutterElectricBlue,
p: 0,
m: 0,
pt: 1,
textAlign: "left",
}}
>
Leafcutter
</Box>
</Grid>
<Grid item>
<Box
sx={{
...h6,
m: 0,
p: 0,
color: cdrLinkOrange,
textAlign: "left",
}}
>
A Project of Center for Digital Resilience
</Box>
</Grid>
</Grid>
</Grid>
<Grid item>
<HelpButton />
</Grid>
{/* <Tooltip
title={t("languageOptionsCardTitle")}
description={t("languageOptionsCardDescription")}
emoji="✍️"
tooltipID="language"
placement="bottom"
>
<Grid item>
<LanguageSelect />
</Grid>
</Tooltip> */}
<Tooltip
title={t("profileSettingsCardTitle")}
description={t("profileSettingsCardDescription")}
tooltipID="profile"
placement="bottom"
previousURL="/?tooltip=recentUpdates"
nextURL="/create?tooltip=searchCreate"
>
<Grid item>
<AccountButton />
</Grid>
</Tooltip>
</Grid>
</AppBar>
);
};

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,31 +0,0 @@
{
"visualizations": {
"horizontalBar": {
"name": "Horizontal Bar"
},
"verticalBar": {
"name": "Vertical Bar"
},
"line": {
"name": "Line"
},
"pieDonut": {
"name": "Pie"
},
"dataTable": {
"name": "Data Table"
},
"metric": {
"name": "Metric"
},
"tagCloud": {
"name": "Tag Cloud"
}
},
"fields": {
"incidentType": ["horizontalBar"],
"targetedGroup": ["horizontalBar"],
"impactedTechnology": ["horizontalBar"],
"region": ["horizontalBar"]
}
}

View file

@ -1,38 +0,0 @@
{
"title": "DataTable",
"type": "table",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "incident.keyword",
"orderBy": "1",
"order": "desc",
"size": 10,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "bucket"
}
],
"params": {
"perPage": 10,
"showPartialRows": false,
"showMetricsAtAllLevels": false,
"sort": { "columnIndex": null, "direction": null },
"showTotal": false,
"totalFunc": "sum",
"percentageCol": ""
}
}

View file

@ -1,93 +0,0 @@
{
"title": "",
"type": "horizontal_bar",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "incident.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": true,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "histogram",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 200
},
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 75,
"filter": true,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "histogram",
"mode": "normal",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-1",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": {},
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
}
}
}

View file

@ -1,94 +0,0 @@
{
"title": "BarStacked",
"type": "horizontal_bar",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "actor.keyword",
"orderBy": "_key",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "split"
}
],
"params": {
"type": "histogram",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 200
},
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 75,
"filter": true,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "histogram",
"mode": "stacked",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-1",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": {},
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
},
"row": true
}
}

View file

@ -1,89 +0,0 @@
{
"title": "Line",
"type": "line",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "technology.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "line",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": { "show": true, "filter": true, "truncate": 100 },
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "line",
"mode": "normal",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-1",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"interpolate": "linear",
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": {},
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
}
}
}

View file

@ -1,105 +0,0 @@
{
"title": "LineStacked",
"type": "line",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "technology.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "line",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": { "show": true, "filter": true, "truncate": 100 },
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 100
},
"title": { "text": "Count" }
},
{
"id": "ValueAxis-2",
"name": "RightAxis-1",
"type": "value",
"position": "right",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "line",
"mode": "stacked",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-2",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"interpolate": "step-after",
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": {},
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
}
}
}

View file

@ -1,50 +0,0 @@
{
"title": "Metric",
"type": "metric",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": { "customLabel": "#" },
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "technology.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "group"
}
],
"params": {
"addTooltip": true,
"addLegend": false,
"type": "metric",
"metric": {
"percentageMode": false,
"useRanges": false,
"colorSchema": "Green to Red",
"metricColorMode": "None",
"colorsRange": [{ "from": 0, "to": 10000 }],
"labels": { "show": true },
"invertColors": false,
"style": {
"bgFill": "#000",
"bgColor": false,
"labelColor": false,
"subText": "",
"fontSize": 60
}
}
}
}

View file

@ -1,42 +0,0 @@
{
"title": "Pie",
"type": "pie",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "technology.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": true,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "pie",
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"isDonut": true,
"labels": {
"show": false,
"values": true,
"last_level": true,
"truncate": 100
}
}
}

View file

@ -1,36 +0,0 @@
{
"title": "Cloud",
"type": "tagcloud",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "incident.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"scale": "linear",
"orientation": "single",
"minFontSize": 18,
"maxFontSize": 72,
"showLabel": true
}
}

View file

@ -1,88 +0,0 @@
{
"title": "VerticalBar",
"type": "histogram",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "actor.keyword",
"orderBy": "1",
"order": "desc",
"size": 10,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "histogram",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": { "show": true, "filter": true, "truncate": 100 },
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "histogram",
"mode": "normal",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-1",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": { "show": false },
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
}
}
}

View file

@ -1,88 +0,0 @@
{
"title": "VerticalBarStacked",
"type": "histogram",
"aggs": [
{
"id": "1",
"enabled": true,
"type": "count",
"params": {},
"schema": "metric"
},
{
"id": "2",
"enabled": true,
"type": "terms",
"params": {
"field": "incident.keyword",
"orderBy": "1",
"order": "desc",
"size": 5,
"otherBucket": false,
"otherBucketLabel": "Other",
"missingBucket": false,
"missingBucketLabel": "Missing"
},
"schema": "segment"
}
],
"params": {
"type": "histogram",
"grid": { "categoryLines": false },
"categoryAxes": [
{
"id": "CategoryAxis-1",
"type": "category",
"position": "bottom",
"show": true,
"style": {},
"scale": { "type": "linear" },
"labels": { "show": true, "filter": true, "truncate": 100 },
"title": {}
}
],
"valueAxes": [
{
"id": "ValueAxis-1",
"name": "LeftAxis-1",
"type": "value",
"position": "left",
"show": true,
"style": {},
"scale": { "type": "linear", "mode": "normal" },
"labels": {
"show": true,
"rotate": 0,
"filter": false,
"truncate": 100
},
"title": { "text": "Count" }
}
],
"seriesParams": [
{
"show": true,
"type": "histogram",
"mode": "stacked",
"data": { "label": "Count", "id": "1" },
"valueAxis": "ValueAxis-1",
"drawLinesBetweenPoints": true,
"lineWidth": 2,
"showCircles": true
}
],
"addTooltip": true,
"addLegend": true,
"legendPosition": "right",
"times": [],
"addTimeMarker": false,
"labels": { "show": false },
"thresholdLine": {
"show": false,
"value": 10,
"width": 1,
"style": "full",
"color": "#E7664C"
}
}
}

View file

@ -1,80 +0,0 @@
import type { NextAuthOptions } from "next-auth";
import Google from "next-auth/providers/google";
import Apple from "next-auth/providers/apple";
import Credentials from "next-auth/providers/credentials";
import { checkAuth } from "./opensearch";
export const authOptions: NextAuthOptions = {
pages: {
signIn: "/login",
error: "/login",
signOut: "/logout",
},
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID ?? "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "",
}),
Apple({
clientId: process.env.APPLE_CLIENT_ID ?? "",
clientSecret: process.env.APPLE_CLIENT_SECRET ?? "",
}),
Credentials({
name: "Link",
credentials: {
authToken: { label: "AuthToken", type: "text", },
},
async authorize(credentials, req) {
const { headers } = req;
console.log({ headers });
const leafcutterUser = headers?.["x-leafcutter-user"];
const authToken = credentials?.authToken;
if (!leafcutterUser || leafcutterUser.trim() === "") {
console.log("no leafcutter user");
return null;
}
console.log({ authToken });
return null;
/*
try {
// add role check
await checkAuth(username, password);
const user = {
id: leafcutterUser,
email: leafcutterUser
};
return user;
} catch (e) {
console.log({ e });
}
return null;
*/
}
})
],
secret: process.env.NEXTAUTH_SECRET,
/*
callbacks: {
signIn: async ({ user, account, profile }) => {
const roles: any = [];
return roles.includes("admin") || roles.includes("agent");
},
session: async ({ session, user, token }) => {
// @ts-ignore
session.user.roles = token.roles;
return session;
},
jwt: async ({ token, user, account, profile, trigger }) => {
if (user) {
token.roles = [];
}
return token;
}
},*/
};

View file

@ -1,593 +0,0 @@
/* eslint-disable no-underscore-dangle */
import { Client } from "@opensearch-project/opensearch";
import { v4 as uuid } from "uuid";
/* Common */
const globalIndex = ".kibana_1";
const dataIndexName = "sample_tagged_tickets";
const userMetadataIndexName = "user_metadata";
const baseURL = `https://${process.env.OPENSEARCH_USERNAME}:${process.env.OPENSEARCH_PASSWORD}@${process.env.OPENSEARCH_URL}`;
const createClient = () => new Client({
node: baseURL,
auth: {
username: process.env.OPENSEARCH_USERNAME!,
password: process.env.OPENSEARCH_PASSWORD!,
},
ssl: {
rejectUnauthorized: false,
},
});
const createUserClient = (username: string, password: string) => new Client({
node: baseURL,
auth: {
username,
password,
},
ssl: {
rejectUnauthorized: false,
},
});
export const checkAuth = async (username: string, password: string) => {
const client = createUserClient(username, password);
const res = await client.ping();
return res.statusCode === 200;
};
const getDocumentID = (doc: any) => doc._id.split(":")[1];
const getEmbedURL = (tenant: string, visualizationID: string) =>
`/app/visualize?security_tenant=${tenant}#/edit/${visualizationID}?embed=true`;
export const getVisualization = async (id: string) => {
const client = createClient();
const res = await client.get({
id: `visualization:${id}`,
index: globalIndex,
});
return res.body._source;
};
const generateKuery = (searchQuery: any) => {
const searchTemplate = {
query: {
query: "",
language: "kuery",
},
filter: [],
indexRefName: "kibanaSavedObjectMeta.searchSourceJSON.index",
};
const incidentTypeClause = searchQuery.incidentType.values
.map((value: string) => `incident:${value} `)
.join(" or ");
const allTechnologies = [
...searchQuery.platform.values,
...searchQuery.device.values,
...searchQuery.service.values,
...searchQuery.maker.values,
];
const technologyClause = allTechnologies
.map((value: string) => `technology:${value} `)
.join(" or ");
const targetedGroupClause = searchQuery.targetedGroup.values
.map((value: string) => `targeted_group:${value} `)
.join(" or ");
const countryClause = searchQuery.country.values
.map((value: string) => `country:${value} `)
.join(" or ");
const subregionClause = searchQuery.subregion.values
.map((value: string) => `region:${value} `)
.join(" or ");
const continentClause = searchQuery.continent.values
.map((value: string) => `continent:${value} `)
.join(" or ");
const kueryString = [
incidentTypeClause,
technologyClause,
targetedGroupClause,
countryClause,
subregionClause,
continentClause,
]
.filter((clause) => clause !== "")
.join(" and ");
searchTemplate.query.query = kueryString;
return JSON.stringify(searchTemplate);
};
export const getUserMetadata = async (username: string) => {
const client = createClient();
let res: any;
try {
res = await client.get({
id: username,
index: userMetadataIndexName,
});
} catch (e) {
await client.create({
id: username,
index: userMetadataIndexName,
body: { username, savedSearches: [] }
});
res = await client.get({
id: username,
index: userMetadataIndexName,
});
}
return res?.body._source;
};
export const saveUserMetadata = async (username: string, metadata: any) => {
const client = createClient();
await client.update({
id: username,
index: userMetadataIndexName,
body: { doc: { username, ...metadata } }
});
};
/* User */
const getCurrentUserIndex = async (email: string) => {
const userIndexName = email.replace(/[\W\d_]/g, "").toLowerCase();
const client = createClient();
const aliasesResponse = await client.indices.getAlias({
name: `.kibana_*_${userIndexName}`,
});
// prefer alias if it exists
if (Object.keys(aliasesResponse.body).length > 0) {
return Object.keys(aliasesResponse.body)[0];
}
const indicesResponse = await client.indices.get({
index: `.kibana_*_${userIndexName}_1`,
});
const currentUserIndex = Object.keys(indicesResponse.body)[0];
return currentUserIndex;
};
const getIndexPattern: any = async (index: string) => {
const client = createClient();
const query = {
query: {
bool: {
must: [
{ match: { type: "index-pattern" } },
{
match: {
"index-pattern.title": dataIndexName,
},
},
],
},
},
};
const res = await client.search({
index,
size: 1,
body: query,
sort: ["updated_at:desc"],
});
if (res.body.hits.total.value === 0) {
// eslint-disable-next-line no-use-before-define
return createCurrentUserIndexPattern(index);
}
const {
hits: {
hits: [indexPattern],
},
} = res.body;
return indexPattern;
};
const createCurrentUserIndexPattern = async (index: string) => {
const { _source: globalIndexPattern } = await getIndexPattern(globalIndex);
globalIndexPattern.updated_at = new Date().toISOString();
const id = uuid();
const fullID = `index-pattern:${id}`;
const client = createClient();
const res = await client.create({
id: fullID,
index,
refresh: true,
body: globalIndexPattern,
});
return res.body;
};
const getIndexPatternID = async (index: string) => {
const indexPattern = await getIndexPattern(index);
return getDocumentID(indexPattern);
};
interface createUserVisualizationProps {
email: string;
query: any;
visualizationID: string;
title: string;
description: string;
}
export const createUserVisualization = async (
props: createUserVisualizationProps
) => {
const { email, query, visualizationID, title, description } = props;
const userIndex = await getCurrentUserIndex(email);
const indexPatternID = await getIndexPatternID(userIndex);
const id = uuid();
const fullID = `visualization:${id}`;
const template: any = await getVisualization(visualizationID);
template.visualization.title = title;
template.visualization.description = description;
template.visualization.kibanaSavedObjectMeta.searchSourceJSON =
generateKuery(query);
template.references = [
{
name: "kibanaSavedObjectMeta.searchSourceJSON.index",
type: "index-pattern",
id: indexPatternID,
},
];
template.updated_at = new Date().toISOString();
const client = createClient();
const res = await client.create({
id: fullID,
index: userIndex,
refresh: true,
body: template,
});
return getDocumentID(res.body);
};
export const getUserVisualization = async (email: string, id: string) => {
const userIndex = await getCurrentUserIndex(email);
const client = createClient();
const res = await client.get({
id: `visualization:${id}`,
index: userIndex,
});
return res.body;
};
interface updateVisualizationProps {
email: string;
id: string;
query: any;
title: string;
description: string;
}
export const updateUserVisualization = async (
props: updateVisualizationProps
) => {
const { email, id, query, title, description } = props;
const userIndex = await getCurrentUserIndex(email);
const result: any = await getUserVisualization(email, id);
const body = {
doc: result._source,
};
body.doc.visualization.title = title;
body.doc.visualization.description = description;
body.doc.visualization.kibanaSavedObjectMeta.searchSourceJSON =
generateKuery(query);
const client = createClient();
try {
await client.update({
id: `visualization:${id}`,
index: userIndex,
body,
});
} catch (e) {
// eslint-disable-next-line no-console
console.log({ e });
}
return id;
};
export const deleteUserVisualization = async (email: string, id: string) => {
const userIndex = await getCurrentUserIndex(email);
const client = createClient();
client.delete({
id: `visualization:${id}`,
index: userIndex,
});
};
export const getUserVisualizations = async (email: string, limit: number) => {
const userIndex = await getCurrentUserIndex(email);
const client = createClient();
const query = {
query: {
match: { type: "visualization" },
},
};
const res = await client.search({
index: userIndex,
size: limit,
body: query,
sort: ["updated_at:desc"],
});
const {
hits: { hits },
} = res.body;
const results = hits.map((hit: any) => ({
id: getDocumentID(hit),
title: hit._source.visualization.title,
description: hit._source.visualization.description ?? "",
url: getEmbedURL("private", getDocumentID(hit)),
}));
return results;
};
/* Global */
export const performQuery = async (searchQuery: any, limit: number) => {
const client = createClient();
const body = {
query: {
bool: {
must: [],
},
},
};
if (searchQuery.relativeDate.values.length > 0) {
searchQuery.relativeDate.values.forEach((value: string) => {
// @ts-expect-error
body.query.bool.must.push({
range: {
date: {
gte: `now-${value}d`,
},
},
});
});
}
if (searchQuery.startDate.values.length > 0) {
searchQuery.startDate.values.forEach((value: string) => {
// @ts-expect-error
body.query.bool.must.push({
range: {
date: {
gte: value,
},
},
});
});
}
if (searchQuery.endDate.values.length > 0) {
searchQuery.endDate.values.forEach((value: string) => {
// @ts-expect-error
body.query.bool.must.push({
range: {
date: {
lte: value,
},
},
});
});
}
if (searchQuery.incidentType.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "incident.keyword": searchQuery.incidentType.values },
});
}
if (searchQuery.targetedGroup.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "targeted_group.keyword": searchQuery.targetedGroup.values },
});
}
if (searchQuery.platform.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "technology.keyword": searchQuery.platform.values },
});
}
if (searchQuery.device.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "technology.keyword": searchQuery.device.values },
});
}
if (searchQuery.service.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "technology.keyword": searchQuery.service.values },
});
}
if (searchQuery.maker.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "technology.keyword": searchQuery.maker.values },
});
}
if (searchQuery.subregion.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "region.keyword": searchQuery.subregion.values },
});
}
if (searchQuery.country.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "country.keyword": searchQuery.country.values },
});
}
if (searchQuery.continent.values.length > 0) {
// @ts-expect-error
body.query.bool.must.push({
terms: { "continent.keyword": searchQuery.continent.values },
});
}
const dataResponse = await client.search({
index: dataIndexName,
size: limit,
body,
sort: ["date:desc"],
});
const {
hits: { hits },
} = dataResponse.body;
const results = hits.map((hit: any) => ({
...hit._source,
id: hit._id,
incident: Array.isArray(hit._source.incident) ? hit._source.incident.join(", ") : hit._source.incident,
technology: Array.isArray(hit._source.technology) ? hit._source.technology.join(", ") : hit._source.technology,
targeted_group: Array.isArray(hit._source.targeted_group) ? hit._source.targeted_group.join(", ") : hit._source.targeted_group,
country: Array.isArray(hit._source.country) ? hit._source.country.join(", ") : hit._source.country,
}));
return results;
};
const cleanTitle = (title: string) =>
title?.replace(/^\[[a-zA-Z]+\] /g, "") ?? "";
const getVisualizationType = (hit: any) => {
const { title, visState } = hit._source.visualization;
const rawType = JSON.parse(visState).type;
let type = "unknown";
if (
rawType === "horizontal_bar" &&
title.includes("Horizontal Bar Stacked")
) {
type = "horizontalBarStacked";
} else if (rawType === "horizontal_bar" && title.includes("Horizontal Bar")) {
type = "horizontalBar";
} else if (
rawType === "histogram" &&
title.includes("Vertical Bar Stacked")
) {
type = "verticalBarStacked";
} else if (rawType === "histogram" && title.includes("Vertical Bar")) {
type = "verticalBar";
} else if (rawType === "histogram" && title.includes("Line Stacked")) {
type = "lineStacked";
} else if (rawType === "histogram" && title.includes("Line")) {
type = "line";
} else if (rawType === "pie") {
type = "pieDonut";
} else if (rawType === "table") {
type = "dataTable";
} else if (rawType === "metric") {
type = "metric";
} else if (rawType === "tagcloud") {
type = "tagCloud";
}
return type;
};
export const getTrends = async (limit: number) => {
const client = createClient();
const query = {
query: {
bool: {
must: [
{ match: { type: "visualization" } },
{
match_bool_prefix: {
"visualization.title": "[Trend]",
},
},
],
},
},
};
const rawResponse = await client.search({
index: globalIndex,
size: limit,
body: query,
sort: ["updated_at:desc"],
});
const response = rawResponse.body;
const {
hits: { hits },
} = response;
const results = hits.map((hit: any) => ({
id: getDocumentID(hit),
title: cleanTitle(hit._source.visualization.title),
description: hit._source.visualization.description,
url: getEmbedURL("global", getDocumentID(hit)),
}));
return results;
};
export const getTemplates = async (limit: number) => {
const client = createClient();
const query = {
query: {
bool: {
must: [
{ match: { type: "visualization" } },
{
match_bool_prefix: {
"visualization.title": "Templated",
},
},
],
},
},
};
const rawResponse = await client.search({
index: globalIndex,
size: limit,
body: query,
});
const response = rawResponse.body;
const {
hits: { hits },
} = response;
const results = hits.map((hit: any) => ({
id: getDocumentID(hit),
title: cleanTitle(hit._source.visualization.title),
type: getVisualizationType(hit),
}));
results.sort((a: any, b: any) => a.title.localeCompare(b.title));
return results;
};

View file

@ -1,186 +0,0 @@
{
"leafcutterDashboard": "Leafcutter Dashboard",
"welcomeToLeafcutter": "Welcome to Leafcutter",
"welcomeToLeafcutterDescription": "A Digital Security Threat Analysis Platform from CDR",
"signInWith": "Sign In With",
"emailMagicLink": "Email a Magic Link",
"dontHaveAccount": "Don't have an account?",
"requestAccessHere": "Request access here",
"goHome": "Go Home",
"trendsTitle": "Trends",
"trendsSubtitle": "Discover whats happening globally",
"trendsDescription": "Here you will view what digital security threats and trends are facing civil society right now. On a regular basis a CDR team member reviews the aggregated Leafcutter data and creates visualizations. You can also find third party datasets like OONI, and MISP. See all or filter your view using the drop down menu.",
"frequentlyAskedQuestionsTitle": "Frequently Asked Questions",
"frequentlyAskedQuestionsSubtitle": "Get answers to your questions",
"frequentlyAskedQuestionsDescription": "Find out what you want to know about the Leafcutter Project.",
"dashboardTitle": "My Dashboard",
"dashboardSubtitle": "Welcome",
"dashboardDescription": "This is your personal dashboard where all your saved items are stored. All your created visualizations or items you save from the Trends page are stored here.",
"searchAndCreateTitle": "Search and Create",
"searchAndCreateSubtitle": "Search datasets and create your own visualizations",
"searchAndCreateDescription": "Find out how you can use data to create visuals that can be shared externally.",
"aboutLeafcutterTitle": "About Leafcutter",
"aboutLeafcutterDescription": "A digital threat security analysis dashboard from CDR",
"whatIsLeafcutterTitle": "What Is Leafcutter?",
"whatIsLeafcutterDescription": "Leafcutter is a secure platform for aggregating, displaying, and sharing data on digital security threats and attacks facing global civil society.",
"whatIsItForTitle": "What Is It For?",
"whatIsItForDescription": "Leafcutter helps civil society incident responders view and analyze regional and global threat data to get ahead of digital attacks.",
"whoCanUseItTitle": "Who Can Use It?",
"whoCanUseItDescription": "Leafcutter is available to civil society incident responders and analysts around the world.",
"createVisualization": "Create Visualization",
"whereDataComesFromTitle": "Where the Data Comes From",
"whereDataComesFromDescription": "All data originates from CDR partner communities using the CDR Link helpdesk or from third-party partners gathering data on network filtering, including OONI. All personally identifiable information (PII) is removed before being added to the Leafcutter database, where it is aggregated with data from other CDR Link instances to provide a comprehensive view of digital threats facing civil society in regions around the world.",
"projectSupportTitle": "Project Support",
"projectSupportDescription": "Leafcutter is a project of Center for Digital Resilience. It is a free and open source tool, built on Open Search and Label Studio. Leafcutter was designed and built by Center for Digital Resilience in collaboration with Julie Kioli (design) and Guardian Project (platform development). Thank you to all who make this project possible.",
"interestedInLeafcutterTitle": "Interested in using Leafcutter for your community?",
"interestedInLeafcutterDescription": "Leafcutter is part of the CDR Link ecosystem. helping partner communities around the world safely collect data about digital security threats and attacks. Please contact us if you are interested in using Leafcutter.",
"dashboardMenuItem": "Dashboard",
"dashboardTooltipTitle": "Dashboard",
"dashboardTooltipDescription": "Dashboard",
"aboutMenuItem": "About",
"aboutTooltipTitle": "About",
"aboutTooltipDescription": "About",
"trendsMenuItem": "Trends",
"trendsTooltipTitle": "Trends",
"trendsTooltipDescription": "Trends",
"searchAndCreateMenuItem": "Search and Create",
"searchAndCreateTooltipTitle": "Search and Create",
"searchAndCreateTooltipDescription": "Search and Create",
"faqMenuItem": "FAQ",
"faqTooltipTitle": "FAQ",
"faqTooltipDescription": "FAQ",
"recentUpdatesTitle": "Recent Updates",
"language": "Language",
"languageTooltipTitle": "Language select",
"languageTooltipDescription": "Select language",
"copyright": "Copyright",
"projectOf": "A project of",
"privacyPolicy": "Privacy Policy",
"codeOfPractice": "Code of Practice",
"contactUs": "Contact Us",
"whatIsLeafcutterQuestion": "What is Leafcutter?",
"whatIsLeafcutterAnswer": "Leafcutter is a secure platform for aggregating, displaying, and sharing data on digital security threats and attacks facing global civil society.",
"whoBuiltLeafcutterQuestion": "Who built Leafcutter?",
"whoBuiltLeafcutterAnswer": "Leafcutter was built and is maintained by Center for Digital Resilience [https://digiresilience.org](https://digiresilience.org/).",
"whoCanUseLeafcutterQuestion": "Who can use Leafcutter?",
"whoCanUseLeafcutterAnswer": "Incident responders, threat analysts, security trainers, and security service providers, in general, can make use of Leafcutter to contextualize threats, draw insights and provide qualitative, data-driven support to the communities they serve.",
"whatCanYouDoWithLeafcutterQuestion": "What can you do with Leafcutter?",
"whatCanYouDoWithLeafcutterAnswer": "1. Analyze current and previously curated threats and attacks facing the civil society community\n2. Keep track of threats and attacks in other geographies\n3. Make accurate threat predictions with live data and visualizations\n4. Leverage threat data to provide tailored and preventative supports to your communities\n5. Create personalized visualizations to interpret the data in the way that works for you\n6. Share your visualizations with your community or colleagues",
"whereIsTheDataComingFromQuestion": "Where is the data coming from?",
"whereIsTheDataComingFromAnswer": "Data aggregated into Leafcutter is currently pooled from two sources:\n1. Individual CDR Link instances (CDR's rapid response helpdesk built on Zammad)\n2. Open Observatory of Network Interference (OONI).\nData from OONI is pulled from their public API, and is displayed to give users a sense of global trends in network filtering and interference.\n\nLeafcutter data is also shared with CDRs MISP instance, to enable sharing of data to other community MISP instances.",
"whereIsTheDataStoredQuestion": "Where is the data stored?",
"whereIsTheDataStoredAnswer": "Leafcutter data is securely stored in an Amazon Web Services (AWS) database.",
"howDoWeKeepTheDataSafeQuestion": "How do we keep the data safe?",
"howDoWeKeepTheDataSafeAnswer": "We keep data protected in a number of ways\n1. Tickets and data from CDR Link helpdesks are de-identified and scrubbed of personal/sensitive information before they are aggregated into the Leafcutter database to enable querying via Amazons [OpenSearch](https://aws.amazon.com/opensearch-service/the-elk-stack/what-is-opensearch/) service.\n2. Our domain is deployed on a Virtual Private Cloud, eliminating public access to the cluster and data\n3. We employ Amazon's [server side encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) with [Key Management Service](https://aws.amazon.com/kms/) to encrypt data. Only CDR holds the decryption keys.\n4. Within OpenSearch, we employ security best practices to protect data, including: - Using the latest version of OpenSearch - Employing a least-privilege, restrictive access-control.\n5. For more on CDRs approach to privacy and security, see our [Privacy Policy](https://digiresilience.org/about/privacy/).",
"howLongDoYouKeepTheDataQuestion": "How long do you keep the data?",
"howLongDoYouKeepTheDataAnswer": "Ticket data from CDR Link helpdesks are kept only for as long as necessary (detailed [here in our privacy policy](https://digiresilience.org/about/privacy/)). Other non-identifiable data are preserved indefinitely to support historical search and analysis for our community.",
"whatOrganizationsAreParticipatingQuestion": "What organizations are participating?",
"whatOrganizationsAreParticipatingAnswer": "Leafcutter was built with the civil society security community in mind and features strong participation from organizations and professionals within the [CiviCERT](https://www.civicert.org/) network and the [Threat Intel Coalition](https://www.first.org/global/sigs/tic/), among other rapid response and service provider communities.",
"howDidYouGetMyProfileInformationQuestion": "How did you get my profile information?",
"howDidYouGetMyProfileInformationAnswer": "We use Google sign-in to authenticate.",
"howCanILearnMoreAboutLeafcutterQuestion": "How can I learn more about Leafcutter?",
"howCanILearnMoreAboutLeafcutterAnswer": "Contact us at [info@cdr.link](mailto:info@cdr.link) (public PGP key [here](https://digiresilience.org/keys/info.cdr.link-public.txt)).",
"of": "of",
"previous": "Previous",
"next": "Next",
"done": "Done",
"dashboardNavigationCardTitle": "Dashboard Navigation",
"dashboardNavigationCardDescription": "Move between different pages to search data, discover recent trends, and create your own data visualizations.",
"recentUpdatesCardTitle": "Recent Updates",
"recentUpdatesCardDescription": "Your quick look at recent digital security trends in your community and around the world.",
"languageOptionsCardTitle": "Language Options",
"languageOptionsCardDescription": "You can change your language preference here and view your dashboard in your preferred language.",
"profileSettingsCardTitle": "Profile Settings",
"profileSettingsCardDescription": "This is your profile menu, where you can turn on/off your notifications and logout.",
"categoriesCardTitle": "Categories",
"categoriesCardDescription": "Search global data by choosing one or multiple categories.",
"subcategoriesCardTitle": "Subcategories",
"subcategoriesCardDescription": "Narrow your search by selecting one or multiple subcategories.",
"optionsCardTitle": "Options",
"optionsCardDescription": "Choose to Include or Exclude fields from your search.",
"incidentTypeCardTitle": "Incident Type",
"incidentTypeCardDescription": "What kind of attack or attempted attack was it?",
"dateRangeCardTitle": "Date Range",
"dateRangeCardDescription": "Choose a beginning and end date for your search or search within a relative timeframe.",
"targetedGroupCardTitle": "Targeted Group",
"targetedGroupCardDescription": "What individual, organization, or community was the target of the attack?",
"impactedTechnologyCardTitle": "Impacted Technology",
"impactedTechnologyCardDescription": "What devices, platforms, or services were affected by the incident?",
"regionCardTitle": "Region",
"regionCardDescription": "Choose geographical regions by country, continent or subregion. When nothing is checked, by default all regions are selected.",
"advancedOptionsCardTitle": "+ Advanced Options",
"advancedOptionsCardDescription": "Clicking this option will redirect you to the Kibana interface. Kibana is the data visualization platform that powers the Leafcutter dashboard. It provides more advanced search fields and options.",
"queryResultsCardTitle": "Your Query & Results",
"queryResultsCardDescription": "Your Query displays your chosen search criteria. Blue is what youve included and Pink is what youve excluded. Your Results display all available search results in a list view based on your search critiera.",
"viewResultsCardTitle": "View Results As:",
"viewResultsCardDescription": "Below are visualization options for displaying your search results. Highlighted boxes are the available options based on your specific search. Click to expand the visualization, save, or edit.",
"technology": "Technology",
"actor": "Actor",
"geography": "Geography",
"channel": "Channel",
"status": "Status",
"ticketFrequency": "Ticket Frequency",
"incidentType": "Incident Type",
"type": "Type",
"date": "Date",
"targetedGroup": "Targeted Group",
"group": "Group",
"impactedTechnology": "Impacted Technology",
"platform": "Platform",
"device": "Device",
"service": "Service",
"maker": "Maker",
"region": "Region",
"continent": "Continent",
"country": "Country",
"subregion": "Subregion",
"advancedOptions": "Advanced Options",
"fullInterfaceWillOpen": "The full OpenSearch Dashboards interface will open in a new window.",
"cancel": "Cancel",
"save": "Save",
"open": "Open",
"include": "Include",
"exclude": "Exclude",
"startDate": "Start Date",
"endDate": "End Date",
"relativeDate": "Relative Date",
"last7Days": "Last 7 days",
"last30Days": "Last 30 days",
"last3Months": "Last 3 months",
"last6Months": "Last 6 months",
"lastYear": "Last year",
"last2Years": "Last 2 years",
"where": "where",
"is": "is",
"isNot": "is not",
"or": "or",
"onOrAfter": "on or after",
"onOrBefore": "on or before",
"findAllIncidents": "Find all incidents",
"title": "Title",
"description": "Description",
"welcome": "Welcome",
"signOut": "Sign Out",
"incident": "Incident",
"results": "Results",
"query": "Query",
"viewAs": "View As",
"selectVisualization": "Select a Visualization",
"selectFieldVisualize": "Select a Field to Visualize",
"noSavedVisualizations": "You dont have any saved visualizations. Go to [Search and Create](/create) or [Trends](/trends) to get started.",
"getStartedChecklist": "Get Started Checklist",
"searchTitle": "Search",
"searchDescription": "This can be trends, new/saved visualizations",
"createVisualizationTitle": "Create Visualization",
"createVisualizationDescription": "This can be from data in trends",
"saveTitle": "Save",
"saveDescription": "As a .png, .pdf or .csv",
"exportTitle": "Export",
"exportDescription": "",
"shareTitle": "Share",
"shareDescription": "Externally or internally",
"savedSearch": "Saved Search",
"saveCurrentSearch": "Save Current Search",
"clear": "Clear",
"delete": "Delete"
}

View file

@ -1,44 +0,0 @@
{
"aboutLeafcutterTitle": "FRENCH!",
"aboutLeafcutterDescription": "FRENCH!",
"whatIsLeafcutterTitle": "FRENCH!",
"whatIsLeafcutterDescription": "FRENCH!",
"whatIsItForTitle": "FRENCH!",
"whatIsItForDescription": "FRENCH!",
"whoCanUseItTitle": "FRENCH!",
"whoCanUseItDescription": "FRENCH!",
"createVisualization": "FRENCH!",
"whereDataComesFromTitle": "FRENCH!",
"whereDataComesFromDescription": "FRENCH!",
"projectSupportTitle": "FRENCH!",
"projectSupportDescription": "FRENCH!",
"interestedInLeafcutterTitle": "FRENCH!",
"interestedInLeafcutterDescription": "FRENCH!\nFRENCH!",
"myVisualizationsMenuItem": "FRENCH!",
"myVisualizationsTooltipTitle": "FRENCH!",
"myVisualizationsTooltipDescription": "FRENCH!",
"aboutMenuItem": "FRENCH!",
"aboutTooltipTitle": "FRENCH!",
"aboutTooltipDescription": "FRENCH!",
"trendsMenuItem": "FRENCH!",
"trendsTooltipTitle": "FRENCH!",
"trendsTooltipDescription": "FRENCH!",
"searchDataMenuItem": "FRENCH!",
"searchDataTooltipTitle": "FRENCH!",
"searchDataTooltipDescription": "FRENCH!",
"createVisualizationsMenuItem": "FRENCH!",
"createVisualizationsTooltipTitle": "FRENCH!",
"createVisualizationsTooltipDescription": "FRENCH!",
"faqMenuItem": "FRENCH!",
"faqTooltipTitle": "FRENCH!",
"faqTooltipDescription": "FRENCH!",
"recentUpdatesTitle": "FRENCH!",
"language": "FRENCH!",
"languageTooltipTitle": "FRENCH!",
"languageTooltipDescription": "FRENCH!",
"copyright": "FRENCH!",
"projectOf": "FRENCH!",
"privacyPolicy": "FRENCH!",
"codeOfPractice": "FRENCH!",
"contactUs": "FRENCH!"
}

View file

@ -1,9 +0,0 @@
body {
overscroll-behavior-x: none;
overscroll-behavior-y: none;
text-size-adjust: none;
}
a {
text-decoration: none;
}

View file

@ -1,86 +0,0 @@
export const colors: any = {
lightGray: "#ededf0",
mediumGray: "#e3e5e5",
darkGray: "#33302f",
mediumBlue: "#4285f4",
green: "#349d7b",
lavender: "#a5a6f6",
darkLavender: "#5d5fef",
pink: "#fcddec",
cdrLinkOrange: "#ff7115",
coreYellow: "#fac942",
helpYellow: "#fff4d5",
dwcDarkBlue: "#191847",
hazyMint: "#ecf7f8",
leafcutterElectricBlue: "#4d6aff",
leafcutterLightBlue: "#fafbfd",
waterbearElectricPurple: "#332c83",
waterbearLightSmokePurple: "#eff3f8",
bumpedPurple: "#212058",
mutedPurple: "#373669",
warningPink: "#ef5da8",
lightPink: "#fff0f7",
lightGreen: "#f0fff3",
lightOrange: "#fff5f0",
beige: "#f6f2f1",
almostBlack: "#33302f",
white: "#ffffff",
};
export const typography: any = {
h1: {
fontFamily: "Playfair, serif",
fontSize: 45,
fontWeight: 700,
lineHeight: 1.1,
margin: 0,
},
h2: {
fontFamily: "Poppins, sans-serif",
fontSize: 35,
fontWeight: 700,
lineHeight: 1.1,
margin: 0,
},
h3: {
fontFamily: "Poppins, sans-serif",
fontWeight: 400,
fontSize: 27,
lineHeight: 1.1,
margin: 0,
},
h4: {
fontFamily: "Poppins, sans-serif",
fontWeight: 700,
fontSize: 18,
},
h5: {
fontFamily: "Roboto, sans-serif",
fontWeight: 700,
fontSize: 16,
lineHeight: "24px",
textTransform: "uppercase",
textAlign: "center",
margin: 1,
},
h6: {
fontFamily: "Roboto, sans-serif",
fontWeight: 400,
fontSize: 14,
textAlign: "center",
},
p: {
fontFamily: "Roboto, sans-serif",
fontSize: 17,
lineHeight: "26.35px",
fontWeight: 400,
margin: 0,
},
small: {
fontFamily: "Roboto, sans-serif",
fontSize: 13,
lineHeight: "18px",
fontWeight: 400,
margin: 0,
},
};

View file

@ -1,6 +0,0 @@
import NextAuth from "next-auth";
import { authOptions } from "app/_lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View file

@ -1,15 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
export const GET = async (req: NextRequest) => {
const validDomains = "localhost";
console.log({ req });
return NextResponse.json({ response: "ok" });
};
export const POST = async (req: NextRequest) => {
const validDomains = "localhost";
console.log({ req });
return NextResponse.json({ response: "ok" });
};

View file

@ -1,22 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "app/_lib/auth";
import { getUserMetadata, saveUserMetadata } from "app/_lib/opensearch";
export const POST = async (req: NextRequest) => {
const session = await getServerSession(authOptions);
const { user: { email } }: any = session;
const { name, query } = await req.json();
const result = await getUserMetadata(email);
const { savedSearches } = result;
await saveUserMetadata(email, {
savedSearches: [...savedSearches, { name, query }]
});
const { savedSearches: updatedSavedSearches } = await getUserMetadata(email);
return NextResponse.json(updatedSavedSearches);
};

Some files were not shown because too many files have changed in this diff Show more