@friggframework/core 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CLAUDE.md +48 -93
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -33
  6. package/core/Worker.js +11 -317
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/backend-utils.js +1 -30
  38. package/handlers/workers/integration-defined-workers.js +0 -2
  39. package/index.js +2 -18
  40. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
  41. package/integrations/integration-base.js +52 -9
  42. package/integrations/integration-router.js +30 -22
  43. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  44. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  45. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  46. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  47. package/integrations/repositories/integration-mapping-repository.js +29 -0
  48. package/integrations/repositories/integration-repository-documentdb.js +32 -0
  49. package/integrations/repositories/integration-repository-interface.js +30 -0
  50. package/integrations/repositories/integration-repository-mongo.js +53 -1
  51. package/integrations/repositories/integration-repository-postgres.js +58 -0
  52. package/integrations/repositories/process-repository-mongo.js +1 -1
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/index.js +1 -5
  58. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/requester/oauth-2.js +0 -7
  67. package/modules/requester/requester.js +9 -187
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +9 -8
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queue-delivery.js +0 -1
  81. package/queues/queuer-util.js +10 -8
  82. package/queues/sqs-message-body.js +17 -0
  83. package/telemetry/otel-telemetry.js +76 -3
  84. package/telemetry/telemetry-config.js +16 -5
  85. package/telemetry/telemetry-runtime.js +14 -1
  86. package/token/repositories/token-repository-documentdb.js +13 -1
  87. package/token/repositories/token-repository-mongo.js +13 -1
  88. package/token/repositories/token-repository-postgres.js +13 -1
  89. package/types/core/index.d.ts +0 -52
  90. package/types/errors/index.d.ts +0 -47
  91. package/types/module-plugin/index.d.ts +0 -43
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
  98. package/integrations/use-cases/record-rate-limit-wait.js +0 -36
  99. package/modules/requester/rate-limit/index.js +0 -4
  100. package/modules/requester/rate-limit/parsers.js +0 -245
  101. package/modules/requester/rate-limit/policy.js +0 -304
  102. package/queues/queue-deferral.js +0 -74
@@ -354,6 +354,10 @@ const config = {
354
354
  {
355
355
  "fromEnvVar": null,
356
356
  "value": "rhel-openssl-3.0.x"
357
+ },
358
+ {
359
+ "fromEnvVar": null,
360
+ "value": "linux-arm64-openssl-3.0.x"
357
361
  }
358
362
  ],
359
363
  "previewFeatures": [],
@@ -380,8 +384,8 @@ const config = {
380
384
  }
381
385
  }
382
386
  },
