Skip to content

[Refactor] Backend Re-architecture - #598

Merged
Fermionic-Lyu merged 15 commits into
mainfrom
refactor-backend
Nov 19, 2025
Merged

Fermionic-Lyu merged 15 commits into
mainfrom
refactor-backend

Conversation

@Fermionic-Lyu

@Fermionic-Lyu Fermionic-Lyu commented Nov 18, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR refactors the backend service into a more maintainable, open-source friendly architecture that follows the best industrial practices.

The backend directory now follows this structure:

backend/src/
├── api/              # HTTP layer (routes + middlewares)
├── services/         # Business logic
├── providers/        # External integrations (OAuth, email, storage, AI, logs)
├── infra/            # Infrastructure (database, socket, config, security)
├── types/            # TypeScript type definitions
└── utils/            # Utility functions

with routes/services file names normalized to keep consistency. Providers are for external services and it is now very extendable.

Also removed deprecated openapi and agent doc files.

How did you test this change?

Tested locally

Summary by CodeRabbit

  • New Features

    • AI Integration: chat completions and image generation.
    • Provider-based services: email, OAuth providers, and pluggable storage (S3 + local).
  • Refactor

    • Backend reorganized with clearer service/provider layering.
    • Consolidated database API under a unified endpoint.
    • Removed auto-generated documentation endpoints.
  • Chores

    • Updated README with expanded architecture and diagram.
    • Bumped version to 1.2.2 and adjusted migration scripts.
  • Bug Fixes

    • Fixed minor configuration/variable naming issue.

@coderabbitai

coderabbitai Bot commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Reorganizes backend module paths (core → services/infra), introduces provider interfaces (OAuth, Email, Storage), renames AI services, adds S3/Local storage providers and EmailService, removes OpenAPI/agent-doc generators and routes, consolidates database routes, updates many import paths, and bumps version to 1.2.2.

Changes

Cohort / File(s) Change Summary
Project metadata
CHANGELOG.md, package.json
Added changelog entry for v1.2.2 and bumped package version to 1.2.2.
README / docs
README.md
Added "AI Integration" feature, updated Quickstart prompt, replaced architecture section with expanded narrative and Mermaid diagram.
Migration scripts
backend/package.json
Migration npm scripts updated to pass explicit --migrations-dir src/infra/database/migrations and maintain --migrations-table _migrations.
Server / routing
backend/src/server.ts, backend/src/api/routes/database/index.routes.ts
Consolidated database routing under /api/database; server now mounts updated route index files and removes OpenAPI/agent-doc endpoints.
Route deletions
backend/src/api/routes/agent.ts, backend/src/api/routes/openapi.ts
Removed agent-docs and OpenAPI route modules and their exported routers.
Route import updates
backend/src/api/routes/* (auth, ai, database/*, functions, logs, metadata, secrets, storage, usage, ...)
Widespread import path updates (core → services/infra, api/middleware → api/middlewares), and AI route imports updated to ChatCompletionService / ImageGenerationService.
Middlewares
backend/src/api/middlewares/*.ts
Updated import specifiers to new paths and explicit .js extensions (error, auth, rate-limiters, upload, etc.).
Core documentation removed
backend/src/core/documentation/agent.ts, backend/src/core/documentation/openapi.ts
Deleted AgentAPIDocService and OpenAPIService singletons and generation logic.
Email provider & service
backend/src/providers/email/base.provider.ts, backend/src/providers/email/cloud.provider.ts, backend/src/services/email/email.service.ts, backend/src/types/email.ts, backend/src/core/email/index.ts
Added EmailProvider interface; replaced prior EmailService with CloudEmailProvider provider implementation; introduced new EmailService singleton that delegates to provider; added EmailTemplate type; removed old core re-export.
OAuth provider refactor
backend/src/providers/oauth/*.provider.ts, backend/src/providers/oauth/index.ts, backend/src/services/auth/*
Introduced OAuthProvider interface; renamed per-provider classes to *Provider (Google/GitHub/Discord/LinkedIn/Facebook/Microsoft/X), updated singletons and AuthService to use provider singletons; added centralized re-exports.
Storage provider additions
backend/src/providers/storage/base.provider.ts, backend/src/providers/storage/local.provider.ts, backend/src/providers/storage/s3.provider.ts
Added StorageProvider interface plus LocalStorageProvider and S3StorageProvider implementations (CRUD, bucket ops, presigned upload/download, CloudFront support).
StorageService refactor
backend/src/services/storage/storage.service.ts
Switched from backend backends to provider-based architecture (StorageProvider); StorageService initializes providers; changed getUploadStrategy/getDownloadStrategy signatures.
AI services rename & re-exports
backend/src/services/ai/*, backend/src/services/ai/index.ts
Renamed ChatService → ChatCompletionService and ImageService → ImageGenerationService; updated imports and added ai service re-exports and helper re-exports.
Auth & related services path updates
backend/src/services/auth/*, backend/src/services/*
Numerous import path relocations (core → infra/services), OTP/config/service re-exports added, AuthService wired to provider classes; other services updated to new infra paths.
Socket / infra imports
backend/src/infra/socket/socket.ts, backend/src/infra/*
Updated socket imports to use @/services/@/types and new middleware error path.
Misc: import path normalization
backend/src/**/* (many)
Many files updated for path normalization (explicit .js extensions) and renames (core → infra/services); small variable/name fixes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Areas to focus review on:

  • backend/src/providers/storage/s3.provider.ts — presigned URL/POST generation, CloudFront signing, key namespacing, pagination/deletion logic.
  • backend/src/services/storage/storage.service.ts — provider selection, signature changes, and compatibility with existing callers.
  • backend/src/services/email/email.service.ts & backend/src/providers/email/cloud.provider.ts — delegation, template handling, and sendRaw fallback behavior.
  • backend/src/services/auth/auth.service.ts and oauth providers — provider singleton wiring and generateOAuthUrl rename impacts.
  • Removal of OpenAPI/agent doc modules and route mounts — ensure no remaining references to deleted singletons/routes.

Possibly related PRs

Suggested reviewers

  • tonychang04
  • Leo-rq-yu

Poem

🐇 I hopped through code with nimble paws,

Split providers, moved the old core laws,
Emails now send from cloud and land,
Storage stretched across S3 and sand,
A tidy hop — commits well-planned! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[Refactor] Backend Re-architecture' directly and clearly summarizes the main change in the PR, which is a comprehensive backend refactoring with reorganized directory structure.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-backend

Comment @coderabbitai help to get the list of available commands and usage tips.

@Fermionic-Lyu
Fermionic-Lyu marked this pull request as ready for review November 18, 2025 23:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
backend/src/services/logs/audit.service.ts (1)

169-224: Fix incorrect use of .get() result in getStats

this.db.prepare(...).get(...) is treated elsewhere as returning a single row object, but here it’s array-destructured. That will break at runtime and make /logs/audits/stats unusable.

Consider updating getStats like this:

