diff --git a/.env.example b/.env.example index f4c5ac841a..4f98814337 100644 --- a/.env.example +++ b/.env.example @@ -18,13 +18,16 @@ NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY='your publishable key' DATABASE_URL='postgresql://postgres:mysecretpassword@localhost:5432/postgres' # Web -APP_URL='https://localhost:3000' +NEXT_PUBLIC_APP_URL='https://localhost:3000' GOOGLE_SITE_VERIFICATION_ID='your google verification id' GITHUB_ID='your github client ID' GITHUB_SECRET='your github secret ID' NEXTAUTH_SECRET='your next-auth secret' NEXTAUTH_URL='http://localhost:3000' +# All +NEXT_PUBLIC_SUPPORT_EMAIL='support@manicode.ai' + ################################################################# # PLEASE SEE JAMES OR BRANDON FOR THE REAL ENVIRONMENT VARIABLES! ################################################################# \ No newline at end of file diff --git a/authentication.knowledge.md b/authentication.knowledge.md index 7c9d2f979c..6b814f5505 100644 --- a/authentication.knowledge.md +++ b/authentication.knowledge.md @@ -16,7 +16,7 @@ Manicode implements a secure authentication flow that involves the npm-app (CLI) a. `fingerprintId` (to link the current session with user credentials) b. Timestamp (5 minutes in the future, for link expiration) c. Hash of the above + a secret value (for request verification) - - Backend appends this auth code to the login URL: `${APP_URL}/login?auth_code=` + - Backend appends this auth code to the login URL: `${NEXT_PUBLIC_APP_URL}/login?auth_code=` 3. User Login: diff --git a/backend/knowledge.md b/backend/knowledge.md index 79bc8170f6..a8df0ae500 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -70,6 +70,31 @@ The backend handles file operations for the Manicode project: - **Reading Files**: The `read_files` tool allows the AI to access project file contents. - **Applying Changes**: The `applyChanges` function in `prompts.ts` processes and applies file modifications suggested by the AI. +## Code Organization and Best Practices + +1. **Centralize Shared Logic**: When implementing functionality that's used in multiple places (e.g., web API and backend), create shared functions to promote code reuse and consistency. This is particularly important for business logic like referral handling and usage calculations. + +2. **Shared Function Location**: Place shared functions in a common directory accessible to both the web API and backend. Consider creating a `common/src/utils` directory for such shared functionality. + +3. **DRY Principle**: Always look for opportunities to refactor repeated code into shared, reusable functions. This not only reduces code duplication but also makes maintenance and updates easier. + +4. **Consistent API**: When creating shared functions, ensure they have a consistent API that can be easily used by different parts of the application. + +5. **Testing Shared Functions**: Implement unit tests for shared functions to ensure they work correctly in all contexts where they are used. + +6. **Documentation**: Document shared functions clearly, including their purpose, inputs, outputs, and any side effects, so that other developers can use them effectively. + +7. **Version Control**: When making changes to shared functions, consider the impact on all parts of the application that use them, and test thoroughly. + +8. **Dependency Injection**: Prefer pulling common dependencies (like database connections or environment variables) from centralized locations rather than passing them as parameters. This reduces function complexity and improves maintainability. + +9. **Single Responsibility Principle**: Design functions to have a single, well-defined purpose. For example, separate the logic of determining eligibility for a referral code from the generation of the full referral link. + +10. **Abstraction Refinement**: Be prepared to refine initial implementations as the system's needs become clearer. This might involve changing function signatures, splitting functions, or adjusting their purposes to better fit the overall architecture. + + + + ## Development Guidelines 1. **Type Safety**: Utilize TypeScript's type system to ensure code reliability and catch errors early. @@ -145,6 +170,29 @@ export const logger = pino({ 4. Create a robust testing suite for backend components. 5. Optimize the file diff generation process for better reliability and performance. +## Referral System + +The referral system is an important feature of our application. Here are key points to remember: + +1. **Referral Limit**: Users are limited to a maximum number of successful referrals (currently set to 5). + +2. **Limit Enforcement**: The referral limit must be enforced during the redemption process (POST request), not just when displaying referral information (GET request). + +3. **Centralized Logic**: The `hasMaxedReferrals` function in `common/src/util/referral.ts` is used to check if a user has reached their referral limit. This function should be used consistently across the application to ensure uniform enforcement of the referral limit. + +4. **Redemption Process**: When redeeming a referral code (in the POST request handler), always check if the referrer has maxed out their referrals before processing the redemption. This ensures that users cannot exceed their referral limit even if they distribute their referral code widely. + +5. **Error Handling**: Provide clear error messages when a referral code cannot be redeemed due to the referrer reaching their limit. This helps maintain a good user experience. + +Remember to keep the referral system logic consistent between the backend API and the websocket server to ensure uniform behavior across different parts of the application. + + + + + + + + ## Debugging Docker Issues - When encountering "Cannot find module" errors in a Docker container, it's important to verify the contents of the container itself, not just the local build. @@ -194,3 +242,5 @@ This project uses Bun for testing instead of Jest. When writing tests, keep the - Bun's test API is similar to Jest's, but there are some differences in implementation. - When mocking methods, use `mock(object.method)` instead of Jest's `jest.spyOn(object, 'method')`. - Bun's `mock` function expects 0-1 arguments, not 2 like Jest's `spyOn`. + +Remember to keep this knowledge file updated as the application evolves or new features are added. diff --git a/backend/src/env.mjs b/backend/src/env.mjs index 5476685810..e65add2659 100644 --- a/backend/src/env.mjs +++ b/backend/src/env.mjs @@ -24,7 +24,7 @@ export const env = createEnv({ STRIPE_SUBSCRIPTION_PRICE_ID: z.string().min(1), PORT: z.coerce.number().min(1000), ENVIRONMENT: z.string().min(1), - APP_URL: z.string().min(1), + NEXT_PUBLIC_APP_URL: z.string().min(1), NEXTAUTH_SECRET: z.string().min(1), }, runtimeEnv: process.env, diff --git a/backend/src/websockets/middleware.ts b/backend/src/websockets/middleware.ts index 06003b3987..3ce2f99cc6 100644 --- a/backend/src/websockets/middleware.ts +++ b/backend/src/websockets/middleware.ts @@ -82,9 +82,6 @@ protec.use(async (action, _clientSessionId, _) => { logger.debug(`Protecting action of type: '${action.type}'`) }) protec.use(async (action, _clientSessionId, ws) => { - if (env.ENVIRONMENT === 'local') { - return - } return match(action) .with( { diff --git a/backend/src/websockets/websocket-action.ts b/backend/src/websockets/websocket-action.ts index b121a10a46..c3b00edab8 100644 --- a/backend/src/websockets/websocket-action.ts +++ b/backend/src/websockets/websocket-action.ts @@ -11,13 +11,14 @@ import { getSearchSystemPrompt } from '../system-prompt' import { promptClaude } from '../claude' import { env } from '../env.mjs' import db from 'common/db' -import * as schema from 'common/db/schema' import { genAuthCode } from 'common/util/credentials' +import * as schema from 'common/db/schema' import { claudeModels } from 'common/constants' import { protec } from './middleware' import { getQuotaManager } from '@/billing/quota-manager' import { logger, withLoggerContext } from '@/util/logger' import { generateCommitMessage } from '@/generate-commit-message' +import { hasMaxedReferrals } from 'common/util/server/referral' export const sendAction = (ws: WebSocket, action: ServerAction) => { sendMessage(ws, { @@ -51,10 +52,7 @@ async function calculateUsage(fingerprintId: string, userId?: string) { userId ? 'authenticated' : 'anonymous', userId ?? fingerprintId ) - const { creditsUsed, quota } = await quotaManager.checkQuota() - if (env.ENVIRONMENT === 'local') { - return { usage: creditsUsed, limit: Infinity } - } + const { creditsUsed, quota } = await quotaManager.updateQuota() return { usage: creditsUsed, limit: quota } } @@ -180,7 +178,10 @@ const onClearAuthTokenRequest = async ( } const onLoginCodeRequest = ( - { fingerprintId }: Extract, + { + fingerprintId, + referralCode, + }: Extract, _clientSessionId: string, ws: WebSocket ): void => { @@ -191,7 +192,7 @@ const onLoginCodeRequest = ( expiresAt.toString(), env.NEXTAUTH_SECRET ) - const loginUrl = `${env.APP_URL}/login?auth_code=${fingerprintId}.${expiresAt}.${fingerprintHash}` + const loginUrl = `${env.NEXT_PUBLIC_APP_URL}/login?auth_code=${fingerprintId}.${expiresAt}.${fingerprintHash}${referralCode ? `&referral_code=${referralCode}` : ''}` sendAction(ws, { type: 'login-code-response', @@ -323,10 +324,20 @@ const onUsageRequest = async ( const { usage, limit } = await calculateUsage(fingerprintId, userId) await withLoggerContext({ fingerprintId, userId, usage, limit }, async () => { logger.info('Sending usage info') + + let referralLink: string | undefined = undefined + if (userId) { + const shouldGenerateReferralLink = await hasMaxedReferrals(userId) + if (shouldGenerateReferralLink.reason === undefined) { + referralLink = shouldGenerateReferralLink.referralLink + } + } + sendAction(ws, { type: 'usage-response', usage, limit, + referralLink, }) }) } @@ -414,7 +425,7 @@ export const onWebsocketAction = async ( } subscribeToAction('user-input', protec.run(onUserInput)) -subscribeToAction('init', () => protec.run(onInit)) +subscribeToAction('init', protec.run(onInit)) subscribeToAction('clear-auth-token', onClearAuthTokenRequest) subscribeToAction('login-code-request', onLoginCodeRequest) diff --git a/bun.lockb b/bun.lockb index 92b7636da5..4cf1421eca 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/common/src/actions.ts b/common/src/actions.ts index 2a0ed9feb1..328a6d3624 100644 --- a/common/src/actions.ts +++ b/common/src/actions.ts @@ -91,6 +91,7 @@ export const CLIENT_ACTION_SCHEMA = z.discriminatedUnion('type', [ z.object({ type: z.literal('login-code-request'), fingerprintId: z.string(), + referralCode: z.string().optional(), }), z.object({ type: z.literal('login-status-request'), @@ -167,6 +168,7 @@ export const SERVER_ACTION_SCHEMA = z.discriminatedUnion('type', [ type: z.literal('usage-response'), usage: z.number(), limit: z.number(), + referralLink: z.string().optional(), }), z.object({ type: z.literal('quota-exceeded'), diff --git a/common/src/constants.ts b/common/src/constants.ts index c0749d29a7..a25e70d2c8 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,3 +1,5 @@ +// import { env } from './env.mjs' + export const STOP_MARKER = '[' + 'END]' export const FIND_FILES_MARKER = '[' + 'FIND_FILES_PLEASE]' export const TOOL_RESULT_MARKER = '[' + 'TOOL_RESULT]' @@ -39,11 +41,20 @@ export const SKIPPED_TERMINAL_COMMANDS = [ export const MAX_DATE = new Date(86399999999999) -export const CREDITS_USAGE_LIMITS = { - ANON: 1_000, - FREE: 2_500, - PAID: 50_000, -} +export type UsageLimits = 'ANON' | 'FREE' | 'PAID' +export const CREDITS_USAGE_LIMITS: Record = + process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' + ? { + ANON: 1_000_000, + FREE: 2_500_000, + PAID: 50_000_000, + } + : { + ANON: 1_000, + FREE: 2_500, + PAID: 50_000, + } +export const CREDITS_REFERRAL_BONUS = 500 export const claudeModels = { sonnet: 'claude-3-5-sonnet-20240620', @@ -61,3 +72,5 @@ export const models = { } export const TEST_USER_ID = 'test-user-id' + +export const MAX_REFERRALS = 5 diff --git a/common/src/db/migrations/0004_neat_pet_avengers.sql b/common/src/db/migrations/0004_neat_pet_avengers.sql new file mode 100644 index 0000000000..cb4e9ecd3b --- /dev/null +++ b/common/src/db/migrations/0004_neat_pet_avengers.sql @@ -0,0 +1,30 @@ +DO $$ BEGIN + CREATE TYPE "public"."referral_status" AS ENUM('pending', 'completed'); +EXCEPTION + WHEN duplicate_object THEN null; +END $$; +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "referral" ( + "referrer_id" text NOT NULL, + "referred_id" text NOT NULL, + "status" "referral_status" DEFAULT 'pending' NOT NULL, + "credits" integer NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL, + "completed_at" timestamp, + CONSTRAINT "referral_referrer_id_referred_id_pk" PRIMARY KEY("referrer_id","referred_id") +); +--> statement-breakpoint +ALTER TABLE "user" ADD COLUMN "referral_code" text DEFAULT 'ref-' || gen_random_uuid();--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "referral" ADD CONSTRAINT "referral_referrer_id_user_id_fk" FOREIGN KEY ("referrer_id") REFERENCES "public"."user"("id") ON DELETE no action ON UPDATE no action; +EXCEPTION + WHEN duplicate_object THEN null; +END $$; +--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "referral" ADD CONSTRAINT "referral_referred_id_user_id_fk" FOREIGN KEY ("referred_id") REFERENCES "public"."user"("id") ON DELETE no action ON UPDATE no action; +EXCEPTION + WHEN duplicate_object THEN null; +END $$; +--> statement-breakpoint +ALTER TABLE "user" ADD CONSTRAINT "user_referral_code_unique" UNIQUE("referral_code"); \ No newline at end of file diff --git a/common/src/db/migrations/meta/0004_snapshot.json b/common/src/db/migrations/meta/0004_snapshot.json new file mode 100644 index 0000000000..0d6784a5ee --- /dev/null +++ b/common/src/db/migrations/meta/0004_snapshot.json @@ -0,0 +1,550 @@ +{ + "id": "14fe47ea-d311-4f6a-b602-37794097cf07", + "prevId": "f13073d6-b3ee-4808-80f7-cde01d1875df", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "providerAccountId": { + "name": "providerAccountId", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "token_type": { + "name": "token_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_state": { + "name": "session_state", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "account_userId_user_id_fk": { + "name": "account_userId_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["userId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "account_provider_providerAccountId_pk": { + "name": "account_provider_providerAccountId_pk", + "columns": ["provider", "providerAccountId"] + } + }, + "uniqueConstraints": {} + }, + "public.fingerprint": { + "name": "fingerprint", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "sig_hash": { + "name": "sig_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quota_exceeded": { + "name": "quota_exceeded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "next_quota_reset": { + "name": "next_quota_reset", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now() + INTERVAL '1 month'" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "public.message": { + "name": "message", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_request_id": { + "name": "client_request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_message": { + "name": "last_message", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "\"message\".\"request\" -> -1", + "type": "stored" + } + }, + "response": { + "name": "response", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_creation_input_tokens": { + "name": "cache_creation_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_read_input_tokens": { + "name": "cache_read_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cost": { + "name": "cost", + "type": "numeric(100, 20)", + "primaryKey": false, + "notNull": true + }, + "credits": { + "name": "credits", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fingerprint_id": { + "name": "fingerprint_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "message_user_id_user_id_fk": { + "name": "message_user_id_user_id_fk", + "tableFrom": "message", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "message_fingerprint_id_fingerprint_id_fk": { + "name": "message_fingerprint_id_fingerprint_id_fk", + "tableFrom": "message", + "tableTo": "fingerprint", + "columnsFrom": ["fingerprint_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "public.referral": { + "name": "referral", + "schema": "", + "columns": { + "referrer_id": { + "name": "referrer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "referred_id": { + "name": "referred_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "referral_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "credits": { + "name": "credits", + "type": "integer", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "referral_referrer_id_user_id_fk": { + "name": "referral_referrer_id_user_id_fk", + "tableFrom": "referral", + "tableTo": "user", + "columnsFrom": ["referrer_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "referral_referred_id_user_id_fk": { + "name": "referral_referred_id_user_id_fk", + "tableFrom": "referral", + "tableTo": "user", + "columnsFrom": ["referred_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "referral_referrer_id_referred_id_pk": { + "name": "referral_referrer_id_referred_id_pk", + "columns": ["referrer_id", "referred_id"] + } + }, + "uniqueConstraints": {} + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "sessionToken": { + "name": "sessionToken", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires": { + "name": "expires", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "fingerprint_id": { + "name": "fingerprint_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "session_userId_user_id_fk": { + "name": "session_userId_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["userId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "session_fingerprint_id_fingerprint_id_fk": { + "name": "session_fingerprint_id_fingerprint_id_fk", + "tableFrom": "session", + "tableTo": "fingerprint", + "columnsFrom": ["fingerprint_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "emailVerified": { + "name": "emailVerified", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subscription_active": { + "name": "subscription_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_price_id": { + "name": "stripe_price_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quota": { + "name": "quota", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "quota_exceeded": { + "name": "quota_exceeded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "next_quota_reset": { + "name": "next_quota_reset", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now() + INTERVAL '1 month'" + }, + "referral_code": { + "name": "referral_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'ref-' || gen_random_uuid()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": ["email"] + }, + "user_stripe_customer_id_unique": { + "name": "user_stripe_customer_id_unique", + "nullsNotDistinct": false, + "columns": ["stripe_customer_id"] + }, + "user_referral_code_unique": { + "name": "user_referral_code_unique", + "nullsNotDistinct": false, + "columns": ["referral_code"] + } + } + }, + "public.verificationToken": { + "name": "verificationToken", + "schema": "", + "columns": { + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires": { + "name": "expires", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "verificationToken_identifier_token_pk": { + "name": "verificationToken_identifier_token_pk", + "columns": ["identifier", "token"] + } + }, + "uniqueConstraints": {} + } + }, + "enums": { + "public.referral_status": { + "name": "referral_status", + "schema": "public", + "values": ["pending", "completed"] + } + }, + "schemas": {}, + "sequences": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/common/src/db/migrations/meta/_journal.json b/common/src/db/migrations/meta/_journal.json index cfa3ab1326..2f580c730f 100644 --- a/common/src/db/migrations/meta/_journal.json +++ b/common/src/db/migrations/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1727986902407, "tag": "0003_military_owl", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1728448952748, + "tag": "0004_neat_pet_avengers", + "breakpoints": true } ] } \ No newline at end of file diff --git a/common/src/db/schema.knowledge.md b/common/src/db/schema.knowledge.md new file mode 100644 index 0000000000..fc14891efa --- /dev/null +++ b/common/src/db/schema.knowledge.md @@ -0,0 +1,97 @@ +# Referral Feature Implementation Plan + +## Database Schema Changes + +### User Table Update + +- Add `referral_code` field to the `user` table + - Type: `text` + - Unique constraint + - Default value: randomly generated UUID with a prefix of `ref-` + +### New Referral Table + +Create a new `referral` table with the following structure: + +- `referrer_id` (part of composite primary key, foreign key to user table) +- `referred_id` (part of composite primary key, foreign key to user table) +- `status` (e.g., 'pending', 'completed') +- `created_at` timestamp +- `completed_at` timestamp (when the referred user signs up) + +## Implementation Steps + +1. Update Database Schema + + - Modify `common/src/db/schema.ts` to include the new `referral` table and update the `user` table + +2. NextJS Pages + + - Create `web/src/app/referrals/page.tsx` for users to view and manage referrals + - Update `web/src/app/onboard/page.tsx` to handle referral codes during sign-up + +3. UI Components + + - displaying referral information + - sharing referral code + - regenerating referral code + - inputting referral link/code manually + +4. API Routes + + - Create `web/src/app/api/referrals/route.ts` for referral-related operations + - Implement security measures to prevent system abuse: + a. Add validation to prevent self-referrals: + - Check if the referred user ID is different from the referrer's ID + - Reason: Prevents users from gaining benefits by referring themselves + b. Limit each referral code to be used 5 times: + - Keep a count of successful referrals for each code + - Reject referrals once the limit is reached + - Reason: Prevents a single code from being overused, encouraging wider distribution + c. Implement rate limiting for referral code generation: + - Use a local cache that clears daily + - Limit the number of codes a user can generate per day + - Reason: Prevents spam and abuse of the referral system + - Implementation tips: + - Use a middleware or decorator for rate limiting + - Implement atomic operations for updating referral counts to handle concurrent requests + - Update user quota when a referral is successful + - Use a database transaction to ensure atomicity of referral creation and quota update + - Reason: Maintains data consistency by ensuring both operations succeed or fail together + - Important: Implement these security measures in the GET method of the referrals API route + - Important: Implement these security measures in the GET method of the referrals API route + - Reason: Ensures ongoing validation of referrals, not just at the point of creation + - Helps maintain system integrity by constantly checking for potential abuse + +5. Authentication Flow + + - Modify `web/src/app/api/auth/[...nextauth]/auth-options.ts` to add referral code to `redirect` URL, if it was provided. + - Ensure proper error handling for all new operations + - Update `web/src/app/onboard/page.tsx` to automatically create a referral and update quotas when a user visits with a `referral_code` query parameter: + - Extract the `referral_code` from the query parameters + - If a valid `referral_code` is present, call the referral API to create the referral and update quotas + - Handle any errors that may occur during this process + - Provide feedback to the user about the successful referral or any issues + +6. Constants + - Add referral-related constants (e.g., quota reward amounts) to `common/src/constants.ts` + +6. Authentication Flow + + - Modify `web/src/app/api/auth/[...nextauth]/auth-options.ts` to add referral code to `redirect` URL, if it was provided. + - Ensure proper error handling for all new operations + +7. Testing + + - Add unit tests for new database operations and API routes + - Create integration tests for the referral flow + +8. Documentation + + - Update relevant documentation to include information about the referral system + +## Notes + +- The existing `quota` field in the `user` table will be used to manage referral rewards +- The referral system leverages the composite primary key of `referrer_id` and `referred_id` for efficiency +- The `referral_code` is stored in the `user` table for simplified lookups and management diff --git a/common/src/db/schema.ts b/common/src/db/schema.ts index f7d3d17e4b..f9b030a12a 100644 --- a/common/src/db/schema.ts +++ b/common/src/db/schema.ts @@ -8,8 +8,17 @@ import { boolean, jsonb, numeric, + uuid, + pgEnum, } from 'drizzle-orm/pg-core' import type { AdapterAccount } from 'next-auth/adapters' +import { ReferralStatusValues } from '../types/referral' + +// Define the ReferralStatus enum +export const ReferralStatus = pgEnum('referral_status', [ + ReferralStatusValues[0], + ...ReferralStatusValues.slice(1), +]) export const user = pgTable('user', { id: text('id') @@ -28,6 +37,9 @@ export const user = pgTable('user', { next_quota_reset: timestamp('next_quota_reset', { mode: 'date' }).default( sql`now() + INTERVAL '1 month'` ), + referral_code: text('referral_code') + .unique() + .default(sql`'ref-' || gen_random_uuid()`), }) export const account = pgTable( @@ -54,6 +66,26 @@ export const account = pgTable( }) ) +export const referral = pgTable( + 'referral', + { + referrer_id: text('referrer_id') + .notNull() + .references(() => user.id), + referred_id: text('referred_id') + .notNull() + .references(() => user.id), + status: ReferralStatus('status').notNull().default('pending'), + credits: integer('credits').notNull(), + created_at: timestamp('created_at', { mode: 'date' }) + .notNull() + .defaultNow(), + completed_at: timestamp('completed_at', { mode: 'date' }), + }, + (table) => ({ + pk: primaryKey({ columns: [table.referrer_id, table.referred_id] }), + }) +) export const fingerprint = pgTable('fingerprint', { id: text('id').primaryKey(), sig_hash: text('sig_hash'), diff --git a/common/src/env.mjs b/common/src/env.mjs index 3a5b4c670c..54c7631959 100644 --- a/common/src/env.mjs +++ b/common/src/env.mjs @@ -3,21 +3,32 @@ import { z } from 'zod' import dotenv from 'dotenv' dotenv.config({ path: '../stack.env' }) -if (!process.env.ENVIRONMENT) { +if (!process.env.NEXT_PUBLIC_ENVIRONMENT) { console.error('ENVIRONMENT is not set, please check `stack.env`') process.exit(1) } const DOTENV_PATH = process.env.RENDER === 'true' ? '/etc/secrets' : '..' -const path = `${DOTENV_PATH}/.env.${process.env.ENVIRONMENT}` -console.log(`Using environment: ${process.env.ENVIRONMENT} (path: ${path})`) +const path = `${DOTENV_PATH}/.env.${process.env.NEXT_PUBLIC_ENVIRONMENT}` +console.log( + `Using environment: ${process.env.NEXT_PUBLIC_ENVIRONMENT} (path: ${path})` +) dotenv.config({ path }) export const env = createEnv({ server: { ENVIRONMENT: z.string().min(1), + NEXT_PUBLIC_ENVIRONMENT: z.string().min(1), DATABASE_URL: z.string().min(1), STRIPE_SECRET_KEY: z.string().min(1), }, - runtimeEnv: process.env, + client: { + NEXT_PUBLIC_ENVIRONMENT: z.string().min(1), + NEXT_PUBLIC_APP_URL: z.string().min(1), + }, + runtimeEnv: { + ...process.env, + NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL, + NEXT_PUBLIC_ENVIRONMENT: process.env.NEXT_PUBLIC_ENVIRONMENT, + }, }) diff --git a/common/src/types/referral.ts b/common/src/types/referral.ts new file mode 100644 index 0000000000..27a51edf89 --- /dev/null +++ b/common/src/types/referral.ts @@ -0,0 +1,3 @@ +export type ReferralStatus = 'pending' | 'completed' + +export const ReferralStatusValues: ReferralStatus[] = ['pending', 'completed'] diff --git a/common/src/util/referral.ts b/common/src/util/referral.ts new file mode 100644 index 0000000000..7fdf8d79ea --- /dev/null +++ b/common/src/util/referral.ts @@ -0,0 +1,2 @@ +export const getReferralLink = (referralCode: string): string => + `${process.env.NEXT_PUBLIC_APP_URL}/referrals/${referralCode}` diff --git a/common/src/util/server/referral.ts b/common/src/util/server/referral.ts new file mode 100644 index 0000000000..96643c2c21 --- /dev/null +++ b/common/src/util/server/referral.ts @@ -0,0 +1,41 @@ +import { eq, sql } from 'drizzle-orm' +import * as schema from '../../db/schema' +import db from '../../db' +import { getReferralLink } from '../referral' +import { MAX_REFERRALS } from '../../constants' + +export async function hasMaxedReferrals(userId: string): Promise< + | { + reason: + | 'You have reached your usage limit' + | "Your user isn't in our system" + } + | { + reason: undefined + referralLink: string + } +> { + const referral = await db + .select({ + referralCode: schema.user.referral_code, + limitReached: sql`count(*) >= ${MAX_REFERRALS}`, + }) + .from(schema.referral) + .leftJoin(schema.user, eq(schema.referral.referrer_id, schema.user.id)) + .where(eq(schema.referral.referrer_id, userId)) + .groupBy(schema.user.referral_code) + .then((result) => (result.length > 0 ? result[0] : undefined)) + + if (!referral || !referral.referralCode) { + return { reason: "Your user isn't in our system" } + } + + if (referral.limitReached) { + return { reason: 'You have reached your usage limit' } + } + + return { + reason: undefined, + referralLink: getReferralLink(referral.referralCode), + } +} diff --git a/knowledge.md b/knowledge.md index d71f8f795a..587b54f236 100644 --- a/knowledge.md +++ b/knowledge.md @@ -57,6 +57,23 @@ There are three top-level code directories: - `src/index.ts`: Contains main application logic and user input handling. - `knowledge.md`: Stores project-wide knowledge and best practices. +## Referral System + +The Manicode project includes a referral system designed to encourage user growth and reward existing users for bringing in new members. Here's a high-level overview: + +- Purpose: Increase user base and engagement by incentivizing current users to invite others. +- Functionality: Users can share a unique referral code or link with potential new users. +- Reward: Both the referrer and the new user receive bonus credits upon successful referral. +- Implementation: Spread across multiple files in the project, handling various aspects such as code generation, validation, and reward distribution. +- Limits: There's a cap on the number of referrals a user can make to prevent system abuse. + +The referral system integrates with the user authentication flow and credit management system, providing a seamless experience for both new and existing users. +- `common/src/util/server/referral.ts`: Contains the `hasMaxedReferrals` function to check if a user has reached their referral limit. +- `web/src/app/api/referrals/route.ts`: Handles API routes for referral-related operations. +- `common/src/util/referral.ts`: Contains utility functions like `getReferralLink`. + +The `MAX_REFERRALS` constant is used to limit the number of referrals a user can make. + ## Development Guidelines 1. Use TypeScript for all new code to maintain type safety. @@ -149,6 +166,42 @@ Mani can now execute terminal commands using the `run_terminal_command` tool. Th - We don't specify return types for functions, since Typescript will infer them. - Always include 'src' in file paths when it's part of the actual directory structure, even though imports automatically remove it. +## Constants and Configuration + +Important constants and configuration values are centralized in `common/src/constants.ts`. This includes: + +- `MAX_REFERRALS`: The maximum number of referrals a user can make (currently set to 5). +- `CREDITS_REFERRAL_BONUS`: The number of credits awarded for a successful referral. +- `CREDITS_USAGE_LIMITS`: Defines credit limits for different user types (ANON, FREE, PAID). + +Centralizing these constants makes it easier to manage and update project-wide settings. + +## Referral System + +Manicode implements a referral system to encourage user growth and reward existing users for bringing in new members. The referral system works as follows: + +1. Each user receives a unique referral code. +2. Users can share their referral code with others. +3. When a new user signs up using a referral code, both the referrer and the new user receive bonus credits. +4. There's a limit to how many successful referrals a user can make. + +The referral system is integrated across the web application and the CLI tool, providing a seamless experience for users to share and redeem referral codes. + +## Development Guidelines + +1. Use TypeScript for all new code to maintain type safety. +The referral system is implemented across several files: + +- Implement authentication and authorization for WebSocket connections. +- Add more comprehensive error handling and logging. +- Implement rate limiting for AI requests to manage resource usage. +- Create a robust testing suite for all components. + +# Code guide + +- We don't specify return types for functions, since Typescript will infer them. +- Always include 'src' in file paths when it's part of the actual directory structure, even though imports automatically remove it. + ## Python Package A Python package for Manicode has been created as a skeleton in python-app. Key points: diff --git a/npm-app/knowledge.md b/npm-app/knowledge.md index df25cfe906..1611a0b867 100644 --- a/npm-app/knowledge.md +++ b/npm-app/knowledge.md @@ -214,6 +214,22 @@ Developers should continue to improve error handling to ensure a smooth user exp - File operations are restricted to the project directory to prevent unauthorized access to the user's system. - Web scraping and external API calls (e.g., Manifold Markets) should be used responsibly and in compliance with the respective services' terms of use. +## Referral System + +The referral system is integrated directly into the CLI application: + +- Users enter referral codes as regular input in the CLI. +- The system detects input with the prefix "ref-" as a referral code. +- When a referral code is detected, the system automatically initiates a login-code-request with the entered referral code. +- The referral code is appended as a query parameter to the login link. +- This process seamlessly combines referral code entry with the user authentication flow. + +Implementation notes: +- Modify the handleUserInput function in cli.ts to detect "ref-" prefixed input. +- Update the login flow in client.ts to include the referral code when present. +- Ensure the backend (websocket-action.ts) appends the referral code to the login link as a query parameter. +- Web scraping and external API calls (e.g., Manifold Markets) should be used responsibly and in compliance with the respective services' terms of use. + ## Future Improvements 1. Implement user authentication for the WebSocket connection. @@ -238,6 +254,19 @@ This system allows for better tracking and correlation of user inputs with their - Users are instructed to update using the command: `npm install -g manicode` - The version check is performed as part of the WebSocket subscription setup. +### Usage Warnings and Referral System + +The client now integrates usage warnings with the referral system to encourage user growth: + +- The 'usage-response' action from the backend includes a 'referralLink' field. +- This referral link is displayed to logged-in users who haven't made more than 5 referrals yet. +- The `showUsageWarning` function in the client displays this referral link alongside the usage warning. + +This feature combines user authentication, referral tracking, and usage monitoring to promote user acquisition through the CLI interface. + +## User Notifications + +### Usage Warnings ## User Notifications ### Usage Warnings diff --git a/npm-app/loadEnv.js b/npm-app/loadEnv.js index cf4cd660a7..d5b0cd577c 100644 --- a/npm-app/loadEnv.js +++ b/npm-app/loadEnv.js @@ -2,7 +2,7 @@ const fs = require('fs') const { match } = require('ts-pattern') const dotenv = require('dotenv') -const ENV_VARS_TO_PULL = ['APP_URL', 'NEXT_PUBLIC_BACKEND_URL'] +const ENV_VARS_TO_PULL = ['NEXT_PUBLIC_APP_URL', 'NEXT_PUBLIC_BACKEND_URL'] dotenv.config({ path: '../stack.env' }) if (!process.env.ENVIRONMENT) { diff --git a/npm-app/src/cli.ts b/npm-app/src/cli.ts index b48c793dd7..6f4935a736 100644 --- a/npm-app/src/cli.ts +++ b/npm-app/src/cli.ts @@ -134,6 +134,8 @@ export class CLI { } public printInitialPrompt(initialInput?: string) { + this.client.getUsage() + if (this.client.user) { console.log( `Welcome back ${this.client.user.name}! What would you like to do?\n` @@ -277,6 +279,13 @@ export class CLI { if (userInput === 'login' || userInput === 'signin') { await this.client.login() return + } else if (userInput === 'logout' || userInput === 'signout') { + await this.client.logout() + this.rl.prompt() + return + } else if (userInput.startsWith('ref-')) { + await this.client.handleReferralCode(userInput.trim()) + return } else if (userInput === 'usage' || userInput === 'credits') { this.client.getUsage() return @@ -322,17 +331,7 @@ export class CLI { } if (this.client.lastWarnedPct >= 100) { - console.error( - [ - red( - 'You have reached your monthly usage limit. You must upgrade your plan to continue using the service.' - ), - this.client.user - ? yellow('Visit https://manicode.ai/pricing to upgrade.') - : yellow('Type "login" to sign up and get more credits!'), - ].join('\n') - ) - this.rl.prompt() + this.client.getUsage() // refresh, in case user upgraded return } this.startLoadingAnimation() diff --git a/npm-app/src/client.ts b/npm-app/src/client.ts index e561444467..1f30d04793 100644 --- a/npm-app/src/client.ts +++ b/npm-app/src/client.ts @@ -1,4 +1,4 @@ -import { yellow, red } from 'picocolors' +import { yellow, red, green } from 'picocolors' import { APIRealtimeClient } from 'common/websockets/websocket-client' import { getFiles, @@ -10,13 +10,15 @@ import { CREDENTIALS_PATH, User, userFromJson } from 'common/util/credentials' import { ChatStorage } from './chat-storage' import { FileChanges, Message } from 'common/actions' import { toolHandlers } from './tool-handlers' -import { CREDITS_USAGE_LIMITS, TOOL_RESULT_MARKER } from 'common/constants' +import { + CREDITS_REFERRAL_BONUS, + CREDITS_USAGE_LIMITS, + TOOL_RESULT_MARKER, +} from 'common/constants' import { fingerprintId } from './config' import { uniq } from 'lodash' -import { spawn } from 'child_process' import path from 'path' import * as fs from 'fs' -import { sleep } from 'common/util/helpers' import { match, P } from 'ts-pattern' export class Client { @@ -55,7 +57,49 @@ export class Client { this.setupSubscriptions() } - async login() { + async handleReferralCode(referralCode: string) { + if (this.user) { + // User is logged in, so attempt to redeem referral code directly + try { + const redeemReferralResp = await fetch( + `${process.env.NEXT_PUBLIC_APP_URL}/api/referrals`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Cookie: `next-auth.session-token=${this.user.authToken};`, + }, + body: JSON.stringify({ + referralCode, + authToken: this.user.authToken, + }), + } + ) + const respJson = await redeemReferralResp.json() + if (redeemReferralResp.ok) { + console.log( + [ + green( + `Noice, you've earned an extra ${respJson.credits_redeemed} credits!` + ), + `(pssst: you can also refer new users and earn ${CREDITS_REFERRAL_BONUS} credits for each referral at: ${process.env.NEXT_PUBLIC_APP_URL}/referrals)`, + ].join('\n') + ) + this.getUsage() + } else { + throw new Error(respJson.error) + } + } catch (e) { + const error = e as Error + console.error(red('Error: ' + error.message)) + this.returnControlToUser() + } + } else { + await this.login(referralCode) + } + } + + async logout() { if (this.user) { // If there was an existing user, clear their existing state this.webSocket.sendAction({ @@ -68,12 +112,17 @@ export class Client { // delete credentials file fs.unlinkSync(CREDENTIALS_PATH) + console.log(`Logged you out of your account (${this.user.name})`) this.user = undefined } + } + async login(referralCode?: string) { + this.logout() this.webSocket.sendAction({ type: 'login-code-request', fingerprintId, + referralCode, }) } @@ -149,20 +198,14 @@ export class Client { 'login-code-response', async ({ loginUrl, fingerprintHash }) => { const responseToUser = [ - 'See you back here after you finish logging in 👋', - "If you're not redirected in a few seconds, please visit the following URL to log in:", + 'Please visit the following URL to log in:', + '\n', loginUrl, '\n', + 'See you back here after you finish logging in 👋', ] console.log(responseToUser.join('\n')) - // Attempt to open the login URL in the user's browser for them - await sleep(5000).then(() => { - const childProcess = spawn(`open ${loginUrl}`, { - shell: true, - }) - }) - // call backend every few seconds to check if user has been created yet, using our fingerprintId, for up to 5 minutes const initialTime = Date.now() shouldRequestLogin = true @@ -211,14 +254,18 @@ export class Client { }) this.webSocket.subscribe('usage-response', (action) => { - const { usage, limit } = action - console.log(`Usage: ${usage} / ${limit} credits`) - this.showUsageWarning(usage, limit) + const { usage, limit, referralLink } = action + console.log(`\nUsage: ${usage} / ${limit} credits`) + this.showUsageWarning(usage, limit, referralLink) this.returnControlToUser() }) } - async showUsageWarning(usage: number, limit: number) { + public async showUsageWarning( + usage: number, + limit: number, + referralLink?: string + ) { const pct: number = match(Math.floor((usage / limit) * 100)) .with(P.number.gte(100), () => 100) .with(P.number.gte(75), () => 75) @@ -226,14 +273,33 @@ export class Client { .with(P.number.gte(25), () => 25) .otherwise(() => 0) + if (pct >= 100) { + console.error( + [ + red( + 'You have reached your monthly usage limit. You must upgrade your plan to continue using the service.' + ), + ].join('\n') + ) + this.returnControlToUser() + return + } + if (pct > 0 && pct > this.lastWarnedPct) { console.warn( [ '', yellow(`You have used over ${pct}% of your monthly usage limit.`), this.user - ? yellow('Visit https://manicode.ai/pricing to upgrade.') + ? yellow( + `Visit ${process.env.NEXT_PUBLIC_APP_URL}/pricing to upgrade.` + ) : yellow('Type "login" to sign up and get more credits!'), + referralLink + ? yellow( + `You can also refer friends using this link and get more credits: ${referralLink}` + ) + : '', ].join('\n') ) this.lastWarnedPct = pct @@ -349,8 +415,14 @@ export class Client { resolveResponse({ ...a, wasStoppedByUser: false }) this.currentUserInputId = undefined - this.usage = a.usage ?? 0 - this.limit = a.limit ?? 0 + if (!a.usage || !a.limit) return + + this.usage = a.usage + if (this.limit !== a.limit) { + // Indicates a change in the user's plan + this.lastWarnedPct = 0 + this.limit = a.limit + } }) return { diff --git a/npm-app/src/menu.ts b/npm-app/src/menu.ts index efcba50126..7f6ac0e7de 100644 --- a/npm-app/src/menu.ts +++ b/npm-app/src/menu.ts @@ -1,5 +1,5 @@ import { getProjectRoot } from './project-files' -import picocolors from 'picocolors' +import picocolors, { blue } from 'picocolors' import { bold, green } from 'picocolors' const getRandomColors = () => { @@ -69,14 +69,24 @@ ${colorizeRandom('╚═╝ ╚═╝')}${colorizeRandom('╚═╝ ╚═ console.log('- Enter terminal commands directly: "cd backend", "npm test"') console.log('- Use "/run " for long terminal commands') console.log('- Press ESC to cancel generation') - console.log('- Type "undo" or "redo" (abbreviated "u" or "r") to undo or redo the last change') + console.log( + '- Type "undo" or "redo" (abbreviated "u" or "r") to undo or redo the last change' + ) console.log('- Type "login" to log into Manicode') - console.log('- Type "diff" or "d" to show changes from the last assistant response') + console.log( + '- Type "diff" or "d" to show changes from the last assistant response' + ) + console.log( + `- Redeem a referral code by simply pasting it here. You can also earn credits if you`, + bold(green(`refer new users: ${process.env.NEXT_PUBLIC_APP_URL}/referrals`)) + ) console.log( '\nAny files in .gitignore are not read by Manicode. You can ignore further files with .manicodeignore' ) console.log( - '\nEmail your feedback to james@manicode.ai. Thanks for using Manicode!' + '\nEmail your feedback to', + bold(blue('founders@manicode.ai.')), + 'Thanks for using Manicode!' ) } diff --git a/package.json b/package.json index 9807ceee7c..8de20f6d1f 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "test:patch": "bun test test/__src__/patch.test.ts" }, "dependencies": { + "@tanstack/react-query": "^5.59.0", "lodash": "4.17.21", "ts-node": "^10.9.2" }, diff --git a/web/.github/workflows/playwright.yml b/web/.github/workflows/playwright.yml index e6cabd65fb..57d1ab9759 100644 --- a/web/.github/workflows/playwright.yml +++ b/web/.github/workflows/playwright.yml @@ -13,7 +13,7 @@ jobs: timeout-minutes: 60 runs-on: ubuntu-latest env: - APP_URL: ${{ secrets.APP_URL }} + NEXT_PUBLIC_APP_URL: ${{ secrets.NEXT_PUBLIC_APP_URL }} GITHUB_ID: ${{ secrets.AUTH_GITHUB_ID }} GITHUB_SECRET: ${{ secrets.AUTH_GITHUB_SECRET }} DATABASE_URL: ${{ secrets.DATABASE_URL }} diff --git a/web/knowledge.md b/web/knowledge.md new file mode 100644 index 0000000000..edae2e5f15 --- /dev/null +++ b/web/knowledge.md @@ -0,0 +1,117 @@ +# Manicode Web Application Knowledge + +## Authentication and Login System + +The authentication system in Manicode's web application plays a crucial role in integrating with the npm app (CLI) to provide a seamless login experience. Here's what the web app needs to focus on: + +### Web App's Role in Authentication + +1. **Auth Code Validation**: + + - The login page (`web/src/app/login/page.tsx`) receives and validates the auth code from the URL. + - It checks for token expiration and handles invalid or expired codes. + +2. **OAuth Flow**: + + - Implements OAuth authentication (currently GitHub) using NextAuth.js. + - Configured in `web/src/app/api/auth/[...nextauth]/auth-options.ts`. + +3. **User Onboarding**: + + - After successful OAuth, the onboarding page (`web/src/app/onboard/page.tsx`) processes the auth code. + - It creates a new session, linking the `fingerprintId` with the user's account. + +4. **Referral Processing**: + + - During onboarding, it handles any referral codes, applying bonuses if valid. + +5. **Session Management**: + - Establishes a session for the authenticated user. + - Provides necessary user data for the npm app to retrieve via WebSocket. + +### Interaction with Other Components + +- **npm app**: Initiates the process by generating a `fingerprintId` and opening the login URL. +- **Backend**: Handles WebSocket communications and session verification. + +### Key Security Considerations + +- Validate auth codes thoroughly to prevent unauthorized access. +- Use secure, HTTP-only cookies for session management. +- Implement proper CSRF protection for all authenticated routes. + +## Referral System + +The referral system is a key feature of the Manicode web application. It allows users to refer others and earn credits for successful referrals. + +### High-Level Workflow + +1. **Referral Code Generation**: + + - Each user is assigned a unique referral code upon account creation. + - Referral codes are stored in the `user` table of the database. + +2. **Sharing Referrals**: + + - Users can share their referral code or a referral link. + - Referral link format: `${env.NEXT_PUBLIC_APP_URL}/redeem?referral_code=${referralCode}` + +3. **Redeeming Referrals**: + + - New users can enter a referral code during signup or on the referrals page. + - The system validates the referral code and creates a referral record. + +4. **Credit Distribution**: + + - Both the referrer and the referred user receive bonus credits. + - Credit amount is defined by `CREDITS_REFERRAL_BONUS` in constants. + +5. **Referral Tracking**: + + - Referrals are tracked in the `referral` table, linking referrer and referred users. + - The referrals page displays a user's referral history and earned credits. + +6. **Quota Management**: + - Referral credits are added to the user's quota. + - When users upgrade or downgrade their subscription, referral credits are preserved. + +### Key Components + +- `web/src/app/referrals/page.tsx`: Main referrals UI +- `web/src/app/api/referrals/route.ts`: API route for referral operations +- `web/src/app/api/stripe/webhook/route.ts`: Handles subscription changes, preserving referral credits +- `common/src/db/schema.ts`: Database schema including user and referral tables + +### Important Considerations + +- Referral codes are unique per user. +- Referral links redirect unauthenticated users to the login page before processing. +- The system prevents users from referring themselves. +- There's a limit on the number of times a referral code can be used. +- As of the latest update, referral codes can only be submitted through the Manicode CLI app, not through the website. + +### CLI-based Referral Code Submission + +To streamline the referral process and integrate it with the CLI tool: + +1. The web interface no longer accepts referral code inputs. +2. Users are directed to use the Manicode CLI app for submitting referral codes. +3. The referrals page should include instructions for installing the CLI tool and using referral codes: + - Install command: `npm i -g manicode` + - Usage: Users should paste their referral code in the CLI after installation. +4. Format CLI commands in a code-like pattern on the web interface for clarity. + +This change ensures a consistent user experience across the Manicode ecosystem and encourages CLI adoption. + +## Environment Configuration + +The application uses environment variables for configuration, which are managed through the `web/src/env.mjs` file. This setup ensures type-safe access to environment variables and proper validation. + +Key points: + +- Uses `@t3-oss/env-nextjs` for creating a type-safe environment configuration. +- Loads environment variables from different `.env` files based on the current environment. +- Defines separate server-side and client-side environment variables. +- Includes critical configuration like database URL, authentication secrets, and Stripe API keys. + +Remember to keep this knowledge file updated as the application evolves or new features are added. diff --git a/web/package.json b/web/package.json index 05c092a83d..8b8cfc1fde 100644 --- a/web/package.json +++ b/web/package.json @@ -22,6 +22,7 @@ "@hookform/resolvers": "^3.9.0", "@radix-ui/react-dropdown-menu": "^2.1.1", "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-separator": "^1.1.0", "@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-toast": "^1.2.1", "@react-three/drei": "^9.112.0", diff --git a/web/src/app/api/referrals/[code]/route.ts b/web/src/app/api/referrals/[code]/route.ts new file mode 100644 index 0000000000..3d2d8cf568 --- /dev/null +++ b/web/src/app/api/referrals/[code]/route.ts @@ -0,0 +1,45 @@ +import db from 'common/db' +import { eq } from 'drizzle-orm' +import { NextResponse } from 'next/server' +import * as schema from 'common/db/schema' +import { getServerSession } from 'next-auth' +import { authOptions } from '../../auth/[...nextauth]/auth-options' + +export async function GET( + _req: Request, + { params }: { params: { code: string } } +) { + const { code } = params + const session = await getServerSession(authOptions) + + if (!session || !session.user || !session.user.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + try { + const user = await db.query.user.findFirst({ + where: eq(schema.user.referral_code, code), + columns: { + name: true, + id: true, + }, + }) + + if (!user) { + return NextResponse.json( + { error: 'Invalid referral code' }, + { status: 400 } + ) + } + + const isSameUser = user.id === session.user.id + + return NextResponse.json({ referrerName: user.name, isSameUser }) + } catch (error) { + console.error(error) + return NextResponse.json( + { error: 'Internal Server Error' }, + { status: 500 } + ) + } +} diff --git a/web/src/app/api/referrals/route.ts b/web/src/app/api/referrals/route.ts new file mode 100644 index 0000000000..a5ee8261fe --- /dev/null +++ b/web/src/app/api/referrals/route.ts @@ -0,0 +1,219 @@ +import { NextResponse } from 'next/server' +import { getServerSession } from 'next-auth' +import { eq, sql, or } from 'drizzle-orm' +import { z } from 'zod' +import { authOptions } from '../auth/[...nextauth]/auth-options' +import db from 'common/db' +import * as schema from 'common/db/schema' +import { CREDITS_REFERRAL_BONUS, MAX_REFERRALS } from 'common/constants' +import { hasMaxedReferrals } from 'common/util/server/referral' + +type Referral = Pick & + Pick +const ReferralSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string().email(), + credits: z.coerce.number(), +}) + +export type ReferralData = { + referralCode: string + referrals: Referral[] + referredBy?: Referral + limitReached: boolean +} + +export async function GET() { + const session = await getServerSession(authOptions) + + if (!session || !session.user || !session.user.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + try { + const user = await db.query.user.findFirst({ + where: eq(schema.user.id, session.user.id), + }) + + const referralCode = user?.referral_code + if (!referralCode) { + throw new Error( + `No referral code found for user with id ${session.user.id}` + ) + } + + // Who did this user refer? + const referralsQuery = db + .select({ + id: schema.referral.referred_id, + credits: schema.referral.credits, + // credits: sql`SUM(${schema.referral.credits})`.as('credits'), + }) + .from(schema.referral) + .where(eq(schema.referral.referrer_id, session.user.id)) + // .groupBy(schema.referral.referred_id) + .as('referralsQuery') + const referrals = await db + .select({ + id: schema.user.id, + name: schema.user.name, + email: schema.user.email, + credits: referralsQuery.credits, + }) + .from(referralsQuery) + .leftJoin(schema.user, eq(schema.user.id, referralsQuery.id)) + + // Who referred this user? + const referredByIdQuery = db + .select({ + id: schema.referral.referrer_id, + credits: schema.referral.credits, + // credits: sql`SUM(${schema.referral.credits})`.as('credits'), + }) + .from(schema.referral) + .where(eq(schema.referral.referred_id, session.user.id)) + // .groupBy(schema.referral.referrer_id) + .limit(1) + .as('referredByIdQuery') + const referredBy = await db + .select({ + id: schema.user.id, + name: schema.user.name, + email: schema.user.email, + credits: referredByIdQuery.credits, + }) + .from(referredByIdQuery) + .leftJoin(schema.user, eq(schema.user.id, referredByIdQuery.id)) + .limit(1) + .then((users) => { + if (users.length !== 1) { + return + } + return ReferralSchema.parse(users[0]) + }) + + const referralData: ReferralData = { + referralCode, + referrals: referrals.reduce((acc, referral) => { + const result = ReferralSchema.safeParse(referral) + if (result.success) { + acc.push(result.data) + } + return acc + }, [] as Referral[]), + referredBy, + limitReached: referrals.length >= MAX_REFERRALS, + } + + return NextResponse.json(referralData) + } catch (error) { + console.error('Error fetching referral data:', error) + return NextResponse.json( + { error: 'Internal Server Error' }, + { status: 500 } + ) + } +} + +export async function POST(request: Request) { + const session = await getServerSession(authOptions) + const userId = session?.user?.id + if (!session || !userId) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const { referralCode } = await request.json() + try { + // Check if the user has already used a referral code + const existingReferral = await db + .select() + .from(schema.referral) + .where(eq(schema.referral.referred_id, userId)) + .limit(1) + + if (existingReferral.length > 0) { + return NextResponse.json( + { error: 'You have already used a referral code' }, + { status: 429 } + ) + } + + // Check if the user is trying to use their own referral code + const currentUser = await db + .select({ referral_code: schema.user.referral_code }) + .from(schema.user) + .where(eq(schema.user.id, userId)) + .limit(1) + + if (currentUser[0]?.referral_code === referralCode) { + return NextResponse.json( + { + error: "Nice try bud, you can't use your own referral code", + }, + { + status: 400, + } + ) + } + + // Find the referrer user + const referrers = await db + .select() + .from(schema.user) + .where(eq(schema.user.referral_code, referralCode)) + .limit(1) + + if (referrers.length !== 1) { + return NextResponse.json( + { error: 'Invalid referral code' }, + { status: 400 } + ) + } + const referrer = referrers[0] + + // Check if the referrer has maxed out their referrals + const referralStatus = await hasMaxedReferrals(referrer.id) + if (referralStatus.reason) { + return NextResponse.json( + { error: referralStatus.reason }, + { status: 400 } + ) + } + + await db.transaction(async (tx) => { + // Create the referral + await tx.insert(schema.referral).values({ + referrer_id: referrer.id, + referred_id: userId, + status: 'completed', + credits: CREDITS_REFERRAL_BONUS, + created_at: new Date(), + completed_at: new Date(), + }) + + // Update both users' quota + await tx + .update(schema.user) + .set({ + quota: sql`${schema.user.quota} + ${CREDITS_REFERRAL_BONUS}`, + }) + .where(or(eq(schema.user.id, referrer.id), eq(schema.user.id, userId))) + }) + + return NextResponse.json( + { + credits_redeemed: CREDITS_REFERRAL_BONUS, + }, + { + status: 200, + } + ) + } catch (error) { + console.error('Error applying referral code:', error) + return NextResponse.json( + { error: 'Internal Server Error' }, + { status: 500 } + ) + } +} diff --git a/web/src/app/api/stripe/checkout-session/route.ts b/web/src/app/api/stripe/checkout-session/route.ts index d99b4850fb..e69d881376 100644 --- a/web/src/app/api/stripe/checkout-session/route.ts +++ b/web/src/app/api/stripe/checkout-session/route.ts @@ -29,8 +29,8 @@ export const GET = async () => { quantity: 1, }, ], - success_url: `${env.APP_URL}?session_id={CHECKOUT_SESSION_ID}`, - cancel_url: env.APP_URL, + success_url: `${env.NEXT_PUBLIC_APP_URL}?session_id={CHECKOUT_SESSION_ID}`, + cancel_url: env.NEXT_PUBLIC_APP_URL, }) return NextResponse.json({ session: checkoutSession }, { status: 200 }) diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.ts index 441a63fbb4..c8decd70e1 100644 --- a/web/src/app/api/stripe/webhook/route.ts +++ b/web/src/app/api/stripe/webhook/route.ts @@ -1,6 +1,6 @@ import { NextRequest, NextResponse } from 'next/server' import Stripe from 'stripe' -import { eq } from 'drizzle-orm' +import { eq, or, sum } from 'drizzle-orm' import { env } from '@/env.mjs' import { stripeServer } from 'common/src/util/stripe' @@ -26,7 +26,7 @@ const getCustomerId = ( .exhaustive() } -const webhookHandler = async (req: NextRequest) => { +const webhookHandler = async (req: NextRequest): Promise => { try { const buf = await req.text() const sig = req.headers.get('stripe-signature')! @@ -77,7 +77,7 @@ const webhookHandler = async (req: NextRequest) => { }, }, { status: 405 } - ).headers.set('Allow', 'POST') + ) } } @@ -86,13 +86,39 @@ async function handleSubscriptionChange( usageTier: keyof typeof CREDITS_USAGE_LIMITS ) { const customerId = getCustomerId(subscription.customer) + + // Fetch the user's current quota and referral credits + const userCredits = await db + .select({ + referralCredits: sum(schema.referral.credits), + }) + .from(schema.user) + .leftJoin( + schema.referral, + or( + eq(schema.referral.referrer_id, schema.user.id), + eq(schema.referral.referred_id, schema.user.id) + ) + ) + .where(eq(schema.user.stripe_customer_id, customerId)) + .limit(1) + .then((rows) => { + if (rows.length < 1) { + return + } + return rows[0] + }) + + const baseQuota = CREDITS_USAGE_LIMITS[usageTier] + const newQuota = baseQuota + parseInt(userCredits?.referralCredits ?? '0') + + // TODO: If downgrading, check Stripe to see if they have exceeded quota, don't just blindly reset. But for now it's fine to just trust them. + // A good indicator that we've created compelling value is if people are subscribing and unsubscribing just to get some more free usage await db .update(schema.user) .set({ - // TODO: If downgrading, check Stripe to see if they have exceeded quota, don't just blindly reset. But for now it's fine to just trust them. - // A good indicator that we've created compelling value is if people are subscribing and unsubscribing just to get some more free usage quota_exceeded: false, - quota: CREDITS_USAGE_LIMITS[usageTier], + quota: newQuota, subscription_active: usageTier === 'PAID', stripe_price_id: subscription.id, }) diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx index 5777ece7fe..2d8a942900 100644 --- a/web/src/app/layout.tsx +++ b/web/src/app/layout.tsx @@ -11,6 +11,7 @@ import { siteConfig } from '@/lib/constant' import { fonts } from '@/lib/fonts' import { cn } from '@/lib/utils' import SessionProvider from '@/lib/SessionProvider' +import QueryProvider from '@/components/providers/query-client-provider' export const generateMetadata = (): Metadata => ({ metadataBase: new URL(siteConfig.url()), @@ -57,10 +58,12 @@ const RootLayout = ({ children }: PropsWithChildren) => { > - -
{children}
-