383
- "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(IN_CREATION)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n IN_CREATION\n IN_DELETION\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n\n// ============================================================================\n// ADMIN PROCESS MODELS\n// ============================================================================\n\n/// Admin process state machine\nenum AdminScriptExecutionState {\n PENDING\n RUNNING\n COMPLETED\n FAILED\n}\n\n/// Admin process tracking (like Process but without user/integration FK)\n/// Used for: admin scripts, db migrations, system maintenance tasks\nmodel AdminScriptExecution {\n id Int @id @default(autoincrement())\n name String // e.g., \"oauth-token-refresh\", \"db-migration-xyz\"\n type String // e.g., \"ADMIN_SCRIPT\", \"DB_MIGRATION\"\n\n // State machine\n state AdminScriptExecutionState @default(PENDING)\n\n // Flexible storage (mirrors Process model pattern)\n context Json @default(\"{}\") // input, trigger, audit info, script version\n results Json @default(\"{}\") // output, logs, metrics, errors\n\n // Hierarchy support - self-referential relation\n parentExecutionId Int?\n parentExecution AdminScriptExecution? @relation(\"AdminScriptExecutionHierarchy\", fields: [parentExecutionId], references: [id], onDelete: SetNull)\n childExecutions AdminScriptExecution[] @relation(\"AdminScriptExecutionHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([name, createdAt(sort: Desc)])\n @@index([state])\n @@index([type])\n}\n\n/// Script scheduling configuration for hybrid scheduling (SQS + EventBridge)\nmodel ScriptSchedule {\n id Int @id @default(autoincrement())\n scriptName String @unique\n enabled Boolean @default(false)\n cronExpression String?\n timezone String @default(\"UTC\")\n lastTriggeredAt DateTime?\n nextTriggerAt DateTime?\n\n // External Scheduler (e.g., AWS EventBridge Scheduler)\n externalScheduleId String?\n externalScheduleName String?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([enabled])\n}\n\n/// Durable usage counters, deliberately isolated: no userId and no foreign key\n/// to Integration, so a user-scoped query can never return a usage row and usage\n/// history survives integration deletion.\nmodel UsageCounter {\n id Int @id @default(autoincrement())\n\n integrationId String\n integrationType String\n metric String\n window String // e.g. \"day:2026-07-05\" or \"hour:2026-07-05T14\"\n value BigInt @default(0) // BigInt: a busy day/hour counter can exceed 32-bit\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, integrationType, metric, window])\n // Covers totals() (metric + window prefix/range, no integrationType filter).\n @@index([metric, window])\n // Covers series() (metric + integrationType + window range).\n @@index([metric, integrationType, window])\n}\n",
384
- "inlineSchemaHash": "479850322beddd1dd3603ea62e13dd64fd3fb9c7b99da74bb7f40fe6450e65ae",
387
+ "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\", \"linux-arm64-openssl-3.0.x\"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(IN_CREATION)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n IN_CREATION\n IN_DELETION\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n\n// ============================================================================\n// ADMIN PROCESS MODELS\n// ============================================================================\n\n/// Admin process state machine\nenum AdminScriptExecutionState {\n PENDING\n RUNNING\n COMPLETED\n FAILED\n}\n\n/// Admin process tracking (like Process but without user/integration FK)\n/// Used for: admin scripts, db migrations, system maintenance tasks\nmodel AdminScriptExecution {\n id Int @id @default(autoincrement())\n name String // e.g., \"oauth-token-refresh\", \"db-migration-xyz\"\n type String // e.g., \"ADMIN_SCRIPT\", \"DB_MIGRATION\"\n\n // State machine\n state AdminScriptExecutionState @default(PENDING)\n\n // Flexible storage (mirrors Process model pattern)\n context Json @default(\"{}\") // input, trigger, audit info, script version\n results Json @default(\"{}\") // output, logs, metrics, errors\n\n // Hierarchy support - self-referential relation\n parentExecutionId Int?\n parentExecution AdminScriptExecution? @relation(\"AdminScriptExecutionHierarchy\", fields: [parentExecutionId], references: [id], onDelete: SetNull)\n childExecutions AdminScriptExecution[] @relation(\"AdminScriptExecutionHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([name, createdAt(sort: Desc)])\n @@index([state])\n @@index([type])\n}\n\n/// Script scheduling configuration for hybrid scheduling (SQS + EventBridge)\nmodel ScriptSchedule {\n id Int @id @default(autoincrement())\n scriptName String @unique\n enabled Boolean @default(false)\n cronExpression String?\n timezone String @default(\"UTC\")\n lastTriggeredAt DateTime?\n nextTriggerAt DateTime?\n\n // External Scheduler (e.g., AWS EventBridge Scheduler)\n externalScheduleId String?\n externalScheduleName String?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([enabled])\n}\n\n/// Durable usage counters, deliberately isolated: no userId and no foreign key\n/// to Integration, so a user-scoped query can never return a usage row and usage\n/// history survives integration deletion.\nmodel UsageCounter {\n id Int @id @default(autoincrement())\n\n integrationId String\n integrationType String\n metric String\n window String // e.g. \"day:2026-07-05\" or \"hour:2026-07-05T14\"\n value BigInt @default(0) // BigInt: a busy day/hour counter can exceed 32-bit\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, integrationType, metric, window])\n // Covers totals() (metric + window prefix/range, no integrationType filter).\n @@index([metric, window])\n // Covers series() (metric + integrationType + window range).\n @@index([metric, integrationType, window])\n}\n",
388
+ "inlineSchemaHash": "db175a805645aca6df6afa87560783c4a684e0579eb550a679bae2f16d43119a",
385
389
  "copyEngine": true