-      const [totalLogs] = await this.db
-        .prepare('SELECT COUNT(*) as count FROM _audit_logs WHERE created_at >= $1')
-        .get(startDate.toISOString());
-
-      const [uniqueActors] = await this.db
-        .prepare('SELECT COUNT(DISTINCT actor) as count FROM _audit_logs WHERE created_at >= $1')
-        .get(startDate.toISOString());
-
-      const [uniqueModules] = await this.db
-        .prepare('SELECT COUNT(DISTINCT module) as count FROM _audit_logs WHERE created_at >= $1')
-        .get(startDate.toISOString());
+      const totalLogsRow = await this.db
+        .prepare('SELECT COUNT(*) as count FROM _audit_logs WHERE created_at >= $1')
+        .get(startDate.toISOString());
+
+      const uniqueActorsRow = await this.db
+        .prepare('SELECT COUNT(DISTINCT actor) as count FROM _audit_logs WHERE created_at >= $1')
+        .get(startDate.toISOString());
+
+      const uniqueModulesRow = await this.db
+        .prepare('SELECT COUNT(DISTINCT module) as count FROM _audit_logs WHERE created_at >= $1')
+        .get(startDate.toISOString());
@@
-      return {
-        totalLogs: parseInt(totalLogs?.count || 0),
-        uniqueActors: parseInt(uniqueActors?.count || 0),
-        uniqueModules: parseInt(uniqueModules?.count || 0),
+      return {
+        totalLogs: parseInt(totalLogsRow?.count ?? 0, 10),
+        uniqueActors: parseInt(uniqueActorsRow?.count ?? 0, 10),
+        uniqueModules: parseInt(uniqueModulesRow?.count ?? 0, 10),

This matches how .get() is used elsewhere and avoids the runtime error.

backend/src/services/secrets/secret.service.ts (1)

163-199: Guard against empty updates in updateSecret

If UpdateSecretInput has no fields set, updates stays empty and the generated SQL becomes UPDATE _secrets SET WHERE id = $1, which is invalid.

A simple guard avoids this edge-case failure:

   async updateSecret(id: string, input: UpdateSecretInput): Promise<boolean> {
@@
       if (input.expiresAt !== undefined) {
         updates.push(`expires_at = $${paramCount++}`);
         values.push(input.expiresAt);
       }
 
-      values.push(id);
-
-      const result = await client.query(
-        `UPDATE _secrets
-         SET ${updates.join(', ')}
-         WHERE id = $${paramCount}`,
-        values
-      );
+      if (updates.length === 0) {
+        // Nothing to update; treat as no-op
+        logger.warn('updateSecret called with no updatable fields', { id });
+        return false;
+      }
+
+      values.push(id);
+
+      const result = await client.query(
+        `UPDATE _secrets
+         SET ${updates.join(', ')}
+         WHERE id = $${paramCount}`,
+        values
+      );

This keeps the API safe if callers accidentally pass an empty payload.

backend/src/api/routes/metadata/index.routes.ts (1)

110-110: Fix variable name typo.

The variable name sercretService is misspelled. It should be secretService.

Apply this diff:

-    const sercretService = new SecretService();
+    const secretService = new SecretService();

Also update line 111:

-    const apiKey = await sercretService.getSecretByKey('API_KEY');
+    const apiKey = await secretService.getSecretByKey('API_KEY');
backend/src/providers/oauth/x.provider.ts (1)

28-47: Clarify the state parameter contract for generateOAuthUrl

The method signature and interface treat state as optional (state?: string), but the implementation throws if state is falsy. This creates a gap between the type-level contract and runtime behavior: callers are allowed by TypeScript to omit state, but will hit a runtime error.

Consider either:

  • Making state required in both the interface and this implementation, or
  • Allowing state to be omitted and handling that case gracefully here (e.g., by generating or defaulting a value, if that fits your overall OAuth design).

This will prevent surprising runtime failures and better align the types with actual behavior.

🧹 Nitpick comments (8)
backend/src/providers/email/base.provider.ts (1)

1-41: EmailProvider interface is well-structured for extensible providers

The interface cleanly separates template-based sending, optional raw sending, and capability discovery via supportsTemplates(), and it aligns with the EmailTemplate union.

If you expect providers to pass non-string data into templates (e.g., numbers or booleans), you might consider widening variables to something like Record<string, string | number> or Record<string, unknown>, but the current stricter typing is perfectly acceptable if templates always work with strings.

backend/src/services/email/email.service.ts (1)

13-27: Consider initializing providers and using domain-specific errors for sendRaw

The service correctly delegates to the underlying EmailProvider, but there are two improvements worth considering:

  1. Provider initialization
    Since EmailProvider exposes an optional initialize() hook, you may want to invoke it in the constructor (or lazily on first use) when present, e.g.:

    if (this.provider.initialize) {
      void this.provider.initialize();
    }

    This keeps provider setup consistently encapsulated in the service.

  2. Error type for unsupported sendRaw
    sendRaw currently throws a plain Error when the provider does not support raw sending. To keep error handling consistent with the rest of the backend (which appears to rely on structured errors like AppError), consider throwing a domain-specific error instead, so HTTP status codes and error codes can be handled uniformly.

These are not blockers but would make the service more robust and consistent.

Also applies to: 62-67

backend/src/providers/email/cloud.provider.ts (1)

47-52: EmailProvider implementation looks solid; consider centralizing template list

CloudEmailProvider cleanly implements EmailProvider (including supportsTemplates) and has good validation and error mapping for the cloud API. The only maintainability concern is the hard‑coded validTemplates list: it must stay in sync with the EmailTemplate union and any backend‑side templates. Consider moving the allowed template list into a shared module (or exporting it alongside EmailTemplate) so both the provider and any future callers derive from a single source of truth.

Also applies to: 62-186

backend/src/services/storage/storage.service.ts (1)

388-412: Upload strategy + confirm flow is clean, but consider orphaned-object handling

The provider-based getUploadStrategy/confirmUpload flow is nicely structured and keeps StorageService independent from specific backends. One behavioral edge case to be aware of: if two clients concurrently request an upload strategy for the same filename, both can receive different keys, upload successfully, but the second confirmUpload will fail because the DB record already exists, leaving the second object orphaned in S3/local storage.

If this matters for your use case, consider:

  • Including a client-generated upload ID or nonce in the key, or
  • Having confirmUpload optionally adopt/rename the second object instead of hard‑failing, or
  • Adding a periodic cleanup routine that removes objects not present in _storage.

Otherwise, the refactor and delegation to StorageProvider look good.

Also applies to: 424-487

backend/src/providers/storage/local.provider.ts (1)

50-56: Use fs.rm instead of deprecated fs.rmdir for recursive deletes

deleteBucket correctly treats missing directories as non-fatal, but fs.rmdir(path, { recursive: true }) is deprecated in recent Node versions. To avoid deprecation warnings and future breakage, consider switching to:

await fs.rm(path.join(this.baseDir, bucket), { recursive: true, force: true });

This preserves the current “ignore if missing” behavior via force: true.

backend/src/providers/storage/s3.provider.ts (1)

82-102: Clarify getObject error semantics (missing vs. other S3 errors)

getObject currently returns null for any error (including permission or transient S3 issues), which is fine if callers treat null strictly as “not available” and don’t need to differentiate missing vs. other failures. If you ever need finer-grained behavior (or better user messaging), consider logging and rethrowing non‑404/NoSuchKey errors while only mapping genuine “not found” cases to null.

backend/src/services/auth/auth.service.ts (2)

65-71: Align naming with provider-based OAuth layer (optional)

You’ve correctly switched the types/initialization to *OAuthProvider.getInstance(), but the fields and comment still refer to “OAuth service”:

  • private googleOAuthService: GoogleOAuthProvider; etc.
  • Comment: // OAuth service instances (cached singletons)

To reduce confusion as more services/providers accumulate, consider renaming these to *OAuthProvider and updating the comment, e.g.:

-  // OAuth service instances (cached singletons)
-  private googleOAuthService: GoogleOAuthProvider;
+  // OAuth provider instances (cached singletons)
+  private googleOAuthProvider: GoogleOAuthProvider;

(and adjust call sites accordingly).

Also applies to: 102-108


900-918: Contract mismatch confirmed; however, current call site always provides state

Verification confirms the X provider enforces state (throws if missing), but oauth.routes.ts always generates and passes a JWT-based state token. The inconsistency exists—X requires state while the method signature suggests it's optional—but the current code path avoids the runtime error.

Since the oauth.routes.ts caller always supplies state and no other call sites were found, this is a design clarity issue rather than an active defect. Refactoring to align the contract (either enforce state for all providers or handle X specially) would prevent future surprises.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d72602 and af7f043.

⛔ Files ignored due to path filters (3)
  • assets/mcpInstallv2.png is excluded by !**/*.png
  • assets/sampleResponse.png is excluded by !**/*.png
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (64)
  • CHANGELOG.md (1 hunks)
  • README.md (3 hunks)
  • backend/package.json (1 hunks)
  • backend/src/api/middlewares/auth.ts (1 hunks)
  • backend/src/api/routes/agent.ts (0 hunks)
  • backend/src/api/routes/ai/index.routes.ts (3 hunks)
  • backend/src/api/routes/auth/index.routes.ts (2 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (1 hunks)
  • backend/src/api/routes/database/advance.routes.ts (1 hunks)
  • backend/src/api/routes/database/index.routes.ts (1 hunks)
  • backend/src/api/routes/database/records.routes.ts (1 hunks)
  • backend/src/api/routes/database/tables.routes.ts (1 hunks)
  • backend/src/api/routes/functions/index.routes.ts (1 hunks)
  • backend/src/api/routes/logs/index.routes.ts (1 hunks)
  • backend/src/api/routes/metadata/index.routes.ts (1 hunks)
  • backend/src/api/routes/openapi.ts (0 hunks)
  • backend/src/api/routes/secrets/index.routes.ts (1 hunks)
  • backend/src/api/routes/storage/index.routes.ts (1 hunks)
  • backend/src/api/routes/usage/index.routes.ts (1 hunks)
  • backend/src/core/documentation/agent.ts (0 hunks)
  • backend/src/core/documentation/openapi.ts (0 hunks)
  • backend/src/core/email/index.ts (0 hunks)
  • backend/src/infra/socket/socket.ts (2 hunks)
  • backend/src/providers/ai/openrouter.provider.ts (1 hunks)
  • backend/src/providers/email/base.provider.ts (1 hunks)
  • backend/src/providers/email/cloud.provider.ts (3 hunks)
  • backend/src/providers/logs/cloudwatch.provider.ts (1 hunks)
  • backend/src/providers/oauth/base.provider.ts (1 hunks)
  • backend/src/providers/oauth/discord.provider.ts (1 hunks)
  • backend/src/providers/oauth/facebook.provider.ts (1 hunks)
  • backend/src/providers/oauth/github.provider.ts (1 hunks)
  • backend/src/providers/oauth/google.provider.ts (2 hunks)
  • backend/src/providers/oauth/index.ts (1 hunks)
  • backend/src/providers/oauth/linkedin.provider.ts (2 hunks)
  • backend/src/providers/oauth/microsoft.provider.ts (1 hunks)
  • backend/src/providers/oauth/x.provider.ts (1 hunks)
  • backend/src/providers/storage/base.provider.ts (1 hunks)
  • backend/src/providers/storage/local.provider.ts (1 hunks)
  • backend/src/providers/storage/s3.provider.ts (1 hunks)
  • backend/src/server.ts (2 hunks)
  • backend/src/services/ai/ai-config.service.ts (1 hunks)
  • backend/src/services/ai/ai-model.service.ts (1 hunks)
  • backend/src/services/ai/ai-usage.service.ts (1 hunks)
  • backend/src/services/ai/chat-completion.service.ts (2 hunks)
  • backend/src/services/ai/image-generation.service.ts (5 hunks)
  • backend/src/services/ai/index.ts (1 hunks)
  • backend/src/services/auth/auth-config.service.ts (1 hunks)
  • backend/src/services/auth/auth-otp.service.ts (1 hunks)
  • backend/src/services/auth/auth.service.ts (6 hunks)
  • backend/src/services/auth/index.ts (1 hunks)
  • backend/src/services/auth/oauth-config.service.ts (1 hunks)
  • backend/src/services/database/database-advance.service.ts (1 hunks)
  • backend/src/services/database/database-table.service.ts (1 hunks)
  • backend/src/services/email/email.service.ts (1 hunks)
  • backend/src/services/functions/function.service.ts (2 hunks)
  • backend/src/services/logs/audit.service.ts (1 hunks)
  • backend/src/services/logs/log.service.ts (1 hunks)
  • backend/src/services/secrets/secret.service.ts (1 hunks)
  • backend/src/services/storage/storage.service.ts (3 hunks)
  • backend/src/types/email.ts (1 hunks)
  • backend/src/utils/cloud-token.ts (1 hunks)
  • backend/src/utils/seed.ts (1 hunks)
  • backend/src/utils/validations.ts (1 hunks)
  • package.json (1 hunks)
💤 Files with no reviewable changes (5)
  • backend/src/core/email/index.ts
  • backend/src/core/documentation/openapi.ts
  • backend/src/api/routes/openapi.ts
  • backend/src/core/documentation/agent.ts
  • backend/src/api/routes/agent.ts
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-11-14T18:47:06.676Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 585
File: frontend/src/features/database/page/FunctionsPage.tsx:57-83
Timestamp: 2025-11-14T18:47:06.676Z
Learning: In the InsForge codebase, there are two distinct types of functions: (1) database functions (SQL stored procedures/functions in PostgreSQL) which are part of the database schema and emit DATA_UPDATE events with resource type DATABASE, handled in frontend/src/features/database/page/FunctionsPage.tsx; (2) edge/serverless functions which emit DATA_UPDATE events with resource type FUNCTIONS, handled in frontend/src/features/functions/page/FunctionsPage.tsx. These are separate concepts with different resource types.

Applied to files:

  • backend/src/services/functions/function.service.ts
📚 Learning: 2025-10-16T01:09:15.904Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:169-195
Timestamp: 2025-10-16T01:09:15.904Z
Learning: In frontend/src/features/ai/helpers.ts, the convertOpenRouterModelToOption function uses `model.name.split(':')[1]` to extract modelName. This is safe because OpenRouter predefines the name format to always include a colon, so the split operation will always return a valid value at index 1.

Applied to files:

  • backend/src/services/ai/ai-model.service.ts
📚 Learning: 2025-10-16T01:08:53.805Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:163-166
Timestamp: 2025-10-16T01:08:53.805Z
Learning: In frontend/src/features/ai/helpers.ts, the sortModalitiesByOrder function uses a simple indexOf-based sort. The user prefers this implementation because ModalitySchema currently only includes 'text' and 'image', both of which are in the order array, so the -1 case won't occur in practice.

Applied to files:

  • backend/src/services/ai/index.ts
📚 Learning: 2025-11-04T05:18:26.126Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 553
File: docs/changelog.mdx:6-35
Timestamp: 2025-11-04T05:18:26.126Z
Learning: The InsForge JavaScript SDK repository is named "insforge-sdk-js" and is located at https://github.com/insforge/insforge-sdk-js

Applied to files:

  • package.json
📚 Learning: 2025-10-25T13:38:54.723Z
Learnt from: Kathuria
Repo: InsForge/InsForge PR: 525
File: i18n/README.de.md:81-83
Timestamp: 2025-10-25T13:38:54.723Z
Learning: In README files for InsForge, code blocks containing natural language prompts/messages to be sent to AI agents (e.g., instructions like "Senden Sie in Ihrem Agenten:" or "Send in your agent:") should not have a language identifier like `bash`, as they are user prompts, not code commands.

Applied to files:

  • README.md
🧬 Code graph analysis (20)
backend/src/services/ai/chat-completion.service.ts (1)
backend/src/services/ai/index.ts (1)
  • ChatCompletionService (4-4)
backend/src/providers/oauth/google.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/api/routes/database/index.routes.ts (1)
backend/src/api/routes/database/records.routes.ts (1)
  • router (260-260)
backend/src/providers/email/base.provider.ts (1)
backend/src/types/email.ts (1)
  • EmailTemplate (4-8)
backend/src/providers/oauth/github.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/oauth/base.provider.ts (1)
backend/src/types/auth.ts (1)
  • OAuthUserData (139-154)
backend/src/providers/oauth/microsoft.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/api/routes/ai/index.routes.ts (2)
backend/src/services/ai/chat-completion.service.ts (1)
  • ChatCompletionService (13-210)
backend/src/services/ai/image-generation.service.ts (1)
  • ImageGenerationService (14-154)
backend/src/services/email/email.service.ts (4)
backend/src/providers/email/base.provider.ts (1)
  • EmailProvider (7-41)
backend/src/providers/email/cloud.provider.ts (1)
  • CloudEmailProvider (13-187)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/email.ts (1)
  • EmailTemplate (4-8)
backend/src/providers/oauth/discord.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/oauth/facebook.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
  • FacebookOAuthProvider (5-5)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/storage/base.provider.ts (1)
shared-schemas/src/storage-api.schema.ts (2)
  • UploadStrategyResponse (62-62)
  • DownloadStrategyResponse (64-64)
backend/src/providers/storage/local.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
  • StorageProvider (7-29)
shared-schemas/src/storage-api.schema.ts (2)
  • UploadStrategyResponse (62-62)
  • DownloadStrategyResponse (64-64)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/providers/email/cloud.provider.ts (1)
backend/src/providers/email/base.provider.ts (1)
  • EmailProvider (7-41)
backend/src/providers/oauth/linkedin.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
  • LinkedInOAuthProvider (4-4)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/oauth/x.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/services/ai/image-generation.service.ts (1)
backend/src/services/ai/index.ts (1)
  • ImageGenerationService (5-5)
backend/src/providers/storage/s3.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
  • StorageProvider (7-29)
backend/src/utils/logger.ts (1)
  • logger (6-29)
shared-schemas/src/storage-api.schema.ts (2)
  • UploadStrategyResponse (62-62)
  • DownloadStrategyResponse (64-64)
backend/src/services/auth/auth.service.ts (7)
backend/src/providers/oauth/google.provider.ts (1)
  • GoogleOAuthProvider (13-249)
backend/src/providers/oauth/github.provider.ts (1)
  • GitHubOAuthProvider (12-208)
backend/src/providers/oauth/discord.provider.ts (1)
  • DiscordOAuthProvider (12-195)
backend/src/providers/oauth/linkedin.provider.ts (1)
  • LinkedInOAuthProvider (12-240)
backend/src/providers/oauth/facebook.provider.ts (1)
  • FacebookOAuthProvider (12-194)
backend/src/providers/oauth/microsoft.provider.ts (1)
  • MicrosoftOAuthProvider (12-169)
backend/src/providers/oauth/x.provider.ts (1)
  • XOAuthProvider (9-202)
backend/src/services/storage/storage.service.ts (3)
backend/src/providers/storage/base.provider.ts (1)
  • StorageProvider (7-29)
backend/src/providers/storage/s3.provider.ts (1)
  • S3StorageProvider (24-313)
backend/src/providers/storage/local.provider.ts (1)
  • LocalStorageProvider (10-103)
🔇 Additional comments (57)
package.json (1)

3-3: LGTM! Version bump aligns with the refactor.

The version bump to 1.2.2 is consistent with the changelog entry and appropriate for this architecture refactor.

CHANGELOG.md (1)

3-4: LGTM! Changelog entry added for version 1.2.2.

The changelog entry is appropriate for this WIP refactor. Consider adding detailed changelog items before merging.

backend/src/providers/logs/cloudwatch.provider.ts (1)

12-12: LGTM! Import path updated correctly.

The import path has been correctly updated from @/api/middleware/error.js to @/api/middlewares/error.js, maintaining the .js extension consistently.

backend/src/api/middlewares/auth.ts (2)

2-2: LGTM! AuthService import path updated correctly.

The import path has been correctly updated from @/core/auth/auth.service.js to @/services/auth/auth.service.js, aligning with the new services-based architecture.


6-6: LGTM! SecretService import path updated correctly.

The import path has been correctly updated from @/core/secrets/secret.service.js to @/services/secrets/secret.service.js, aligning with the new services-based architecture.

backend/src/utils/validations.ts (1)

1-1: LGTM! Import path updated correctly.

The import path has been correctly updated from @/api/middleware/error to @/api/middlewares/error.

backend/src/providers/ai/openrouter.provider.ts (1)

4-4: LGTM! Import path updated correctly.

The import path has been correctly updated from @/api/middleware/error to @/api/middlewares/error.

backend/src/services/functions/function.service.ts (2)

1-1: LGTM! DatabaseManager import path updated correctly.

The import path has been correctly updated from @/core/database/manager.js to @/infra/database/manager.js, aligning with the new infrastructure-based architecture.


10-10: LGTM! AppError import path updated correctly across the codebase.

Verification confirms the import path has been correctly updated from @/api/middleware/error.js to @/api/middlewares/error.js in function.service.ts, and no remaining old import paths exist in the backend codebase.

backend/src/services/auth/auth-config.service.ts (1)

2-3: LGTM! Clean import path updates.

The import paths have been correctly updated to reflect the new architecture (infra for infrastructure, middlewares for middleware). The service logic remains unchanged.

backend/src/services/auth/oauth-config.service.ts (1)

2-4: LGTM! Import paths aligned with new architecture.

The import path updates are consistent with the project's migration to services/infra organization. All service functionality is preserved.

backend/src/api/routes/database/records.routes.ts (1)

5-16: LGTM! Comprehensive import path migration.

All import paths have been correctly updated to reflect the new organizational structure:

  • Middlewares: @/api/middlewares/*
  • Infrastructure: @/infra/database/*, @/infra/socket/*
  • Services: @/services/auth/*, @/services/secrets/*
  • Types: @/types/socket

The route logic remains unchanged and functional.

backend/src/services/ai/image-generation.service.ts (2)

3-5: LGTM! Import paths updated for service layer.

The import paths correctly reference the new service and provider locations.


14-14: Excellent rename for clarity.

The rename from ImageService to ImageGenerationService is more descriptive and aligns with the ChatCompletionService naming pattern. All internal references (lines 25, 40, 136) have been consistently updated.

backend/src/utils/seed.ts (1)

1-9: LGTM! All seed imports updated correctly.

The import paths have been comprehensively updated to reflect the new architecture:

  • Infrastructure: @/infra/database/*
  • Services: @/services/ai/*, @/services/auth/*, @/services/secrets/*

The seed logic remains intact and functional.

README.md (3)

28-28: Great addition! AI Integration feature documented.

The new AI Integration feature is now properly documented in the Core Features list, making it clear that InsForge supports chat completions and image generation with OpenAI-compatible APIs.


81-83: Improved quickstart prompt.

The updated prompt is clearer and more instructive, directing users to fetch the InsForge instruction doc to learn more. This aligns with the MCP integration workflow.

Based on learnings, the code block format without a language identifier is appropriate here since this is a user prompt to be sent to an AI agent, not a code command.


95-141: Excellent architecture visualization.

The new Mermaid diagram effectively illustrates:

  • How multiple agents (Claude, Cursor, Windsurf, etc.) connect via MCP
  • The fetch-docs pattern for InsForge instructions
  • Core service offerings (Storage, Auth, Database, Edge Function, AI Integration)

The accompanying Reddit-like app specification provides a concrete, relatable example for users. The styling makes the diagram visually appealing and professional.

backend/package.json (1)

19-24: LGTM! Migration scripts updated for new directory structure.

Verification confirms the migrations directory exists at backend/src/infra/database/migrations/ and contains 17 SQL migration files. All migration scripts correctly specify --migrations-dir src/infra/database/migrations, ensuring node-pg-migrate operates on the new infra directory structure as intended.

backend/src/providers/oauth/base.provider.ts (1)

1-29: LGTM! Clean provider interface definition.

All 7 OAuth providers (Google, GitHub, Discord, LinkedIn, Facebook, Microsoft, X) correctly implement the OAuthProvider interface with full compliance:

  • Required methods present in all providers: generateOAuthUrl() and handleCallback()
  • Optional method handleSharedCallback() implemented in 6 providers (Microsoft intentionally omits it, which is valid since the method is optional)
  • All method signatures match the interface contract exactly
  • Well-documented with consistent JSDoc comments
  • Standardized return type ensures consistency across implementations

The interface promotes clean, predictable OAuth provider implementations across the codebase.

backend/src/services/database/database-advance.service.ts (1)

1-2: Import paths aligned with new infra/middlewares layout

DatabaseManager and AppError imports now match the refactored locations; no behavioral change in this service.

backend/src/services/database/database-table.service.ts (1)

1-2: Consistent DatabaseManager/AppError import refactor

Updated imports match the new infra and middlewares structure and keep the service behavior intact.

backend/src/services/ai/ai-usage.service.ts (1)

1-2: DatabaseManager import moved to infra module

Using @/infra/database/manager.js keeps the pooling logic the same while aligning with the new infra layout.

backend/src/services/logs/audit.service.ts (1)

1-3: Audit service imports now point to infra/middlewares

Imports for DatabaseManager and AppError are consistent with the new architecture; behavior is unchanged.

backend/src/services/secrets/secret.service.ts (1)

3-5: Secrets service imports updated to infra modules

DatabaseManager and EncryptionUtils now come from the shared infra layer, centralizing DB and crypto concerns without changing this service’s behavior.

backend/src/api/routes/logs/index.routes.ts (1)

2-4: Logs router now wired to services/middlewares paths

Using @/services/logs/* and the new @/api/middlewares/auth.js is consistent with the backend re-architecture; route behavior is preserved.

backend/src/services/ai/ai-config.service.ts (1)

1-2: AIConfigService now depends on infra DatabaseManager

Switching to @/infra/database/manager.js keeps the pooling pattern identical while aligning with the new infra layer.

backend/src/services/ai/ai-model.service.ts (1)

2-5: AI model service now uses provider-based client and shared helpers

Importing AIClientService from @/providers/ai/openrouter.provider and helpers from ./helpers fits the new provider pattern; getModels’ logic and API remain the same.

backend/src/services/logs/log.service.ts (1)

2-4: Log provider import refactor looks consistent

The switch to @/providers/logs/* imports with .js extensions is consistent with the new provider-based logging structure and should be transparent to callers of LogService. No behavioral issues apparent in how CloudWatchProvider / LocalFileProvider are selected or used.

backend/src/api/routes/database/index.routes.ts (1)

1-13: Central database router composition is clean and correct

The new index router cleanly mounts the three sub-routers under /tables, /records, and /advance with explicit .js extensions, which fits the refactored routing architecture. No issues from an express standpoint.

backend/src/services/auth/auth-otp.service.ts (1)

4-5: Auth OTP imports now aligned with infra/middlewares layout

Updating DatabaseManager to @/infra/database/manager.js and AppError to @/api/middlewares/error.js matches the new layering and keeps the existing OTP transaction logic intact. No further changes required here.

backend/src/api/routes/usage/index.routes.ts (1)

2-5: Usage route imports correctly follow new infra/types structure

The updated imports for DatabaseManager, auth middlewares, SocketService, and ServerEvents are consistent with the broader move to infra and middlewares directories and maintain the existing route behavior.

backend/src/infra/socket/socket.ts (1)

4-15: SocketService import updates match refactored module layout

The AuthService, socket type, and AppError imports have been correctly redirected to @/services/auth/auth.service.js, @/types/socket.js, and @/api/middlewares/error.js, respectively. The surrounding SocketService logic remains intact, so this should be a no-op behaviorally.

backend/src/types/email.ts (1)

1-8: EmailTemplate union is a clear, type-safe centralization of template IDs

Defining EmailTemplate as a string-literal union with inline documentation gives providers and services a single, type-safe source of truth for email templates. This is a good fit for the refactored email provider architecture.

backend/src/api/routes/secrets/index.routes.ts (1)

2-5: LGTM!

Import path updates are consistent and correctly reflect the new project structure.

backend/src/api/routes/auth/index.routes.ts (1)

2-40: LGTM!

Import path updates correctly reflect the new project structure with consistent .js extensions throughout.

backend/src/api/routes/auth/oauth.routes.ts (1)

2-8: LGTM!

Import paths properly updated to reflect the new service and middleware organization.

backend/src/services/auth/index.ts (1)

1-4: LGTM!

Clean barrel export pattern with consistent .js extensions for all auth service modules.

backend/src/providers/oauth/linkedin.provider.ts (1)

12-28: Class rename and interface implementation look good.

The rename from LinkedInOAuthService to LinkedInOAuthProvider with OAuthProvider interface implementation aligns well with the provider-based architecture refactor.

backend/src/services/ai/chat-completion.service.ts (1)

13-13: Class rename verified as complete and correct.

The verification confirms:

  • New class name ChatCompletionService is properly declared at backend/src/services/ai/chat-completion.service.ts:13
  • Consumers have been updated (e.g., backend/src/api/routes/ai/index.routes.ts imports the new name)
  • No orphaned references to the old ChatService name remain anywhere in the codebase
backend/src/providers/oauth/x.provider.ts (1)

9-26: XOAuthProvider implementation aligns with OAuthProvider contract

The singleton pattern and the concrete implementations of generateOAuthUrl, handleCallback, and handleSharedCallback are consistent with the OAuthProvider interface and provide a clear, self-contained X/Twitter OAuth flow (including PKCE and shared-key mode). No functional issues spotted in these sections.

Also applies to: 82-201

backend/src/providers/oauth/index.ts (1)

1-7: Centralized OAuth provider barrel looks good

The consolidated exports for all OAuth providers are clean and make the public surface of the OAuth module obvious. Paths and names look consistent.

backend/src/services/ai/index.ts (1)

1-13: AI services and helper barrel export is consistent and useful

The centralized exports for AI services and helper functions give callers a single, coherent entry point to the AI module. Re-exporting modality helpers (sortModalities, filterAndSortModalities, etc.) aligns well with the existing pattern of using simple helper-based sorting logic elsewhere in the project. Based on learnings.

backend/src/api/routes/storage/index.routes.ts (1)

3-17: LGTM! Import paths updated for architectural refactor.

All import path updates are consistent with the migration from core/ to services//infra/ and middleware/ to middlewares/. No behavioral changes detected.

backend/src/api/routes/ai/index.routes.ts (3)

2-12: LGTM! Service imports updated correctly.

Import paths updated to reflect the new architecture with services in @/services/ and providers in @/providers/. The service renames (ChatService → ChatCompletionService, ImageService → ImageGenerationService) are consistent with the PR's architectural improvements.


23-23: LGTM! Service instantiation updated correctly.

The instantiation of ChatCompletionService aligns with the new service architecture and matches the instance method usage pattern throughout the route handlers.


136-136: LGTM! Static method call updated correctly.

The call to ImageGenerationService.generate() correctly uses the static method pattern as shown in the service implementation.

backend/src/providers/oauth/facebook.provider.ts (1)

4-24: LGTM! OAuth provider refactor completed correctly.

The class rename from FacebookOAuthService to FacebookOAuthProvider and the implementation of the OAuthProvider interface are correctly applied. The singleton pattern is properly updated, and all required interface methods are present.

backend/src/providers/oauth/github.provider.ts (1)

4-24: LGTM! GitHub provider refactor matches the new architecture.

The refactoring from GitHubOAuthService to GitHubOAuthProvider is consistent with the Facebook provider and correctly implements the OAuthProvider interface with all required methods.

backend/src/providers/oauth/google.provider.ts (1)

5-29: LGTM! Google provider refactor applied consistently.

The migration from GoogleOAuthService to GoogleOAuthProvider follows the same pattern as other OAuth providers and correctly implements the OAuthProvider interface.

backend/src/providers/oauth/microsoft.provider.ts (1)

4-24: LGTM! Microsoft provider refactor completed correctly.

The refactoring from MicrosoftOAuthService to MicrosoftOAuthProvider is consistent with other providers. Note that handleSharedCallback is not implemented, which is acceptable as it's optional in the OAuthProvider interface.

backend/src/server.ts (2)

8-27: LGTM! Server imports updated for new architecture.

All route imports updated to use consolidated index.routes.js files, and service/middleware imports reflect the new services//infra//middlewares/ structure. The packageJson import enables version reporting in the health endpoint.


164-174: LGTM! Route mounting consolidated successfully.

The database routes are now mounted under a single /api/database endpoint using the consolidated databaseRouter, which simplifies the routing structure. This aligns with the PR's goal of improving maintainability.

backend/src/providers/oauth/discord.provider.ts (1)

4-24: LGTM! Discord provider refactor completes the OAuth provider migration.

The refactoring from DiscordOAuthService to DiscordOAuthProvider is consistent with all other OAuth providers and correctly implements the OAuthProvider interface with all required methods.

backend/src/providers/storage/base.provider.ts (1)

1-29: Well‑factored storage abstraction

StorageProvider cleanly captures the storage contract (CRUD, bucket ops, presigned strategies, existence checks) and aligns with both LocalStorageProvider and S3StorageProvider. This should make future backends straightforward to plug in without touching StorageService.

backend/src/services/auth/auth.service.ts (2)

9-30: Import refactor looks consistent with new architecture layout

The moved imports (DatabaseManager → @/infra, OAuth config/services, providers, AppError, EmailService, XOAuthProvider) align with the new infra/ + providers/ + services/ structure and preserve the previous public APIs from this file’s perspective. No issues from this file’s usage standpoint.

Also applies to: 46-49


924-954: Review comment is incorrect—Facebook OAuth implementation is working as designed

The actual FacebookOAuthProvider implementation correctly handles the OAuth flow:

  1. exchangeCodeToToken calls the correct Facebook token endpoint (https://graph.facebook.com/v21.0/oauth/access_token) with the required parameters (client_id, client_secret, code, redirect_uri)
  2. It properly retrieves and returns the access token from the response
  3. handleCallback correctly chains the flow: it calls exchangeCodeToToken(payload.code) to obtain the token, then passes that token to getUserInfo(accessToken)
  4. getUserInfo then calls the user info endpoint (/me) with the retrieved access token—this is the expected behavior

The accessToken variable is not undefined; it is explicitly assigned from the exchangeCodeToToken return value. There are no bugs preventing Facebook OAuth login from functioning.

Likely an incorrect or invalid review comment.

Comment on lines +2 to +9
import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js';
import { FunctionService } from '@/services/functions/function.service.js';
import { AuditService } from '@/services/logs/audit.service.js';
import { AppError } from '@/api/middlewares/error.js';
import logger from '@/utils/logger.js';
import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas';
import { SocketService } from '@/core/socket/socket';
import { DataUpdateResourceType, ServerEvents } from '@/core/socket/types';
import { SocketService } from '@/infra/socket/socket';
import { DataUpdateResourceType, ServerEvents } from '@/types/socket';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix missing .js extensions for consistency.

Lines 8 and 9 are missing .js file extensions, which is inconsistent with the other imports in this file (lines 2-7). This could cause module resolution issues depending on your configuration.

Apply this diff:

-import { SocketService } from '@/infra/socket/socket';
-import { DataUpdateResourceType, ServerEvents } from '@/types/socket';
+import { SocketService } from '@/infra/socket/socket.js';
+import { DataUpdateResourceType, ServerEvents } from '@/types/socket.js';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js';
import { FunctionService } from '@/services/functions/function.service.js';
import { AuditService } from '@/services/logs/audit.service.js';
import { AppError } from '@/api/middlewares/error.js';
import logger from '@/utils/logger.js';
import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas';
import { SocketService } from '@/core/socket/socket';
import { DataUpdateResourceType, ServerEvents } from '@/core/socket/types';
import { SocketService } from '@/infra/socket/socket';
import { DataUpdateResourceType, ServerEvents } from '@/types/socket';
import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js';
import { FunctionService } from '@/services/functions/function.service.js';
import { AuditService } from '@/services/logs/audit.service.js';
import { AppError } from '@/api/middlewares/error.js';
import logger from '@/utils/logger.js';
import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas';
import { SocketService } from '@/infra/socket/socket.js';
import { DataUpdateResourceType, ServerEvents } from '@/types/socket.js';
🤖 Prompt for AI Agents
In backend/src/api/routes/functions/index.routes.ts around lines 2 to 9, imports
on lines 8 and 9 are missing the .js extensions; update the import specifiers to
include the .js extension (e.g., change "@insforge/shared-schemas" to
"@insforge/shared-schemas.js" and "@/infra/socket/socket" to
"@/infra/socket/socket.js") so they match the other imports in this file and
ensure consistent module resolution.

Comment thread backend/src/utils/cloud-token.ts Resolved
@tonychang04
tonychang04 self-requested a review November 19, 2025 00:31

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
backend/src/providers/email/cloud.provider.ts (2)

82-94: Consider centralizing template validation to reduce maintenance burden.

The validTemplates array duplicates the EmailTemplate type definition imported from @/types/email.js. If the type changes, this validation logic must be manually updated, creating a maintenance risk and potential for runtime errors.

Consider one of these approaches:

Option 1: Define the valid templates as a const array in @/types/email.js and import it:

// In @/types/email.js
export const VALID_EMAIL_TEMPLATES = [
  'email-verification-code',
  'email-verification-link',
  'reset-password-code',
  'reset-password-link',
] as const;

export type EmailTemplate = typeof VALID_EMAIL_TEMPLATES[number];

Then use it here:

-      const validTemplates: EmailTemplate[] = [
-        'email-verification-code',
-        'email-verification-link',
-        'reset-password-code',
-        'reset-password-link',
-      ];
-      if (!validTemplates.includes(template)) {
+      if (!VALID_EMAIL_TEMPLATES.includes(template)) {
         throw new AppError(
-          `Invalid template type: ${template}. Must be one of: ${validTemplates.join(', ')}`,
+          `Invalid template type: ${template}. Must be one of: ${VALID_EMAIL_TEMPLATES.join(', ')}`,
           400,
           ERROR_CODES.INVALID_INPUT
         );
       }

Option 2: If runtime validation isn't critical (TypeScript already enforces the type), you can remove this check entirely and rely on the type system.


110-110: Consider making the timeout configurable.

The 10-second timeout is hardcoded. Consider adding this to the config for better flexibility, especially if different environments require different timeout values.

-          timeout: 10000, // 10 second timeout
+          timeout: config.cloud.emailTimeout || 10000,
backend/src/api/routes/metadata/index.routes.ts (1)

110-111: Consider using a singleton pattern for SecretService.

A new SecretService instance is created on every request. While this works (the underlying database pool is shared via the DatabaseManager singleton), adopting a singleton pattern like other services would reduce object allocations.

Apply this pattern if you'd like to optimize:

+const secretService = new SecretService();
+
 router.use(verifyAdmin);
 
 // Get full metadata (default endpoint)

Then replace line 110:

-    const secretService = new SecretService();
-    const apiKey = await secretService.getSecretByKey('API_KEY');
+    const apiKey = await secretService.getSecretByKey('API_KEY');
backend/src/providers/storage/local.provider.ts (1)

50-56: Consider using fs.rm instead of deprecated fs.rmdir.

The fs.rmdir method with recursive option is deprecated in Node.js 14+ in favor of fs.rm.

Apply this diff:

 async deleteBucket(bucket: string): Promise<void> {
   try {
-    await fs.rmdir(path.join(this.baseDir, bucket), { recursive: true });
+    await fs.rm(path.join(this.baseDir, bucket), { recursive: true });
   } catch {
     // Directory might not exist
   }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de2b7d6 and 14fb397.

📒 Files selected for processing (33)
  • backend/src/api/middlewares/error.ts (1 hunks)
  • backend/src/api/middlewares/rate-limiters.ts (1 hunks)
  • backend/src/api/routes/ai/index.routes.ts (3 hunks)
  • backend/src/api/routes/database/advance.routes.ts (1 hunks)
  • backend/src/api/routes/database/records.routes.ts (1 hunks)
  • backend/src/api/routes/database/tables.routes.ts (1 hunks)
  • backend/src/api/routes/functions/index.routes.ts (1 hunks)
  • backend/src/api/routes/metadata/index.routes.ts (2 hunks)
  • backend/src/api/routes/storage/index.routes.ts (1 hunks)
  • backend/src/providers/ai/openrouter.provider.ts (1 hunks)
  • backend/src/providers/email/cloud.provider.ts (3 hunks)
  • backend/src/providers/oauth/base.provider.ts (1 hunks)
  • backend/src/providers/oauth/discord.provider.ts (1 hunks)
  • backend/src/providers/oauth/facebook.provider.ts (1 hunks)
  • backend/src/providers/oauth/github.provider.ts (1 hunks)
  • backend/src/providers/oauth/google.provider.ts (2 hunks)
  • backend/src/providers/oauth/linkedin.provider.ts (2 hunks)
  • backend/src/providers/oauth/microsoft.provider.ts (1 hunks)
  • backend/src/providers/oauth/x.provider.ts (1 hunks)
  • backend/src/providers/storage/local.provider.ts (1 hunks)
  • backend/src/server.ts (2 hunks)
  • backend/src/services/ai/ai-model.service.ts (1 hunks)
  • backend/src/services/ai/chat-completion.service.ts (1 hunks)
  • backend/src/services/ai/helpers.ts (1 hunks)
  • backend/src/services/ai/image-generation.service.ts (4 hunks)
  • backend/src/services/auth/auth.service.ts (6 hunks)
  • backend/src/services/database/database-advance.service.ts (2 hunks)
  • backend/src/services/database/database-table.service.ts (2 hunks)
  • backend/src/services/storage/storage.service.ts (3 hunks)
  • backend/src/utils/cloud-token.ts (1 hunks)
  • backend/src/utils/seed.ts (1 hunks)
  • backend/src/utils/sql-parser.ts (1 hunks)
  • backend/src/utils/validations.ts (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • backend/src/api/middlewares/error.ts
  • backend/src/api/middlewares/rate-limiters.ts
  • backend/src/services/database/database-advance.service.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • backend/src/services/database/database-table.service.ts
  • backend/src/utils/validations.ts
  • backend/src/api/routes/database/records.routes.ts
  • backend/src/api/routes/database/advance.routes.ts
  • backend/src/api/routes/ai/index.routes.ts
  • backend/src/providers/ai/openrouter.provider.ts
  • backend/src/api/routes/functions/index.routes.ts
  • backend/src/services/ai/image-generation.service.ts
  • backend/src/providers/oauth/linkedin.provider.ts
  • backend/src/utils/seed.ts
  • backend/src/providers/oauth/microsoft.provider.ts
  • backend/src/providers/oauth/base.provider.ts
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-16T01:09:15.904Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:169-195
Timestamp: 2025-10-16T01:09:15.904Z
Learning: In frontend/src/features/ai/helpers.ts, the convertOpenRouterModelToOption function uses `model.name.split(':')[1]` to extract modelName. This is safe because OpenRouter predefines the name format to always include a colon, so the split operation will always return a valid value at index 1.

Applied to files:

  • backend/src/services/ai/helpers.ts
  • backend/src/services/ai/ai-model.service.ts
📚 Learning: 2025-10-16T01:08:53.805Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:163-166
Timestamp: 2025-10-16T01:08:53.805Z
Learning: In frontend/src/features/ai/helpers.ts, the sortModalitiesByOrder function uses a simple indexOf-based sort. The user prefers this implementation because ModalitySchema currently only includes 'text' and 'image', both of which are in the order array, so the -1 case won't occur in practice.

Applied to files:

  • backend/src/services/ai/helpers.ts
🧬 Code graph analysis (11)
backend/src/providers/oauth/x.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
  • XOAuthProvider (7-7)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/services/ai/chat-completion.service.ts (1)
backend/src/services/ai/index.ts (1)
  • ChatCompletionService (4-4)
backend/src/providers/oauth/discord.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/oauth/facebook.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/services/storage/storage.service.ts (3)
backend/src/providers/storage/base.provider.ts (1)
  • StorageProvider (7-29)
backend/src/providers/storage/s3.provider.ts (1)
  • S3StorageProvider (24-313)
backend/src/providers/storage/local.provider.ts (1)
  • LocalStorageProvider (10-103)
backend/src/providers/email/cloud.provider.ts (1)
backend/src/providers/email/base.provider.ts (1)
  • EmailProvider (7-41)
backend/src/api/routes/metadata/index.routes.ts (1)
backend/src/services/secrets/secret.service.ts (1)
  • SecretService (32-410)
backend/src/services/auth/auth.service.ts (7)
backend/src/providers/oauth/google.provider.ts (1)
  • GoogleOAuthProvider (13-249)
backend/src/providers/oauth/github.provider.ts (1)
  • GitHubOAuthProvider (12-208)
backend/src/providers/oauth/discord.provider.ts (1)
  • DiscordOAuthProvider (12-195)
backend/src/providers/oauth/linkedin.provider.ts (1)
  • LinkedInOAuthProvider (12-240)
backend/src/providers/oauth/facebook.provider.ts (1)
  • FacebookOAuthProvider (12-194)
backend/src/providers/oauth/microsoft.provider.ts (1)
  • MicrosoftOAuthProvider (12-169)
backend/src/providers/oauth/x.provider.ts (1)
  • XOAuthProvider (9-202)
backend/src/providers/oauth/github.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/oauth/google.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
  • OAuthProvider (7-29)
backend/src/providers/storage/local.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
  • StorageProvider (7-29)
shared-schemas/src/storage-api.schema.ts (2)
  • UploadStrategyResponse (62-62)
  • DownloadStrategyResponse (64-64)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (31)
backend/src/utils/cloud-token.ts (1)

2-3: Import paths updated correctly with .js extensions.

The import paths have been successfully updated to reflect the new backend structure:

  • @/api/middleware/error → @/api/middlewares/error.js
  • @/types/error-constants → @/types/error-constants.js

Both imports now include the .js extension, addressing the consistency concern raised in the previous review. The changes correctly align with the new directory layout and ESM module resolution requirements.

backend/src/services/ai/helpers.ts (1)

1-1: LGTM!

The explicit .js extension aligns with ES module best practices and the broader refactoring goal of normalizing import paths.

backend/src/services/ai/chat-completion.service.ts (1)

2-4: LGTM!

The updated import paths and class rename to ChatCompletionService align well with the refactoring objectives, improving clarity and maintainability.

Also applies to: 13-13

backend/src/providers/email/cloud.provider.ts (2)

1-13: LGTM! Clean implementation of the provider interface.

The import paths have been correctly updated to the new module structure, and the class properly implements the EmailProvider interface from base.provider.ts.


47-52: LGTM! Correctly implements interface requirement.

The supportsTemplates() method properly implements the required interface method and accurately returns true for this cloud-based provider.

backend/src/services/ai/ai-model.service.ts (1)

1-5: Import verification passed—all paths resolve correctly.

All four imports in the file have been verified:

  • isCloudEnvironment correctly exported from @/utils/environment.js
  • AIClientService correctly exported from @/providers/ai/openrouter.provider.js
  • RawOpenRouterModel correctly exported from @/types/ai.js
  • calculatePriceLevel, filterAndSortModalities, getProviderOrder correctly exported from ./helpers.js

The import path updates are sound, the refactor structure is consistent, and the code is ready.

backend/src/utils/sql-parser.ts (1)

3-3: ESM import path updated correctly and verified consistent across codebase.

The .js extension on line 3 is correct for ESM and TypeScript. Verification confirms all local module imports in backend/src/ consistently use .js extensions, confirming the refactoring is complete and uniform.

backend/src/api/routes/database/tables.routes.ts (1)

2-8: LGTM! Import paths successfully updated.

All imports now correctly reference the new module structure with explicit .js extensions. The previous concern about the missing .js extension on the AuditService import has been resolved.

backend/src/api/routes/metadata/index.routes.ts (1)

2-13: LGTM! Import consistency restored.

All imports now include explicit .js extensions, resolving the previous review concerns about lines 12-13. The module paths correctly reflect the new architecture.

backend/src/providers/oauth/x.provider.ts (1)

9-28: LGTM! Provider refactor correctly implemented.

The class has been successfully renamed to XOAuthProvider and now implements the OAuthProvider interface. The singleton pattern and method signature (generateOAuthUrl) align with the new provider-based architecture.

backend/src/providers/oauth/facebook.provider.ts (1)

12-29: LGTM! Consistent provider pattern applied.

The refactor from FacebookOAuthService to FacebookOAuthProvider implementing the OAuthProvider interface is consistent with the broader OAuth provider architecture changes across the codebase.

backend/src/providers/oauth/discord.provider.ts (1)

12-29: LGTM! Provider architecture consistently applied.

The renaming and interface implementation align with the standardized OAuth provider pattern being applied across all providers in this refactor.

backend/src/api/routes/storage/index.routes.ts (1)

3-17: LGTM! Import paths successfully migrated.

All import paths have been correctly updated to reflect the new architecture (services/, infra/, middlewares/) with explicit .js extensions throughout.

backend/src/server.ts (2)

8-26: LGTM! Router imports successfully consolidated.

All route imports now use the index.routes.js pattern and reference the correct paths. Infrastructure imports (DatabaseManager, LogService, StorageService, SocketService) correctly point to their new locations in infra/ and services/.


164-174: LGTM! Database routes successfully consolidated.

The consolidation of database routes under /api/database (line 166) aligns with the PR's objective to normalize and organize the backend structure. The removal of deprecated OpenAPI and agent documentation routes is also consistent with the stated goals.

backend/src/providers/oauth/github.provider.ts (1)

12-29: LGTM! Provider pattern consistently implemented.

The refactor to GitHubOAuthProvider implementing OAuthProvider is consistent with the standardized provider architecture applied across all OAuth integrations in this PR.

backend/src/providers/oauth/google.provider.ts (5)

1-29: LGTM! Clean refactoring to provider-based architecture.

The class correctly implements the OAuthProvider interface and the singleton pattern has been properly updated with the new class name.


34-81: LGTM!

The OAuth URL generation logic correctly handles both shared key and standard OAuth flows.


86-202: LGTM!

The token exchange and verification methods correctly handle caching, deduplication, and error cases.


207-229: LGTM!

The callback handler correctly implements the OAuthProvider interface and properly transforms provider-specific data to the generic format.


234-248: LGTM!

The shared callback handler correctly transforms the payload data with defensive type coercion.

backend/src/services/storage/storage.service.ts (4)

1-45: LGTM! Provider-based architecture properly implemented.

The service correctly instantiates either S3StorageProvider or LocalStorageProvider based on the environment configuration.


389-412: LGTM!

The method correctly generates the next available key using the (1), (2), (3) pattern before delegating to the storage provider.


414-422: LGTM!

The method correctly determines bucket visibility internally and passes it to the storage provider.


119-563: LGTM! Comprehensive provider delegation.

All storage operations correctly delegate to the provider while maintaining business logic (validation, metadata management, access control) at the service layer.

backend/src/providers/storage/local.provider.ts (3)

58-61: LGTM!

Correctly indicates that local storage does not support presigned URLs.


63-90: LGTM!

The upload and download strategies correctly return direct URLs with proper encoding for local storage operations.


92-102: LGTM!

The file existence verification correctly uses fs.access with appropriate error handling.

backend/src/services/auth/auth.service.ts (3)

1-71: LGTM! Consistent provider-based refactoring.

All imports and field declarations have been correctly updated to use the new provider-based architecture.


73-111: LGTM!

All OAuth providers are correctly initialized using their singleton getInstance() methods.


900-1008: LGTM! OAuth provider integration complete.

All three OAuth methods correctly delegate to the appropriate provider implementations with proper error handling for unsupported providers.

} from '@insforge/shared-schemas';
import logger from '@/utils/logger.js';
import { ChatCompletionOptions } from '@/types/ai';
import { ChatCompletionOptions } from '@/types/ai.js';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use type-only import for ChatCompletionOptions.

Since ChatCompletionOptions is only used as a type annotation (lines 81, 144), it should be imported as a type-only import to prevent unnecessary runtime bundling.

Apply this diff:

-import { ChatCompletionOptions } from '@/types/ai.js';
+import type { ChatCompletionOptions } from '@/types/ai.js';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { ChatCompletionOptions } from '@/types/ai.js';
import type { ChatCompletionOptions } from '@/types/ai.js';
🤖 Prompt for AI Agents
In backend/src/services/ai/chat-completion.service.ts around line 11, the import
"import { ChatCompletionOptions } from '@/types/ai.js';" brings in
ChatCompletionOptions at runtime even though it's used only for type annotations
(lines ~81 and ~144); change it to a type-only import (e.g., "import type {
ChatCompletionOptions } from '@/types/ai.js';") so the type is erased at emit
and not included in the runtime bundle.

@Fermionic-Lyu Fermionic-Lyu changed the title [WIP][Refactor] Backend Re-architecture [Refactor] Backend Re-architecture Nov 19, 2025
@Fermionic-Lyu
Fermionic-Lyu merged commit 42a5109 into main Nov 19, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Dec 13, 2025
This was referenced Jan 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants