@friggframework/core 2.0.0--canary.663.8de669c.0 → 2.0.0--canary.686.821f8a3.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 (188) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +20 -10
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/application/index.js +6 -2
  8. package/core/Worker.js +31 -7
  9. package/core/create-handler.js +9 -0
  10. package/credential/repositories/credential-repository-documentdb.js +34 -0
  11. package/credential/repositories/credential-repository-interface.js +15 -0
  12. package/credential/repositories/credential-repository-mongo.js +23 -0
  13. package/credential/repositories/credential-repository-postgres.js +28 -0
  14. package/credential/use-cases/credential-operations-for-user.js +202 -0
  15. package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
  16. package/database/config.js +48 -24
  17. package/database/documentdb-utils.js +6 -1
  18. package/database/encryption/README.md +2 -0
  19. package/database/encryption/encryption-config.js +10 -31
  20. package/database/encryption/encryption-schema-registry.js +121 -24
  21. package/database/encryption/field-encryption-service.js +69 -5
  22. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  23. package/database/organization-where.js +18 -0
  24. package/database/prisma.js +4 -2
  25. package/database/unique-violation.js +25 -0
  26. package/extensions/bootstrap-runner.js +43 -0
  27. package/extensions/extension-loader.js +187 -0
  28. package/extensions/index.js +41 -0
  29. package/extensions/initialize-app.js +123 -0
  30. package/extensions/route-mounter.js +103 -0
  31. package/extensions/schema-composer.js +188 -0
  32. package/generated/prisma-mongodb/edge.js +43 -4
  33. package/generated/prisma-mongodb/index-browser.js +40 -1
  34. package/generated/prisma-mongodb/index.d.ts +4761 -133
  35. package/generated/prisma-mongodb/index.js +43 -4
  36. package/generated/prisma-mongodb/package.json +1 -1
  37. package/generated/prisma-mongodb/schema.prisma +92 -0
  38. package/generated/prisma-mongodb/wasm.js +43 -4
  39. package/generated/prisma-postgresql/edge.js +43 -4
  40. package/generated/prisma-postgresql/index-browser.js +40 -1
  41. package/generated/prisma-postgresql/index.d.ts +4961 -28
  42. package/generated/prisma-postgresql/index.js +43 -4
  43. package/generated/prisma-postgresql/package.json +1 -1
  44. package/generated/prisma-postgresql/schema.prisma +87 -0
  45. package/generated/prisma-postgresql/wasm.js +43 -4
  46. package/handlers/app-definition-loader.js +121 -19
  47. package/handlers/app-handler-helpers.js +25 -3
  48. package/handlers/backend-utils.js +31 -25
  49. package/handlers/middleware/admin-auth.js +14 -1
  50. package/handlers/routers/auth.js +46 -10
  51. package/handlers/routers/health.js +13 -4
  52. package/handlers/routers/integration-defined-routers.js +144 -92
  53. package/handlers/routers/integration-webhook-routers.js +102 -64
  54. package/handlers/workers/integration-defined-workers.js +5 -2
  55. package/index.js +65 -1
  56. package/infrastructure/scheduler/index.js +19 -6
  57. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  58. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  59. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  60. package/integrations/index.js +1 -0
  61. package/integrations/integration-router.js +131 -96
  62. package/integrations/repositories/integration-not-found.js +14 -0
  63. package/integrations/repositories/integration-repository-documentdb.js +35 -3
  64. package/integrations/repositories/integration-repository-interface.js +17 -1
  65. package/integrations/repositories/integration-repository-mongo.js +59 -76
  66. package/integrations/repositories/integration-repository-postgres.js +62 -76
  67. package/integrations/schedule-config.js +80 -0
  68. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  69. package/integrations/use-cases/create-integration.js +55 -20
  70. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  71. package/integrations/use-cases/get-integrations-for-user.js +80 -40
  72. package/integrations/use-cases/index.js +7 -1
  73. package/integrations/use-cases/integration-operations-for-user.js +256 -0
  74. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  75. package/integrations/utils/map-integration-dto.js +43 -14
  76. package/management-api/create-management-api-router.js +49 -0
  77. package/management-api/error-response.js +116 -0
  78. package/management-api/management-api-config.js +151 -0
  79. package/management-api/meta-router.js +76 -0
  80. package/management-api/openapi/build-openapi.js +144 -0
  81. package/management-api/openapi/components.js +408 -0
  82. package/management-api/openapi/v1-operations.js +83 -0
  83. package/management-api/openapi/v2-operations.js +264 -0
  84. package/management-api/route-registry.js +411 -0
  85. package/management-api/test-support/http-client.js +39 -0
  86. package/management-api/use-cases/get-management-api-meta.js +57 -0
  87. package/management-api/v1-deprecation.js +120 -0
  88. package/management-api/v2/create-v2-router.js +85 -0
  89. package/management-api/v2/dependencies.js +281 -0
  90. package/management-api/v2/dto.js +143 -0
  91. package/management-api/v2/handlers/authorization.js +94 -0
  92. package/management-api/v2/handlers/credentials.js +33 -0
  93. package/management-api/v2/handlers/entities.js +77 -0
  94. package/management-api/v2/handlers/integrations.js +128 -0
  95. package/management-api/v2/handlers/proxy.js +34 -0
  96. package/management-api/v2/request.js +85 -0
  97. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  98. package/modules/domain/authorization-session.js +144 -0
  99. package/modules/entity-scope.js +15 -0
  100. package/modules/entity-type-registry.js +311 -0
  101. package/modules/index.js +14 -0
  102. package/modules/module-factory.js +12 -0
  103. package/modules/module.js +53 -2
  104. package/modules/proxy/proxy-errors.js +20 -0
  105. package/modules/proxy/proxy-path.js +179 -0
  106. package/modules/proxy/proxy-policy.js +248 -0
  107. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  108. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  109. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  110. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  111. package/modules/repositories/entity-not-found.js +18 -0
  112. package/modules/repositories/module-repository-documentdb.js +51 -6
  113. package/modules/repositories/module-repository-interface.js +19 -2
  114. package/modules/repositories/module-repository-mongo.js +67 -74
  115. package/modules/repositories/module-repository-postgres.js +66 -74
  116. package/modules/repositories/module-repository.js +2 -1
  117. package/modules/requester/proxy-request.js +244 -0
  118. package/modules/requester/requester.js +27 -2
  119. package/modules/scope-config.js +192 -0
  120. package/modules/scope-policy.js +112 -0
  121. package/modules/scope-resolution.js +288 -0
  122. package/modules/scope-visibility.js +247 -0
  123. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  124. package/modules/tests/doubles/ownership-matching.js +18 -0
  125. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  126. package/modules/use-cases/create-entity-from-credential.js +113 -0
  127. package/modules/use-cases/entity-operations-for-user.js +162 -0
  128. package/modules/use-cases/entity-types.js +139 -0
  129. package/modules/use-cases/execute-entity-proxy-request.js +286 -0
  130. package/modules/use-cases/get-authorization-requirements.js +100 -0
  131. package/modules/use-cases/get-entities-for-user.js +26 -13
  132. package/modules/use-cases/get-entity-module-for-user.js +113 -0
  133. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  134. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  135. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  136. package/modules/use-cases/get-module.js +10 -4
  137. package/modules/use-cases/manage-access.js +21 -0
  138. package/modules/use-cases/multi-step-authorization.js +329 -0
  139. package/modules/use-cases/process-authorization-callback.js +53 -19
  140. package/modules/use-cases/refresh-entity-options.js +10 -4
  141. package/modules/use-cases/test-module-auth.js +10 -4
  142. package/package.json +6 -5
  143. package/prisma-mongodb/schema.prisma +92 -0
  144. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  145. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  146. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  147. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  148. package/prisma-postgresql/schema.prisma +87 -0
  149. package/providers/index.js +23 -0
  150. package/providers/resolve-provider.js +93 -0
  151. package/providers/runtime-detection.js +124 -0
  152. package/queues/index.js +25 -0
  153. package/queues/providers/index.js +11 -0
  154. package/queues/providers/netlify-background-provider.js +150 -0
  155. package/queues/providers/qstash-queue-provider.js +219 -0
  156. package/queues/providers/sqs-queue-provider.js +70 -0
  157. package/queues/queue-client-interface.js +55 -0
  158. package/queues/queue-message-auth.js +193 -0
  159. package/queues/queue-provider-factory.js +101 -0
  160. package/queues/queue-provider.js +65 -0
  161. package/queues/sqs-queue-client.js +81 -0
  162. package/types/index.d.ts +2 -0
  163. package/types/modules/index.d.ts +197 -0
  164. package/types/user/index.d.ts +134 -0
  165. package/user/adopter-jwt-config.js +177 -0
  166. package/user/adopter-jwt-errors.js +59 -0
  167. package/user/adopter-token-verifier.js +122 -0
  168. package/user/app-user-helpers.js +97 -0
  169. package/user/create-user-authentication.js +64 -0
  170. package/user/membership.js +51 -0
  171. package/user/repositories/organization-membership-record.js +19 -0
  172. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  173. package/user/repositories/organization-membership-repository-factory.js +42 -0
  174. package/user/repositories/organization-membership-repository-interface.js +57 -0
  175. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  176. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  177. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  178. package/user/repositories/user-repository-documentdb.js +27 -2
  179. package/user/repositories/user-repository-interface.js +18 -0
  180. package/user/repositories/user-repository-mongo.js +24 -0
  181. package/user/repositories/user-repository-postgres.js +18 -0
  182. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  183. package/user/use-cases/authenticate-user.js +7 -1
  184. package/user/use-cases/ensure-organization-membership.js +92 -0
  185. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  186. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  187. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  188. package/user/user.js +64 -1
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Queue message authentication for HTTP-delivered queues.
3
+ *
4
+ * An SQS-triggered Lambda is invoked by AWS itself, so its events are trusted
5
+ * by the transport. An HTTP-delivered queue (a Netlify Background Function,
6
+ * a QStash destination) is a public URL: anyone who can reach it can post a
7
+ * message. These helpers let the sending adapter prove a message came from
8
+ * Frigg and let the receiving adapter check that proof before anything runs.
9
+ *
10
+ * Scheme (Frigg-signed messages):
11
+ * timestamp = whole seconds since the epoch, as a decimal string
12
+ * signature = 'v1=' + hex(HMAC-SHA256(secret, `${timestamp}.${rawBody}`))
13
+ * sent as the `x-frigg-queue-timestamp` and `x-frigg-queue-signature`
14
+ * headers. The receiver recomputes the HMAC over the raw body it was given,
15
+ * compares in constant time, and refuses a timestamp more than
16
+ * MAX_MESSAGE_AGE_SECONDS away from its own clock (replay window).
17
+ *
18
+ * Fail closed: with no secret configured, a message is accepted unsigned only
19
+ * when FRIGG_QUEUE_ALLOW_UNSIGNED=true AND the environment is not production
20
+ * (isProductionEnvironment; a deployed function always is). Anything else is
21
+ * refused.
22
+ */
23
+ const crypto = require('crypto');
24
+ const { isDeployedRuntime } = require('../providers/runtime-detection');
25
+
26
+ const SIGNING_SECRET_ENV = 'FRIGG_QUEUE_SIGNING_SECRET';
27
+ const ALLOW_UNSIGNED_ENV = 'FRIGG_QUEUE_ALLOW_UNSIGNED';
28
+ const SIGNATURE_HEADER = 'x-frigg-queue-signature';
29
+ const TIMESTAMP_HEADER = 'x-frigg-queue-timestamp';
30
+ const SIGNATURE_VERSION = 'v1';
31
+ const MAX_MESSAGE_AGE_SECONDS = 5 * 60;
32
+
33
+ // Stages core already treats as non-production (database/prisma.js bypasses
34
+ // encryption for the same list).
35
+ const NON_PRODUCTION_STAGES = ['dev', 'test', 'local'];
36
+ const NON_PRODUCTION_NODE_ENVS = ['development', 'test'];
37
+
38
+ /**
39
+ * Production unless the environment says otherwise: an unset STAGE and
40
+ * NODE_ENV count as production, so a missing setting never opens the door.
41
+ * A deployed function (AWS Lambda, or the active provider's platform such as
42
+ * a Netlify Function: providers/runtime-detection) is production whatever
43
+ * STAGE says, so a deployed `dev` stage cannot opt out of signatures.
44
+ *
45
+ * @param {Object} [env=process.env]
46
+ * @returns {boolean}
47
+ */
48
+ function isProductionEnvironment(env = process.env) {
49
+ if (isDeployedRuntime(env)) return true;
50
+ if (NON_PRODUCTION_STAGES.includes(env.STAGE)) return false;
51
+ if (NON_PRODUCTION_NODE_ENVS.includes(env.NODE_ENV)) return false;
52
+ if (env.NETLIFY_DEV === 'true') return false;
53
+ return true;
54
+ }
55
+
56
+ /**
57
+ * Unsigned messages are allowed only by an explicit opt-in outside production.
58
+ *
59
+ * @param {Object} [env=process.env]
60
+ * @returns {boolean}
61
+ */
62
+ function allowsUnsignedMessages(env = process.env) {
63
+ return env[ALLOW_UNSIGNED_ENV] === 'true' && !isProductionEnvironment(env);
64
+ }
65
+
66
+ /**
67
+ * @param {Object} [env=process.env]
68
+ * @returns {string|undefined} the configured signing secret, if non-empty
69
+ */
70
+ function readSigningSecret(env = process.env) {
71
+ const secret = env[SIGNING_SECRET_ENV];
72
+ return typeof secret === 'string' && secret.length > 0 ? secret : undefined;
73
+ }
74
+
75
+ function computeSignature(secret, timestamp, rawBody) {
76
+ const mac = crypto
77
+ .createHmac('sha256', secret)
78
+ .update(`${timestamp}.${rawBody}`)
79
+ .digest('hex');
80
+ return `${SIGNATURE_VERSION}=${mac}`;
81
+ }
82
+
83
+ /**
84
+ * Sign a raw message body.
85
+ *
86
+ * @param {Object} params
87
+ * @param {string} params.body - the exact string that will be sent
88
+ * @param {string} params.secret
89
+ * @param {number} [params.now] - milliseconds since the epoch (default Date.now())
90
+ * @returns {{ [header: string]: string }} headers to add to the request
91
+ */
92
+ function signQueueMessage({ body, secret, now = Date.now() }) {
93
+ if (!secret) {
94
+ throw new Error('A signing secret is required to sign a queue message');
95
+ }
96
+ const timestamp = String(Math.floor(now / 1000));
97
+ return {
98
+ [TIMESTAMP_HEADER]: timestamp,
99
+ [SIGNATURE_HEADER]: computeSignature(secret, timestamp, body),
100
+ };
101
+ }
102
+
103
+ function constantTimeEqual(a, b) {
104
+ const left = Buffer.from(a, 'utf8');
105
+ const right = Buffer.from(b, 'utf8');
106
+ // timingSafeEqual throws on unequal lengths; the length of a v1 signature
107
+ // is fixed, so comparing lengths first leaks nothing secret.
108
+ if (left.length !== right.length) return false;
109
+ return crypto.timingSafeEqual(left, right);
110
+ }
111
+
112
+ /**
113
+ * Verify a Frigg-signed message.
114
+ *
115
+ * @param {Object} params
116
+ * @param {string|null|undefined} params.body - raw body as received
117
+ * @param {string|undefined} params.timestamp - x-frigg-queue-timestamp
118
+ * @param {string|undefined} params.signature - x-frigg-queue-signature
119
+ * @param {string} params.secret
120
+ * @param {number} [params.now] - milliseconds since the epoch
121
+ * @param {number} [params.maxAgeSeconds]
122
+ * @returns {{ ok: true } | { ok: false, reason: string }}
123
+ */
124
+ function verifyQueueMessage({
125
+ body,
126
+ timestamp,
127
+ signature,
128
+ secret,
129
+ now = Date.now(),
130
+ maxAgeSeconds = MAX_MESSAGE_AGE_SECONDS,
131
+ }) {
132
+ if (!secret) return { ok: false, reason: 'signing_secret_not_configured' };
133
+ if (!signature || !timestamp) return { ok: false, reason: 'missing_signature' };
134
+ if (typeof body !== 'string') return { ok: false, reason: 'missing_body' };
135
+ if (!/^\d{1,15}$/.test(timestamp)) return { ok: false, reason: 'invalid_timestamp' };
136
+
137
+ const ageSeconds = Math.abs(Math.floor(now / 1000) - Number(timestamp));
138
+ if (ageSeconds > maxAgeSeconds) return { ok: false, reason: 'stale_timestamp' };
139
+
140
+ const expected = computeSignature(secret, timestamp, body);
141
+ if (!constantTimeEqual(expected, signature)) {
142
+ return { ok: false, reason: 'invalid_signature' };
143
+ }
144
+ return { ok: true };
145
+ }
146
+
147
+ /**
148
+ * Case-insensitive header lookup over a Lambda/Netlify v1 event's headers.
149
+ *
150
+ * @param {Object} event
151
+ * @param {string} name - lower-case header name
152
+ * @returns {string|undefined}
153
+ */
154
+ function readHeader(event, name) {
155
+ const headers = event?.headers || {};
156
+ for (const [key, value] of Object.entries(headers)) {
157
+ if (key.toLowerCase() === name) {
158
+ return Array.isArray(value) ? value[0] : value;
159
+ }
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ /**
165
+ * The raw request body exactly as signed: a string body as is, a base64
166
+ * body decoded to its UTF-8 text. An already-parsed object body cannot be
167
+ * verified (its bytes are gone), so it reads as absent.
168
+ *
169
+ * @param {Object} event
170
+ * @returns {string|null}
171
+ */
172
+ function readRawBody(event) {
173
+ if (typeof event?.body !== 'string') return null;
174
+ if (event.isBase64Encoded) {
175
+ return Buffer.from(event.body, 'base64').toString('utf8');
176
+ }
177
+ return event.body;
178
+ }
179
+
180
+ module.exports = {
181
+ SIGNING_SECRET_ENV,
182
+ ALLOW_UNSIGNED_ENV,
183
+ SIGNATURE_HEADER,
184
+ TIMESTAMP_HEADER,
185
+ MAX_MESSAGE_AGE_SECONDS,
186
+ isProductionEnvironment,
187
+ allowsUnsignedMessages,
188
+ readSigningSecret,
189
+ signQueueMessage,
190
+ verifyQueueMessage,
191
+ readHeader,
192
+ readRawBody,
193
+ };
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Queue Provider Factory
3
+ *
4
+ * Creates a QueueProvider (send / batchSend / parseEvent) for the active
5
+ * platform. From friggframework/frigg#545, adapted: #545 resolved every
6
+ * provider through resolveProvider(), so an AWS app had to install
7
+ * @friggframework/provider-aws. In this stack the AWS SDK is a core
8
+ * dependency, so the built-in queues are created here and only an unknown
9
+ * name goes through the provider plugin system.
10
+ *
11
+ * Priority order for determining the provider:
12
+ * 1. Explicit `provider` option
13
+ * 2. `appDefinition.queue.provider`
14
+ * 3. `QUEUE_PROVIDER` environment variable
15
+ * 4. Default: SQS
16
+ *
17
+ * Built-in names:
18
+ * - 'sqs' | 'aws' -> SqsQueueProvider
19
+ * - 'netlify-background' | 'netlify' -> NetlifyBackgroundProvider
20
+ * - 'qstash' -> QStashQueueProvider
21
+ * Any other name -> require('@friggframework/provider-<name>').QueueProvider
22
+ */
23
+
24
+ const QUEUE_PROVIDERS = {
25
+ SQS: 'sqs',
26
+ NETLIFY_BACKGROUND: 'netlify-background',
27
+ QSTASH: 'qstash',
28
+ };
29
+
30
+ // Platform provider names (appDefinition.provider) that map to a built-in queue.
31
+ const PLATFORM_ALIASES = {
32
+ aws: QUEUE_PROVIDERS.SQS,
33
+ netlify: QUEUE_PROVIDERS.NETLIFY_BACKGROUND,
34
+ };
35
+
36
+ /**
37
+ * Determine the queue provider from the config hierarchy.
38
+ *
39
+ * @param {Object} [options]
40
+ * @param {string} [options.provider]
41
+ * @param {Object} [options.appDefinition]
42
+ * @returns {string|undefined}
43
+ */
44
+ function determineProvider(options = {}) {
45
+ if (options.provider) {
46
+ return options.provider;
47
+ }
48
+ if (options.appDefinition?.queue?.provider) {
49
+ return options.appDefinition.queue.provider;
50
+ }
51
+ if (process.env.QUEUE_PROVIDER) {
52
+ return process.env.QUEUE_PROVIDER;
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ /**
58
+ * Create a queue provider instance.
59
+ *
60
+ * @param {Object} [options]
61
+ * @param {string} [options.provider] - Queue provider name
62
+ * @param {Object} [options.appDefinition] - reads `queue.provider`
63
+ * @param {Object} [options.providerOptions] - passed to the provider constructor
64
+ * @returns {import('./queue-provider').QueueProvider}
65
+ */
66
+ function createQueueProvider(options = {}) {
67
+ const explicit = determineProvider(options);
68
+ const name = PLATFORM_ALIASES[explicit] || explicit || QUEUE_PROVIDERS.SQS;
69
+ const providerOptions = options.providerOptions || {};
70
+
71
+ switch (name) {
72
+ case QUEUE_PROVIDERS.SQS: {
73
+ const { SqsQueueProvider } = require('./providers/sqs-queue-provider');
74
+ return new SqsQueueProvider(providerOptions);
75
+ }
76
+ case QUEUE_PROVIDERS.NETLIFY_BACKGROUND: {
77
+ const {
78
+ NetlifyBackgroundProvider,
79
+ } = require('./providers/netlify-background-provider');
80
+ return new NetlifyBackgroundProvider(providerOptions);
81
+ }
82
+ case QUEUE_PROVIDERS.QSTASH: {
83
+ const { QStashQueueProvider } = require('./providers/qstash-queue-provider');
84
+ return new QStashQueueProvider(providerOptions);
85
+ }
86
+ default: {
87
+ const { resolveProvider } = require('../providers/resolve-provider');
88
+ const provider = resolveProvider(null, { provider: name });
89
+ if (!provider.QueueProvider) {
90
+ throw new Error(`Provider '${provider.name || name}' does not export a QueueProvider`);
91
+ }
92
+ return new provider.QueueProvider(providerOptions);
93
+ }
94
+ }
95
+ }
96
+
97
+ module.exports = {
98
+ createQueueProvider,
99
+ determineProvider,
100
+ QUEUE_PROVIDERS,
101
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Queue Provider Interface (Port)
3
+ *
4
+ * Defines the contract for queue message sending.
5
+ * All queue adapters must extend this interface.
6
+ *
7
+ * Following Frigg's hexagonal architecture pattern:
8
+ * - Port defines WHAT the service does (contract)
9
+ * - Adapters implement HOW (AWS SQS, Netlify Background Functions, QStash, etc.)
10
+ */
11
+ class QueueProvider {
12
+ /**
13
+ * Send a single message to a queue
14
+ *
15
+ * @param {Object} message - Message payload (will be JSON-serialized)
16
+ * @param {string} queueId - Queue identifier (URL, name, or endpoint depending on provider)
17
+ * @returns {Promise<Object>} Provider-specific response
18
+ */
19
+ async send(message, queueId) {
20
+ throw new Error('Method send must be implemented by subclass');
21
+ }
22
+
23
+ /**
24
+ * Send a batch of messages to a queue
25
+ *
26
+ * @param {Object[]} entries - Array of message payloads
27
+ * @param {string} queueId - Queue identifier
28
+ * @returns {Promise<Object>} Provider-specific response
29
+ */
30
+ async batchSend(entries, queueId) {
31
+ throw new Error('Method batchSend must be implemented by subclass');
32
+ }
33
+
34
+ /**
35
+ * Parse an incoming event into an array of message payloads.
36
+ * Each provider has its own event shape (SQS Records, HTTP body, etc.)
37
+ *
38
+ * @param {Object} event - Raw event from the runtime (Lambda event, HTTP request, etc.)
39
+ * @returns {Object[]} Array of parsed message payloads
40
+ */
41
+ parseEvent(event) {
42
+ throw new Error('Method parseEvent must be implemented by subclass');
43
+ }
44
+
45
+ /**
46
+ * Prove an incoming event was sent by Frigg before anything is parsed or
47
+ * dispatched. HTTP-delivered queues (Netlify Background Functions,
48
+ * QStash) are public URLs, so their adapters check a signature here.
49
+ *
50
+ * The default refuses: an adapter that does not know how to verify its
51
+ * events must not have them run. An adapter whose transport already
52
+ * authenticates the caller (SQS triggering a Lambda) overrides this, and
53
+ * must not set `verifiesHttpDelivery`: an HTTP entry point (Netlify's
54
+ * worker-background) consults only adapters that set it to true, since
55
+ * a transport-trust answer says nothing about an HTTP caller.
56
+ *
57
+ * @param {Object} event - Raw event from the runtime
58
+ * @returns {Promise<{ ok: boolean, reason?: string, unsigned?: boolean }>}
59
+ */
60
+ async verifyEvent(event) {
61
+ return { ok: false, reason: 'verification_not_implemented' };
62
+ }
63
+ }
64
+
65
+ module.exports = { QueueProvider };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * SQS Queue Client (Adapter)
3
+ *
4
+ * AWS SQS implementation of QueueClientInterface, used by Worker.
5
+ *
6
+ * In friggframework/frigg#545 this adapter moved to
7
+ * @friggframework/provider-aws and Worker required it to be injected. In
8
+ * this stack the AWS SDK stays a core dependency, so the adapter lives here,
9
+ * Worker defaults to it, and provider-aws re-exports it. The SDK is
10
+ * required on first use, not at module load.
11
+ */
12
+ const { QueueClientInterface } = require('./queue-client-interface');
13
+
14
+ let sqsModule = null;
15
+ function getSqsModule() {
16
+ if (!sqsModule) {
17
+ sqsModule = require('@aws-sdk/client-sqs');
18
+ }
19
+ return sqsModule;
20
+ }
21
+
22
+ /**
23
+ * Client config #545's adapter used: IS_OFFLINE credentials, AWS_REGION and
24
+ * AWS_ENDPOINT.
25
+ */
26
+ function defaultSqsClientConfig() {
27
+ const config = {};
28
+ if (process.env.IS_OFFLINE) {
29
+ config.credentials = {
30
+ accessKeyId: 'test-aws-key',
31
+ secretAccessKey: 'test-aws-secret',
32
+ };
33
+ config.region = 'us-east-1';
34
+ }
35
+ if (!config.region && process.env.AWS_REGION) {
36
+ config.region = process.env.AWS_REGION;
37
+ }
38
+ if (process.env.AWS_ENDPOINT) {
39
+ config.endpoint = process.env.AWS_ENDPOINT;
40
+ }
41
+ return config;
42
+ }
43
+
44
+ class SqsQueueClient extends QueueClientInterface {
45
+ /**
46
+ * @param {Object} [options]
47
+ * @param {Object} [options.clientConfig] - SQSClient config; defaults to
48
+ * defaultSqsClientConfig().
49
+ */
50
+ constructor({ clientConfig } = {}) {
51
+ super();
52
+ this._clientConfig = clientConfig;
53
+ this._sqs = null;
54
+ }
55
+
56
+ _client() {
57
+ if (!this._sqs) {
58
+ const { SQSClient } = getSqsModule();
59
+ this._sqs = new SQSClient(this._clientConfig || defaultSqsClientConfig());
60
+ }
61
+ return this._sqs;
62
+ }
63
+
64
+ async sendMessage(params) {
65
+ const { SendMessageCommand } = getSqsModule();
66
+ return this._client().send(new SendMessageCommand(params));
67
+ }
68
+
69
+ async sendMessageBatch(params) {
70
+ const { SendMessageBatchCommand } = getSqsModule();
71
+ return this._client().send(new SendMessageBatchCommand(params));
72
+ }
73
+
74
+ async getQueueUrl(params) {
75
+ const { GetQueueUrlCommand } = getSqsModule();
76
+ const data = await this._client().send(new GetQueueUrlCommand(params));
77
+ return data.QueueUrl;
78
+ }
79
+ }
80
+
81
+ module.exports = { SqsQueueClient, defaultSqsClientConfig };
package/types/index.d.ts CHANGED
@@ -12,3 +12,5 @@
12
12
  /// <reference path="./eslint-config/index.d.ts" />
13
13
  /// <reference path="./associations/index.d.ts" />
14
14
  /// <reference path="./syncs/index.d.ts" />
15
+ /// <reference path="./user/index.d.ts" />
16
+ /// <reference path="./modules/index.d.ts" />
@@ -0,0 +1,197 @@
1
+ declare module "@friggframework/core" {
2
+ /** Where an entity type comes from: the app's `entities` map or an integration binding it. */
3
+ export type EntityTypeSource =
4
+ | { kind: "app" }
5
+ | { kind: "integration"; name: string };
6
+
7
+ export type EntityScope = "individual" | "organization" | "global";
8
+
9
+ /** App-level settings carried from the `entities` entry; empty for an inferred-only type. */
10
+ export interface EntityTypeSettings {
11
+ scope?: EntityScope | { default?: EntityScope; allow?: EntityScope[] };
12
+ proxy?: Record<string, unknown>;
13
+ display?: Record<string, unknown>;
14
+ }
15
+
16
+ export interface EntityTypeEntry {
17
+ /** The API module definition. */
18
+ definition: any;
19
+ /** Frozen. `{ kind: 'app' }` first when registered, then each binding integration. */
20
+ sources: readonly EntityTypeSource[];
21
+ /** Frozen. */
22
+ settings: Readonly<EntityTypeSettings>;
23
+ }
24
+
25
+ /** Entity type name (the definition's moduleName) to its entry. */
26
+ export type EntityTypeRegistry = Map<string, EntityTypeEntry>;
27
+
28
+ /** One `appDefinition.entities` entry. The key must equal the definition's moduleName (and getName() when defined). */
29
+ export interface EntityRegistration extends EntityTypeSettings {
30
+ definition: any;
31
+ }
32
+
33
+ export interface AppDefinitionEntities {
34
+ /** false turns inference off: every module an integration binds must be registered. Default true. */
35
+ $infer?: boolean;
36
+ [entityType: string]: EntityRegistration | boolean | undefined;
37
+ }
38
+
39
+ /**
40
+ * One level's setting: a scope, or a default plus the scopes a request may
41
+ * choose from (ADR-056 §3.1). `global` is never chosen by a tenant request.
42
+ */
43
+ export type ScopeSetting =
44
+ | EntityScope
45
+ | { default?: EntityScope; allow?: EntityScope[] };
46
+
47
+ /**
48
+ * `appDefinition.ownership` (ADR-056 §3, §3.6). Resolution order for a new
49
+ * connection: request, binding, integration, entity type (`entities[name].scope`),
50
+ * this `scope`, then `organization` for an organization-primary app and
51
+ * `individual` otherwise.
52
+ */
53
+ export interface AppOwnership {
54
+ scope?: ScopeSetting;
55
+ /**
56
+ * `'organization'` (default): an individual entity belongs to the organization
57
+ * it was connected in. `'all'`: one connection per person across every
58
+ * organization, stored with no `organizationId`.
59
+ */
60
+ individualAcross?: "organization" | "all";
61
+ }
62
+
63
+ /** `Definition.ownership` on an integration (ADR-056 §3.1, §3.3). */
64
+ export interface IntegrationOwnership {
65
+ /** Scope every binding of this integration accepts unless it sets its own. */
66
+ scope?: ScopeSetting;
67
+ /** `'derive'` (default): organization when every entity it uses is organization-scoped. */
68
+ owner?: "derive" | "individual" | "organization";
69
+ }
70
+
71
+ /** One operation a module or the app lets the entity proxy forward (ADR-052). */
72
+ export interface ProxyAllowRule {
73
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "*";
74
+ /** Relative to the module's base URL. `:param` is one segment; a trailing `/**` is a subtree. */
75
+ path: string;
76
+ }
77
+
78
+ /** `appDefinition.managementApi.proxy`: the entity proxy, POST /api/v2/entities/:id/proxy (ADR-052). */
79
+ export interface ManagementApiProxyConfig {
80
+ /** Mount the route. Default false. */
81
+ enable?: boolean;
82
+ /** Upstream timeout in ms; can only be lowered from 25000. */
83
+ timeoutMs?: number;
84
+ /** Largest request body in bytes; default 1 MiB, at most 10 MiB. */
85
+ maxRequestBytes?: number;
86
+ /** Largest response body in bytes; can only be lowered from 5 MiB. */
87
+ maxResponseBytes?: number;
88
+ /**
89
+ * Entity scopes the proxy accepts (ADR-056 §3.5). Default `['individual']`.
90
+ * Add `'organization'` to let a member with use access proxy through the
91
+ * organization's shared credential. `global` is never accepted. An unknown,
92
+ * empty or repeated value throws ManagementApiConfigError at load.
93
+ */
94
+ scopes?: Array<Exclude<EntityScope, "global">>;
95
+ /** Per-module allow-list override; `'module'` uses the module's own list. */
96
+ modules?: Record<string, { allow: "module" | ProxyAllowRule[] }>;
97
+ }
98
+
99
+ /** `appDefinition.managementApi` (ADR-052, ADR-053). */
100
+ export interface ManagementApiConfig {
101
+ /** Serve the deprecated v1 routes. Default true. */
102
+ v1?: boolean;
103
+ proxy?: ManagementApiProxyConfig;
104
+ }
105
+
106
+ export interface AppDefinition {
107
+ integrations: any[];
108
+ /** App-level entity type registry (ADR-059). */
109
+ entities?: AppDefinitionEntities;
110
+ /** Who owns what a person connects (ADR-056). */
111
+ ownership?: AppOwnership;
112
+ /** Management API versions and the entity proxy (ADR-052, ADR-053, ADR-056 §3.5). */
113
+ managementApi?: ManagementApiConfig;
114
+ [key: string]: unknown;
115
+ }
116
+
117
+ /** Whose a record is and what the caller may do with it (ADR-056 §3.4). */
118
+ export interface RecordTenancy {
119
+ scope: Exclude<EntityScope, "global">;
120
+ owner: { type: Exclude<EntityScope, "global">; id: string };
121
+ /** Null for an individual entity connected outside an organization, or under `individualAcross: 'all'`. */
122
+ organizationId: string | null;
123
+ /** `manage`: create, reauthorize, delete. `use`: bind it, proxy through it. `view`: metadata only. */
124
+ access: "manage" | "use" | "view";
125
+ }
126
+
127
+ /** Which scope a connection gets, and from which level of the order (ADR-056 §3.1). */
128
+ export interface ResolvedScope {
129
+ scope: EntityScope;
130
+ /** Where `scope` came from. `request` when the request chose within the allowed list. */
131
+ source: "request" | "binding" | "integration" | "entityType" | "app" | "default";
132
+ /** The level that decided what a request may choose from. */
133
+ decidedBy: "binding" | "integration" | "entityType" | "app" | "default";
134
+ allow: EntityScope[];
135
+ }
136
+
137
+ /**
138
+ * First match wins, each level overriding the ones below it. A request may
139
+ * choose only from the deciding level's `allow`; `global` never comes from a
140
+ * tenant request. Throws a Boom 400/403 for a request scope that is not allowed.
141
+ */
142
+ export function resolveScope(levels: {
143
+ request?: EntityScope;
144
+ binding?: ScopeSetting;
145
+ integration?: ScopeSetting;
146
+ entityType?: ScopeSetting;
147
+ app?: ScopeSetting;
148
+ primary?: "individual" | "organization";
149
+ }): ResolvedScope;
150
+
151
+ /** Every binding of every integration with its resolved scope (for tooling that wants to show the chain). */
152
+ export function listBindingScopes(
153
+ appDefinition: Pick<AppDefinition, "integrations" | "ownership">,
154
+ entityTypeRegistry: EntityTypeRegistry,
155
+ primary?: "individual" | "organization"
156
+ ): Array<{
157
+ integration: string;
158
+ binding: string;
159
+ moduleName: string | null;
160
+ scope: EntityScope;
161
+ source: ResolvedScope["source"];
162
+ owner: "derive" | "individual" | "organization";
163
+ }>;
164
+
165
+ /** Invalid ownership or scope setting, thrown at app-definition load. `code` is always `OWNERSHIP_CONFIG_INVALID`. */
166
+ export class OwnershipConfigError extends Error {
167
+ code: "OWNERSHIP_CONFIG_INVALID";
168
+ }
169
+
170
+ /**
171
+ * Builds the registry from `entities` plus the modules integrations bind.
172
+ * Throws EntityRegistryError on an invalid registry.
173
+ */
174
+ export function getEntityTypeRegistry(
175
+ appDefinition?: Pick<AppDefinition, "entities" | "integrations">
176
+ ): EntityTypeRegistry;
177
+
178
+ /** Invalid `managementApi` setting (today: `proxy.scopes`), thrown at app-definition load. */
179
+ export class ManagementApiConfigError extends Error {
180
+ code: "MANAGEMENT_API_CONFIG_INVALID";
181
+ }
182
+
183
+ /**
184
+ * @deprecated ADR-059. Use `getEntityTypeRegistry(appDefinition)` and read
185
+ * each entry's `definition`. Returns the registry's definitions for these
186
+ * integrations (plus registry-only types when `entities` is passed).
187
+ */
188
+ export function getModulesDefinitionFromIntegrationClasses(
189
+ integrationClasses: any[],
190
+ entities?: AppDefinitionEntities
191
+ ): any[];
192
+
193
+ /** Invalid `entities` registry. `code` is always `ENTITY_REGISTRY_INVALID`. */
194
+ export class EntityRegistryError extends Error {
195
+ code: "ENTITY_REGISTRY_INVALID";
196
+ }
197
+ }