386
390
  }
387
391
  config.dirname = '/'
@@ -483,6 +483,35 @@ async onWebhook({ data }) {
483
483
  }
484
484
  ```
485
485
 
486
+ `getMapping` followed by `upsertMapping` is not atomic. To claim an event so only one
487
+ concurrent worker proceeds, use the insert-only `createMapping`, which throws
488
+ `MappingAlreadyExistsError` (exported from `@friggframework/core`) when the
489
+ `sourceId` is already taken. `deleteMapping(sourceId)` releases the claim and is a
490
+ no-op when nothing exists.
491
+
492
+ ```javascript
493
+ const { MappingAlreadyExistsError } = require('@friggframework/core');
494
+
495
+ async onWebhook({ data }) {
496
+ const claimId = `claim:${data.body.id}`;
497
+ try {
498
+ await this.createMapping(claimId, { claimedAt: new Date() });
499
+ } catch (error) {
500
+ if (error instanceof MappingAlreadyExistsError) {
501
+ return { processed: false, duplicate: true };
502
+ }
503
+ throw error;
504
+ }
505
+
506
+ try {
507
+ await this.processEvent(data.body);
508
+ } catch (error) {
509
+ await this.deleteMapping(claimId);
510
+ throw error;
511
+ }
512
+ }
513
+ ```
514
+
486
515
  ### 4. Error Handling
487
516
  ```javascript
488
517
  async onWebhook({ data }) {
@@ -1,6 +1,9 @@
1
1
  const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
2
2
  const path = require('node:path');
3
3
  const fs = require('fs-extra');
4
+ const {
5
+ applyAppDefinitionDefaults,
6
+ } = require('@friggframework/schemas/app-definition');
4
7
  const { resolveTelemetryConfig } = require('../telemetry/telemetry-config');
5
8
  const { registerDeniedKeys } = require('../logs/denied-keys');
6
9
  const {
@@ -33,7 +36,9 @@ function registerCredentialLogKeys(appDefinition, integrations) {
33
36
  * @function loadAppDefinition
34
37
  * @description Searches for the nearest backend package.json, loads the corresponding index.js file,
35
38
  * and extracts the application definition containing integrations and user configuration.
36
- * @returns {{integrations: Array<object>, userConfig: object | null, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
39
+ * The defaults declared in the app-definition schema are applied first (ADR-051), so
40
+ * `userConfig` always holds a complete user config, also when the app omits `user`.
41
+ * @returns {{integrations: Array<object>, userConfig: object, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
37
42
  * @throws {Error} Throws error if backend package.json cannot be found.
38
43
  * @throws {Error} Throws error if index.js file cannot be found in the backend directory.
39
44
  * @example
@@ -53,7 +58,9 @@ function loadAppDefinition() {
53
58
  }
54
59
 
55
60
  const backendJsFile = require(backendFilePath);
56
- const appDefinition = backendJsFile.Definition;
61
+ // The one place schema defaults are applied at runtime (ADR-051): a
62
+ // default in app-definition.schema.json is the value core sees.
63
+ const appDefinition = applyAppDefinitionDefaults(backendJsFile.Definition);
57
64
 
58
65
  const {
59
66
  integrations = [],
@@ -9,6 +9,17 @@ const serverlessHttp = require('serverless-http');
9
9
 
10
10
  const log = getLogger('frigg.http');
11
11
 
12
+ const isHttpErrorStatus = (statusCode) =>
13
+ Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
14
+
15
+ const toBoom = (err) => {
16
+ if (err.isBoom) return err;
17
+ if (err.isClientSafe === true && isHttpErrorStatus(err.statusCode)) {
18
+ return Boom.boomify(err, { statusCode: err.statusCode });
19
+ }
20
+ return Boom.boomify(err);
21
+ };
22
+
12
23
  const createApp = (applyMiddleware) => {
13
24
  const app = express();
14
25
 
@@ -27,7 +38,7 @@ const createApp = (applyMiddleware) => {
27
38
 
28
39
  // The express boundary: send the error response and log it one time.
29
40
  app.use((err, req, res, next) => {
30
- const boomError = err.isBoom ? err : Boom.boomify(err);
41
+ const boomError = toBoom(err);
31
42
  const {
32
43
  output: { statusCode = 500 },
33
44
  } = boomError;
@@ -21,12 +21,6 @@ const {
21
21
  getModulesDefinitionFromIntegrationClasses,
22
22
  } = require('../integrations/utils/map-integration-dto');
23
23
  const { processNotFound } = require('../integrations/use-cases/process-errors');
24
- const {
25
- RecordRateLimitWait,
26
- } = require('../integrations/use-cases/record-rate-limit-wait');
27
- const {
28
- ClearRateLimitWait,
29
- } = require('../integrations/use-cases/clear-rate-limit-wait');
30
24
 
31
25
  const loadRouterFromObject = (IntegrationClass, routerObject) => {
32
26
  const router = Router();
@@ -171,28 +165,6 @@ const createQueueWorker = (integrationClass) => {
171
165
  const integrationName = integrationClass.Definition.name;
172
166
 
173
167
  class QueueWorker extends Worker {
174
- async recordRateLimitWait(body, error, state) {
175
- const processId = body.data?.processId;
176
- if (!processId) return;
177
- const recordRateLimitWait = new RecordRateLimitWait({
178
- processRepository: createProcessRepository(),
179
- });
180
- await recordRateLimitWait.execute(processId, {
181
- ...state,
182
- reason: error.reason,
183
- module: error.module,
184
- });
185
- }
186
-
187
- async clearRateLimitWait(body, { deferralId } = {}) {
188
- const processId = body?.data?.processId;
189
- if (!processId) return;
190
- const clearRateLimitWait = new ClearRateLimitWait({
191
- processRepository: createProcessRepository(),
192
- });
193
- await clearRateLimitWait.execute(processId, { deferralId });
194
- }
195
-
196
168
  async _run(params, context, delivery) {
197
169
  const logCtx = {
198
170
  integration: integrationName,
@@ -313,8 +285,7 @@ const createQueueWorker = (integrationClass) => {
313
285
  status >= 400 &&
314
286
  status < 500 &&
315
287
  status !== 408 &&
316
- status !== 429 &&
317
- !error.isRateLimited
288
+ status !== 429
318
289
  ) {
319
290
  error.isHaltError = true;
320
291
  console.warn(
@@ -1,7 +1,6 @@
1
1
  const { createHandler } = require('@friggframework/core');
2
2
  const { loadAppDefinition } = require('../app-definition-loader');
3
3
  const { createQueueWorker } = require('../backend-utils');
4
- const { MAX_IN_PROCESS_WAIT_MS } = require('../../core/invocation-deadline');
5
4
  // TODO(Phase 2): mount extension-declared workers in addition to the per-integration
6
5
  // default queue worker. Today, getExtensionWorkers(IntegrationClass) returns the
7
6
  // declared workers but they are not yet bound to dedicated SQS sources. Extension-
@@ -20,7 +19,6 @@ integrationClasses.forEach((IntegrationClass) => {
20
19
  queueWorker: createHandler({
21
20
  eventName: `Queue Worker for ${IntegrationClass.Definition.name}`,
22
21
  isUserFacingResponse: false,
23
- maxInProcessWaitMs: MAX_IN_PROCESS_WAIT_MS.queueWorker,
24
22
  method: async (event, context) => {
25
23
  const worker = new defaultQueueWorker();
26
24
  return await worker.run(event, context);
package/index.js CHANGED
@@ -12,8 +12,6 @@ const {
12
12
  loadInstalledModules,
13
13
  createHandler,
14
14
  runInvocationScope,
15
- runWithInvocationDeadline,
16
- remainingInvocationMs,
17
15
  } = require('./core/index');
18
16
  const {
19
17
  prisma,
@@ -57,9 +55,9 @@ const {
57
55
  BaseError,
58
56
  FetchError,
59
57
  HaltError,
60
- RateLimitError,
61
58
  RequiredPropertyError,
62
59
  ParameterTypeError,
60
+ MappingAlreadyExistsError,
63
61
  } = require('./errors/index');
64
62
  const {
65
63
  IntegrationBase,
@@ -103,12 +101,6 @@ const {
103
101
  ModuleConstants,
104
102
  ModuleFactory,
105
103
  } = require('./modules/index');
106
- const {
107
- classifyRateLimit,
108
- parseRetryAfter,
109
- parseResetHeaders,
110
- parseIetfRateLimit,
111
- } = require('./modules/requester/rate-limit');
112
104
  const application = require('./application');
113
105
  const utils = require('./utils');
114
106
 
@@ -129,8 +121,6 @@ module.exports = {
129
121
  loadInstalledModules,
130
122
  createHandler,
131
123
  runInvocationScope,
132
- runWithInvocationDeadline,
133
- remainingInvocationMs,
134
124
 
135
125
  // database
136
126
  prisma,
@@ -153,15 +143,9 @@ module.exports = {
153
143
  BaseError,
154
144
  FetchError,
155
145
  HaltError,
156
- RateLimitError,
157
146
  RequiredPropertyError,
158
147
  ParameterTypeError,
159
-
160
- // rate limit
161
- classifyRateLimit,
162
- parseRetryAfter,
163
- parseResetHeaders,
164
- parseIetfRateLimit,
148
+ MappingAlreadyExistsError,
165
149
 
166
150
  // integrations
167
151
  IntegrationBase,
@@ -11,23 +11,67 @@
11
11
  * This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
12
12
  */
13
13
 
14
- const {
15
- SchedulerClient,
16
- CreateScheduleCommand,
17
- DeleteScheduleCommand,
18
- GetScheduleCommand,
19
- ResourceNotFoundException,
20
- } = require('@aws-sdk/client-scheduler');
21
-
22
14
  const { SchedulerServiceInterface } = require('./scheduler-service-interface');
23
- const { awsConfigOptions } = require('../../queues/queuer-util');
15
+
16
+ const SCHEDULER_SDK = '@aws-sdk/client-scheduler';
17
+
18
+ /**
19
+ * Lazily load the AWS EventBridge Scheduler SDK.
20
+ *
21
+ * Requiring `@aws-sdk/client-scheduler` at module top level would put the AWS
22
+ * SDK on the load path of every consumer of `@friggframework/core`, including
23
+ * those using the mock scheduler or no scheduler at all. Loading it here, on
24
+ * construction of the EventBridge adapter, keeps it out of the module-load
25
+ * path. The adapter calls it exactly once, in its constructor, and keeps the
26
+ * classes its methods need on the instance.
27
+ *
28
+ * Only a MODULE_NOT_FOUND for the scheduler SDK itself is rewritten into an
29
+ * actionable message; any other failure (including a missing transitive
30
+ * dependency) is rethrown unchanged so the real cause is not masked.
31
+ *
32
+ * @returns {object} The relevant exports from `@aws-sdk/client-scheduler`.
33
+ */
34
+ function loadSchedulerSdk() {
35
+ try {
36
+ // Keep the literal specifier so bundlers (esbuild) can resolve it.
37
+ return require('@aws-sdk/client-scheduler');
38
+ } catch (error) {
39
+ const isSchedulerSdkMissing =
40
+ error &&
41
+ error.code === 'MODULE_NOT_FOUND' &&
42
+ typeof error.message === 'string' &&
43
+ error.message.includes(SCHEDULER_SDK);
44
+ if (isSchedulerSdkMissing) {
45
+ throw new Error(
46
+ `The EventBridge scheduler requires the "${SCHEDULER_SDK}" package, ` +
47
+ `which is not installed. Install it (\`npm install ${SCHEDULER_SDK}\`) ` +
48
+ 'to use the EventBridge scheduler provider, or use the mock scheduler provider ' +
49
+ '(SCHEDULER_PROVIDER=mock) for local development.',
50
+ { cause: error }
51
+ );
52
+ }
53
+ throw error;
54
+ }
55
+ }
24
56
 
25
57
  class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
26
58
  constructor({ region } = {}) {
27
59
  super();
60
+ const {
61
+ SchedulerClient,
62
+ CreateScheduleCommand,
63
+ DeleteScheduleCommand,
64
+ GetScheduleCommand,
65
+ ResourceNotFoundException,
66
+ } = loadSchedulerSdk();
67
+ this.sdk = {
68
+ CreateScheduleCommand,
69
+ DeleteScheduleCommand,
70
+ GetScheduleCommand,
71
+ ResourceNotFoundException,
72
+ };
28
73
  this.client = new SchedulerClient({
29
74
  region: region || process.env.AWS_REGION || 'us-east-1',
30
- ...awsConfigOptions(),
31
75
  });
32
76
  this.scheduleGroupName =
33
77
  process.env.SCHEDULE_GROUP_NAME || 'frigg-integration-schedules';
@@ -44,7 +88,12 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
44
88
  * @param {Object} params.payload - Message payload
45
89
  * @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
46
90
  */
47
- async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
91
+ async scheduleOneTime({
92
+ scheduleName,
93
+ scheduleAt,
94
+ queueResourceId,
95
+ payload,
96
+ }) {
48
97
  if (!scheduleName) {
49
98
  throw new Error('scheduleName is required');
50
99
  }
@@ -61,8 +110,11 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
61
110
  }
62
111
 
63
112
  // Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
64
- const scheduleExpression = `at(${scheduleAt.toISOString().replace(/\.\d{3}Z$/, '')})`;
113
+ const scheduleExpression = `at(${scheduleAt
114
+ .toISOString()
115
+ .replace(/\.\d{3}Z$/, '')})`;
65
116
 
117
+ const { CreateScheduleCommand } = this.sdk;
66
118
  const command = new CreateScheduleCommand({
67
119
  Name: scheduleName,
68
120
  GroupName: this.scheduleGroupName,
@@ -109,6 +161,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
109
161
  throw new Error('scheduleName is required');
110
162
  }
111
163
 
164
+ const { DeleteScheduleCommand, ResourceNotFoundException } = this.sdk;
112
165
  const command = new DeleteScheduleCommand({
113
166
  Name: scheduleName,
114
167
  GroupName: this.scheduleGroupName,
@@ -143,6 +196,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
143
196
  throw new Error('scheduleName is required');
144
197
  }
145
198
 
199
+ const { GetScheduleCommand, ResourceNotFoundException } = this.sdk;
146
200
  const command = new GetScheduleCommand({
147
201
  Name: scheduleName,
148
202
  GroupName: this.scheduleGroupName,
@@ -155,9 +209,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
155
209
  // Format: at(yyyy-mm-ddThh:mm:ss)
156
210
  let scheduledAt = null;
157
211
  if (response.ScheduleExpression) {
158
- const match = response.ScheduleExpression.match(
159
- /^at\((.+)\)$/
160
- );
212
+ const match = response.ScheduleExpression.match(/^at\((.+)\)$/);
161
213
  if (match) {
162
214
  scheduledAt = new Date(match[1] + 'Z').toISOString();
163
215
  }
@@ -457,6 +457,35 @@ class IntegrationBase {
457
457
  );
458
458
  }
459
459
 
460
+ /**
461
+ * Insert-only mapping write; usable as an atomic claim/lock row.
462
+ * @throws {MappingAlreadyExistsError} If a mapping for sourceId exists
463
+ */
464
+ async createMapping(sourceId, mapping) {
465
+ if (!sourceId) {
466
+ throw new Error(`sourceId must be set`);
467
+ }
468
+ return await this.integrationMappingRepository.createMapping(
469
+ this.id,
470
+ sourceId,
471
+ mapping
472
+ );
473
+ }
474
+
475
+ /**
476
+ * Deletes the mapping for sourceId. A missing mapping is not an error
477
+ * (resolves with deletedCount 0).
478
+ */
479
+ async deleteMapping(sourceId) {
480
+ if (!sourceId) {
481
+ throw new Error(`sourceId must be set`);
482
+ }
483
+ return await this.integrationMappingRepository.deleteMapping(
484
+ this.id,
485
+ sourceId
486
+ );
487
+ }
488
+
460
489
  /**
461
490
  * CHILDREN CAN OVERRIDE THESE CONFIGURATION METHODS
462
491
  */
@@ -528,17 +557,30 @@ class IntegrationBase {
528
557
  }
529
558
  }
530
559
  }
531
- const dynamicUserActions = await this.loadDynamicUserActions();
532
- const filteredDynamicActions = actionType
533
- ? Object.fromEntries(
534
- Object.entries(dynamicUserActions).filter(
535
- ([_, event]) => event.userActionType === actionType
536
- )
537
- )
538
- : dynamicUserActions;
560
+ const dynamicUserActions = await this._loadDynamicUserActionEvents();
561
+ const filteredDynamicActions = Object.fromEntries(
562
+ Object.entries(dynamicUserActions).filter(
563
+ ([_, event]) =>
564
+ event.type === constantsToBeMigrated.types.USER_ACTION &&
565
+ (!actionType || event.userActionType === actionType)
566
+ )
567
+ );
539
568
  return { ...userActions, ...filteredDynamicActions };
540
569
  }
541
570
 
571
+ async _loadDynamicUserActionEvents() {
572
+ const dynamicUserActions = await this.loadDynamicUserActions();
573
+ return Object.fromEntries(
574
+ Object.entries(dynamicUserActions).map(([key, event]) => [
575
+ key,
576
+ {
577
+ ...event,
578
+ type: event.type ?? constantsToBeMigrated.types.USER_ACTION,
579
+ },
580
+ ])
581
+ );
582
+ }
583
+
542
584
  async getActionOptions(actionId, data) {
543
585
  const options = {
544
586
  jsonSchema: {},
@@ -818,7 +860,8 @@ class IntegrationBase {
818
860
 
819
861
  async initialize() {
820
862
  try {
821
- const additionalUserActions = await this.loadDynamicUserActions();
863
+ const additionalUserActions =
864
+ await this._loadDynamicUserActionEvents();
822
865
  this.events = { ...this.events, ...additionalUserActions };
823
866
  } catch (e) {
824
867
  this.addError(e);
@@ -42,6 +42,9 @@ const {
42
42
  } = require('../modules/use-cases/get-entity-options-by-type');
43
43
  const { TestModuleAuth } = require('../modules/use-cases/test-module-auth');
44
44
  const { GetModule } = require('../modules/use-cases/get-module');
45
+ const {
46
+ CreateEntityFromCredential,
47
+ } = require('../modules/use-cases/create-entity-from-credential');
45
48
  const {
46
49
  GetEntityOptionsById,
47
50
  } = require('../modules/use-cases/get-entity-options-by-id');
@@ -198,6 +201,13 @@ function createIntegrationRouter() {
198
201
  getModulesDefinitionFromIntegrationClasses(integrationClasses),
199
202
  });
200
203
 
204
+ const createEntityFromCredential = new CreateEntityFromCredential({
205
+ processAuthorizationCallback,
206
+ credentialRepository,
207
+ moduleDefinitions:
208
+ getModulesDefinitionFromIntegrationClasses(integrationClasses),
209
+ });
210
+
201
211
  const router = express();
202
212
 
203
213
  setIntegrationRoutes(router, authenticateUser, {
@@ -218,6 +228,7 @@ function createIntegrationRouter() {
218
228
  getEntityOptionsById,
219
229
  refreshEntityOptions,
220
230
  processAuthorizationCallback,
231
+ createEntityFromCredential,
221
232
  });
222
233
  return router;
223
234
  }
@@ -246,6 +257,15 @@ function checkRequiredParams(params, requiredKeys) {
246
257
  return returnDict;
247
258
  }
248
259
 
260
+ function assertUserAction(integration, actionId) {
261
+ if (
262
+ !Object.hasOwn(integration.events, actionId) ||
263
+ integration.events[actionId].type !== 'USER_ACTION'
264
+ ) {
265
+ throw Boom.notFound(`User action ${actionId} does not exist`);
266
+ }
267
+ }
268
+
249
269
  /**
250
270
  * Sets up integration-related routes on the provided Express router
251
271
  * @param {express.Router} router - Express router instance to add routes to
@@ -382,6 +402,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
382
402
  params.integrationId,
383
403
  user.getId()
384
404
  );
405
+ assertUserAction(integration, params.actionId);
385
406
 
386
407
  res.json(
387
408
  await integration.send('GET_USER_ACTION_OPTIONS', {
@@ -407,6 +428,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
407
428
  params.integrationId,
408
429
  user.getId()
409
430
  );
431
+ assertUserAction(integration, params.actionId);
410
432
 
411
433
  res.json(
412
434
  await integration.send('REFRESH_USER_ACTION_OPTIONS', {
@@ -428,6 +450,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
428
450
  params.integrationId,
429
451
  user.getId()
430
452
  );
453
+ assertUserAction(integration, params.actionId);
431
454
  res.json(await integration.send(params.actionId, req.body));
432
455
  })
433
456
  );
@@ -502,6 +525,7 @@ function setEntityRoutes(router, authenticateUser, useCases) {
502
525
  getEntityOptionsById,
503
526
  refreshEntityOptions,
504
527
  processAuthorizationCallback,
528
+ createEntityFromCredential,
505
529
  } = useCases;
506
530
 
507
531
  router.route('/api/authorize').get(
@@ -566,35 +590,19 @@ function setEntityRoutes(router, authenticateUser, useCases) {
566
590
  router.route('/api/entity').post(
567
591
  catchAsyncError(async (req, res) => {
568
592
  const user = await authenticateUser.execute(req);
569
- const userId = user.getId();
570
593
  const params = checkRequiredParams(req.body, [
571
594
  'entityType',
572
595
  'data',
573
596
  ]);
574
597
  checkRequiredParams(req.body.data, ['credential_id']);
575
598
 
576
- // May want to pass along the user ID as well so credential ID's can't be fished???
577
- const credential = await getCredentialForUser.execute(
578
- params.data.credential_id,
579
- userId
599
+ res.json(
600
+ await createEntityFromCredential.execute({
601
+ user,
602
+ entityType: params.entityType,
603
+ credentialId: params.data.credential_id,
604
+ })
580
605
  );
581
-
582
- if (!credential) {
583
- throw Boom.badRequest('Invalid credential ID');
584
- }
585
-
586
- const module = await getModuleInstanceFromType.execute(
587
- userId,
588
- params.entityType
589
- );
590
- const entityDetails = await module.getEntityDetails(
591
- module.api,
592
- null,
593
- null,
594
- userId
595
- );
596
-
597
- res.json(await module.findOrCreateEntity(entityDetails));
598
606
  })
599
607
  );
600
608