@adaptic/backend 0.0.1056 → 0.0.1058
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.
- package/Account.cjs +14 -0
- package/AccountLinkingRequest.cjs +14 -0
- package/AccountRiskMetrics.cjs +11 -0
- package/AdaConversation.cjs +14 -0
- package/Alert.cjs +11 -0
- package/Allocation.cjs +11 -0
- package/AlpacaAccount.cjs +36 -0
- package/Authenticator.cjs +14 -0
- package/AutoFollowRule.cjs +14 -0
- package/BrokerageAccount.cjs +11 -0
- package/Customer.cjs +14 -0
- package/DeskDecision.cjs +11 -0
- package/FeatureFlagOverride.cjs +14 -0
- package/Follow.cjs +14 -0
- package/Fund.cjs +56 -0
- package/FundAssignment.cjs +14 -0
- package/Investor.cjs +14 -0
- package/LinkedProvider.cjs +14 -0
- package/LlmConfiguration.cjs +14 -0
- package/Mandate.cjs +14 -0
- package/MandateApproval.cjs +14 -0
- package/MandateVersion.cjs +14 -0
- package/NotificationDelivery.cjs +14 -0
- package/NotificationPreference.cjs +14 -0
- package/OrgMembership.cjs +14 -0
- package/PolicyOverlay.cjs +64 -0
- package/PushSubscription.cjs +14 -0
- package/RiskEscalationEvent.cjs +33 -0
- package/Session.cjs +14 -0
- package/Strategy.cjs +28 -0
- package/StrategyHealthSnapshot.cjs +11 -0
- package/StrategySubscription.cjs +11 -0
- package/TradingPolicy.cjs +6 -0
- package/User.cjs +11 -0
- package/UserTotp.cjs +14 -0
- package/WaitlistEntry.cjs +14 -0
- package/auth/authorization-map.cjs +306 -0
- package/auth/authorization-map.d.ts +143 -0
- package/auth/cortex-auth-checker.cjs +172 -0
- package/auth/cortex-auth-checker.d.ts +114 -0
- package/auth/credential-fields.cjs +51 -0
- package/auth/credential-fields.d.ts +19 -0
- package/auth/credential-redaction.cjs +134 -0
- package/auth/credential-redaction.d.ts +60 -0
- package/auth/graphql-auth-shadow.cjs +317 -0
- package/auth/graphql-auth-shadow.d.ts +194 -0
- package/auth/membership-write-authority.cjs +131 -0
- package/auth/membership-write-authority.d.ts +110 -0
- package/auth/mutation-authorization.cjs +376 -0
- package/auth/mutation-authorization.d.ts +261 -0
- package/auth/nested-write-inspector.cjs +189 -0
- package/auth/nested-write-inspector.d.ts +94 -0
- package/auth/nested-write-policy.cjs +189 -0
- package/auth/nested-write-policy.d.ts +99 -0
- package/auth/service-token.cjs +316 -0
- package/auth/service-token.d.ts +94 -0
- package/auth/tenancy-scope.cjs +736 -0
- package/auth/tenancy-scope.d.ts +347 -0
- package/auth/token-verifier.cjs +451 -0
- package/auth/token-verifier.d.ts +153 -0
- package/auth/totp.cjs +265 -0
- package/auth/totp.d.ts +111 -0
- package/auth/user-write-content.cjs +116 -0
- package/auth/user-write-content.d.ts +47 -0
- package/auth/ws-auth-context.cjs +75 -0
- package/auth/ws-auth-context.d.ts +69 -0
- package/config/jwtConfig.cjs +52 -0
- package/config/jwtConfig.d.ts +16 -0
- package/config/metrics.cjs +356 -0
- package/config/metrics.d.ts +128 -0
- package/config/persisted-queries.cjs +122 -0
- package/config/persisted-queries.d.ts +40 -0
- package/config/server-only-models.cjs +166 -0
- package/config/server-only-models.d.ts +89 -0
- package/config/tracing.d.ts +24 -0
- package/esm/Account.mjs +14 -0
- package/esm/AccountLinkingRequest.mjs +14 -0
- package/esm/AccountRiskMetrics.mjs +11 -0
- package/esm/AdaConversation.mjs +14 -0
- package/esm/Alert.mjs +11 -0
- package/esm/Allocation.mjs +11 -0
- package/esm/AlpacaAccount.mjs +36 -0
- package/esm/Authenticator.mjs +14 -0
- package/esm/AutoFollowRule.mjs +14 -0
- package/esm/BrokerageAccount.mjs +11 -0
- package/esm/Customer.mjs +14 -0
- package/esm/DeskDecision.mjs +11 -0
- package/esm/FeatureFlagOverride.mjs +14 -0
- package/esm/Follow.mjs +14 -0
- package/esm/Fund.mjs +56 -0
- package/esm/FundAssignment.mjs +14 -0
- package/esm/Investor.mjs +14 -0
- package/esm/LinkedProvider.mjs +14 -0
- package/esm/LlmConfiguration.mjs +14 -0
- package/esm/Mandate.mjs +14 -0
- package/esm/MandateApproval.mjs +14 -0
- package/esm/MandateVersion.mjs +14 -0
- package/esm/NotificationDelivery.mjs +14 -0
- package/esm/NotificationPreference.mjs +14 -0
- package/esm/OrgMembership.mjs +14 -0
- package/esm/PolicyOverlay.mjs +64 -0
- package/esm/PushSubscription.mjs +14 -0
- package/esm/RiskEscalationEvent.mjs +33 -0
- package/esm/Session.mjs +14 -0
- package/esm/Strategy.mjs +28 -0
- package/esm/StrategyHealthSnapshot.mjs +11 -0
- package/esm/StrategySubscription.mjs +11 -0
- package/esm/TradingPolicy.mjs +6 -0
- package/esm/User.mjs +11 -0
- package/esm/UserTotp.mjs +14 -0
- package/esm/WaitlistEntry.mjs +14 -0
- package/esm/generated/typeStrings/PolicyOverlay.d.ts +1 -1
- package/esm/generated/typeStrings/PolicyOverlay.mjs +18 -0
- package/esm/generated/typeStrings/TradingPolicy.d.ts +1 -1
- package/esm/generated/typeStrings/TradingPolicy.mjs +18 -0
- package/esm/generated/typeStrings/index.d.ts +2 -2
- package/esm/generated/typegraphql-prisma/enhance.mjs +18 -18
- package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.mjs +1 -0
- package/esm/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
- package/esm/generated/typegraphql-prisma/models/TradingPolicy.mjs +27 -0
- package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
- package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
- package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
- package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.mjs +7 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
- package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.mjs +7 -0
- package/esm/index.d.ts +1 -0
- package/esm/index.mjs +2 -0
- package/esm/middleware/mutation-account-facts.d.ts +3 -0
- package/esm/middleware/mutation-account-facts.mjs +2 -0
- package/esm/middleware/trading-policy-audit.d.ts +16 -4
- package/esm/middleware/trading-policy-audit.mjs +40 -11
- package/esm/readers/index.d.ts +10 -0
- package/esm/readers/index.mjs +10 -0
- package/esm/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/readers/intraday-lane-prefs.mjs +71 -0
- package/esm/tests/trading-policy-lane-fields-roundtrip.harness.d.ts +14 -0
- package/esm/tests/trading-policy-lane-fields-roundtrip.harness.mjs +107 -0
- package/generated/typeStrings/PolicyOverlay.cjs +18 -0
- package/generated/typeStrings/PolicyOverlay.d.ts +1 -1
- package/generated/typeStrings/TradingPolicy.cjs +18 -0
- package/generated/typeStrings/TradingPolicy.d.ts +1 -1
- package/generated/typeStrings/index.d.ts +2 -2
- package/generated/typegraphql-prisma/enhance.cjs +21 -21
- package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.cjs +1 -0
- package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
- package/generated/typegraphql-prisma/index.cjs +6 -6
- package/generated/typegraphql-prisma/models/TradingPolicy.cjs +7 -0
- package/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
- package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
- package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
- package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
- package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
- package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.cjs +6 -0
- package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
- package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
- package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
- package/index.cjs +2 -0
- package/index.d.ts +1 -0
- package/middleware/audit-log-write-redaction.cjs +143 -0
- package/middleware/audit-log-write-redaction.d.ts +82 -0
- package/middleware/audit-logger.cjs +378 -0
- package/middleware/audit-logger.d.ts +158 -0
- package/middleware/audit-payload-guard.cjs +107 -0
- package/middleware/audit-payload-guard.d.ts +85 -0
- package/middleware/auth.cjs +66 -0
- package/middleware/auth.d.ts +41 -0
- package/middleware/credential-field-guard.cjs +514 -0
- package/middleware/credential-field-guard.d.ts +173 -0
- package/middleware/generated-type-names.cjs +77 -0
- package/middleware/generated-type-names.d.ts +44 -0
- package/middleware/graphql-validation-plugin.cjs +310 -0
- package/middleware/graphql-validation-plugin.d.ts +98 -0
- package/middleware/guard-log-throttle.cjs +89 -0
- package/middleware/guard-log-throttle.d.ts +80 -0
- package/middleware/index.cjs +57 -0
- package/middleware/index.d.ts +14 -0
- package/middleware/input-validator.cjs +220 -0
- package/middleware/input-validator.d.ts +63 -0
- package/middleware/mandate-version-validation.cjs +131 -0
- package/middleware/mandate-version-validation.d.ts +41 -0
- package/middleware/mutation-account-facts.cjs +223 -0
- package/middleware/mutation-account-facts.d.ts +143 -0
- package/middleware/mutation-auth-guard.cjs +536 -0
- package/middleware/mutation-auth-guard.d.ts +100 -0
- package/middleware/mutation-membership-facts.cjs +276 -0
- package/middleware/mutation-membership-facts.d.ts +133 -0
- package/middleware/mutation-tenant-facts.cjs +132 -0
- package/middleware/mutation-tenant-facts.d.ts +81 -0
- package/middleware/query-complexity.cjs +182 -0
- package/middleware/query-complexity.d.ts +56 -0
- package/middleware/rate-limiter.cjs +223 -0
- package/middleware/rate-limiter.d.ts +93 -0
- package/middleware/rate-tier.cjs +111 -0
- package/middleware/rate-tier.d.ts +56 -0
- package/middleware/soft-delete.cjs +175 -0
- package/middleware/soft-delete.d.ts +146 -0
- package/middleware/tenancy-scoping.cjs +229 -0
- package/middleware/tenancy-scoping.d.ts +67 -0
- package/middleware/trading-policy-audit.cjs +353 -0
- package/middleware/trading-policy-audit.d.ts +184 -0
- package/middleware/types.cjs +17 -0
- package/middleware/types.d.ts +87 -0
- package/middleware/validation-examples.cjs +398 -0
- package/middleware/validation-examples.d.ts +76 -0
- package/package.json +10 -2
- package/readers/index.cjs +15 -0
- package/readers/index.d.ts +10 -0
- package/readers/intraday-lane-prefs.cjs +76 -0
- package/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
- package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -570
- package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
- package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
- package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
- package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
- package/health.cjs +0 -274
- package/server.cjs +0 -607
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Which nested relation writes a `user` principal may make. Pure; no I/O.
|
|
4
|
+
*
|
|
5
|
+
* ## Why each hop is judged on its own
|
|
6
|
+
*
|
|
7
|
+
* A root mutation's authorization proves one thing: the caller may write THAT
|
|
8
|
+
* row (they own the account, it is their user row, it sits in a tenant they
|
|
9
|
+
* are entitled to). A nested write walks from that row along a relation into
|
|
10
|
+
* another model's rows, and from there into another's. Nothing about the
|
|
11
|
+
* root's proof survives the first hop into rows the caller does not own:
|
|
12
|
+
* `updateOneUser(self) → managedFunds → operator.update` edits a different
|
|
13
|
+
* person's user row, and `updateOneAlpacaAccount(own) → brokerageAccount →
|
|
14
|
+
* fund → …` reaches every account the fund is bridged to.
|
|
15
|
+
*
|
|
16
|
+
* So each nested container is decided against the model that HOLDS the
|
|
17
|
+
* relation (its parent), the relation itself, whether the parent row is being
|
|
18
|
+
* created or updated, and its depth — never against the root. The rule is an
|
|
19
|
+
* allowlist; everything not named here is refused:
|
|
20
|
+
*
|
|
21
|
+
* - **Entitlement rows are never written nested.** `OrgMembership`,
|
|
22
|
+
* `FundAssignment` and a fund's `manager` / `operator` relations are what
|
|
23
|
+
* fund entitlement is read from (`resolveEntitlement`), and fund
|
|
24
|
+
* entitlement authorises writes to every account bridged to the fund. A
|
|
25
|
+
* nested write to them has no scope check of its own, so it would let a
|
|
26
|
+
* caller mint the entitlement it is then checked against.
|
|
27
|
+
* - **`connect` may only move the parent row, never the connected one.** When
|
|
28
|
+
* the foreign key sits on the parent (`FundAssignment.fund`), a `connect`
|
|
29
|
+
* writes only the parent; when it sits on the connected row
|
|
30
|
+
* (`Organization.funds`, `User.alpacaAccounts`), the connected row — someone
|
|
31
|
+
* else's — is re-pointed. Only the first kind is admitted, and then only:
|
|
32
|
+
* - into a user-authored (`authenticated`) model;
|
|
33
|
+
* - into a tenant-scoped model while the parent row is being CREATED (the
|
|
34
|
+
* root's tenant check reads exactly that connect); re-tenanting an
|
|
35
|
+
* existing row is refused;
|
|
36
|
+
* - into the caller's own `User` row while the parent is being created;
|
|
37
|
+
* - into any `User` row as the member of a root `OrgMembership` or
|
|
38
|
+
* `FundAssignment` create: adding a person to a team is what those
|
|
39
|
+
* creates are for, and the root decision reads that connect and requires
|
|
40
|
+
* authority over the tenant (`./membership-write-authority.ts`);
|
|
41
|
+
* - into `AlpacaAccount` only as the policy's own account on a root
|
|
42
|
+
* TradingPolicy create, whose ownership check reads that connect.
|
|
43
|
+
* - **Content writes into an owned model** (account, policy, user row) are
|
|
44
|
+
* admitted only on the three edges whose target row is the ROOT row's own
|
|
45
|
+
* counterpart, and only at depth 1: an account's own policy, a policy's own
|
|
46
|
+
* account, and a brokerage binding's own engine account. The root decision
|
|
47
|
+
* has already authorised that exact account.
|
|
48
|
+
* - **New user-authored rows** (`create` into an `authenticated` model) may be
|
|
49
|
+
* attached anywhere the walk is otherwise admitted.
|
|
50
|
+
* - `set`, `disconnect`, `delete`, `deleteMany`, `updateMany`,
|
|
51
|
+
* `connectOrCreate` and `createMany` are never admitted nested.
|
|
52
|
+
*
|
|
53
|
+
* @module auth/nested-write-policy
|
|
54
|
+
*/
|
|
55
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
56
|
+
exports.ENTITLEMENT_RELATIONS = exports.ENTITLEMENT_MODELS = void 0;
|
|
57
|
+
exports.nestedWriteRefusalForUser = nestedWriteRefusalForUser;
|
|
58
|
+
exports.writesNestedModelRows = writesNestedModelRows;
|
|
59
|
+
exports.firstNestedRefusal = firstNestedRefusal;
|
|
60
|
+
const mutation_authorization_1 = require("./mutation-authorization.cjs");
|
|
61
|
+
/** The models fund entitlement is read from. */
|
|
62
|
+
exports.ENTITLEMENT_MODELS = new Set(['OrgMembership', 'FundAssignment']);
|
|
63
|
+
/** The relations that name a fund's manager or operator, from either side. */
|
|
64
|
+
exports.ENTITLEMENT_RELATIONS = new Set([
|
|
65
|
+
'Fund.manager',
|
|
66
|
+
'Fund.operator',
|
|
67
|
+
'User.managedFunds',
|
|
68
|
+
'User.operatedFunds',
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* `Parent.relation` edges on which a user may write an owned model's content,
|
|
72
|
+
* with the operations allowed. Each edge reaches the root row's own
|
|
73
|
+
* counterpart, which the root decision has already authorised.
|
|
74
|
+
*/
|
|
75
|
+
const OWNED_CONTENT_EDGES = new Map([
|
|
76
|
+
['AlpacaAccount.tradingPolicy', new Set(['create', 'update', 'upsert'])],
|
|
77
|
+
['TradingPolicy.alpacaAccount', new Set(['update'])],
|
|
78
|
+
['BrokerageAccount.engineAccount', new Set(['create', 'update', 'upsert'])],
|
|
79
|
+
]);
|
|
80
|
+
/**
|
|
81
|
+
* A model's policy as the nested rules read it. `mandate_tenant` is a ROOT
|
|
82
|
+
* rule (the addressed version's mandate must be in the caller's tenant);
|
|
83
|
+
* nested, a mandate version keeps the `authenticated` treatment it had.
|
|
84
|
+
*/
|
|
85
|
+
function nestedPolicyOf(model) {
|
|
86
|
+
const policy = (0, mutation_authorization_1.ruleFor)(model).policy;
|
|
87
|
+
return policy === 'mandate_tenant' ? 'authenticated' : policy;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether a connect names the member of a root entitlement-row create. The
|
|
91
|
+
* root's own decision reads the member from this connect and holds the
|
|
92
|
+
* caller to authority over the tenant, so the hop needs no check of its own.
|
|
93
|
+
*/
|
|
94
|
+
function isRootMemberConnect(write) {
|
|
95
|
+
return (write.depth === 1 &&
|
|
96
|
+
write.parentMode === 'create' &&
|
|
97
|
+
write.relation === 'user' &&
|
|
98
|
+
exports.ENTITLEMENT_MODELS.has(write.parentModel) &&
|
|
99
|
+
write.connectIds !== null &&
|
|
100
|
+
write.connectIds.length === 1);
|
|
101
|
+
}
|
|
102
|
+
function connectAllowed(write, callerId, relations) {
|
|
103
|
+
if (relations.fkOnParent(write.parentModel, write.relation) !== true)
|
|
104
|
+
return false;
|
|
105
|
+
const policy = nestedPolicyOf(write.model);
|
|
106
|
+
switch (policy) {
|
|
107
|
+
case 'self':
|
|
108
|
+
if (isRootMemberConnect(write))
|
|
109
|
+
return true;
|
|
110
|
+
return (write.parentMode === 'create' &&
|
|
111
|
+
write.connectIds !== null &&
|
|
112
|
+
write.connectIds.length > 0 &&
|
|
113
|
+
write.connectIds.every((id) => id === callerId));
|
|
114
|
+
case 'authenticated':
|
|
115
|
+
return true;
|
|
116
|
+
case 'tenant_scoped':
|
|
117
|
+
return write.parentMode === 'create';
|
|
118
|
+
case 'account_owned':
|
|
119
|
+
return (write.depth === 1 &&
|
|
120
|
+
write.parentMode === 'create' &&
|
|
121
|
+
`${write.parentModel}.${write.relation}` === 'TradingPolicy.alpacaAccount');
|
|
122
|
+
default:
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function contentWriteAllowed(write, operation) {
|
|
127
|
+
var _a;
|
|
128
|
+
const policy = nestedPolicyOf(write.model);
|
|
129
|
+
if (operation === 'create' && policy === 'authenticated')
|
|
130
|
+
return true;
|
|
131
|
+
if (policy !== 'account_owned' || write.depth !== 1)
|
|
132
|
+
return false;
|
|
133
|
+
return ((_a = OWNED_CONTENT_EDGES.get(`${write.parentModel}.${write.relation}`)) === null || _a === void 0 ? void 0 : _a.has(operation)) === true;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Whether a user principal may make one nested write.
|
|
137
|
+
*
|
|
138
|
+
* @param write - The nested container, with its parent context.
|
|
139
|
+
* @param callerId - The user principal's subject (`User.id`).
|
|
140
|
+
* @param relations - Foreign-key placement per relation.
|
|
141
|
+
* @returns `null` when the write is admitted, otherwise the refusal reason.
|
|
142
|
+
*/
|
|
143
|
+
function nestedWriteRefusalForUser(write, callerId, relations) {
|
|
144
|
+
if (exports.ENTITLEMENT_MODELS.has(write.model) ||
|
|
145
|
+
exports.ENTITLEMENT_RELATIONS.has(`${write.parentModel}.${write.relation}`)) {
|
|
146
|
+
return 'nested_entitlement_write';
|
|
147
|
+
}
|
|
148
|
+
for (const operation of write.operations) {
|
|
149
|
+
const allowed = operation === 'connect'
|
|
150
|
+
? connectAllowed(write, callerId, relations)
|
|
151
|
+
: operation === 'create' || operation === 'update' || operation === 'upsert'
|
|
152
|
+
? contentWriteAllowed(write, operation)
|
|
153
|
+
: false;
|
|
154
|
+
if (!allowed)
|
|
155
|
+
return 'nested_write_not_user_writable';
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Whether a nested container writes rows of its OWN model. A container whose
|
|
161
|
+
* only operation is `connect` over a relation whose foreign key sits on the
|
|
162
|
+
* parent writes only the parent row (it sets the parent's key); anything else
|
|
163
|
+
* — a create, an update, a connect that re-points the connected row, a
|
|
164
|
+
* disconnect — writes the nested model. The guard decides a mutation at the
|
|
165
|
+
* strictest mode among the models it writes, so this is what decides whether
|
|
166
|
+
* an escalated nested model governs the mutation.
|
|
167
|
+
*
|
|
168
|
+
* @param write - The nested container.
|
|
169
|
+
* @param relations - Foreign-key placement per relation.
|
|
170
|
+
*/
|
|
171
|
+
function writesNestedModelRows(write, relations) {
|
|
172
|
+
const onlyConnect = write.operations.length > 0 && write.operations.every((op) => op === 'connect');
|
|
173
|
+
return !(onlyConnect && relations.fkOnParent(write.parentModel, write.relation) === true);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The first refusal among a mutation's nested writes, entitlement refusals
|
|
177
|
+
* first (they are the more specific signal), or `null` when all are admitted.
|
|
178
|
+
*/
|
|
179
|
+
function firstNestedRefusal(writes, callerId, relations) {
|
|
180
|
+
let refusal = null;
|
|
181
|
+
for (const write of writes) {
|
|
182
|
+
const reason = nestedWriteRefusalForUser(write, callerId, relations);
|
|
183
|
+
if (reason === 'nested_entitlement_write')
|
|
184
|
+
return reason;
|
|
185
|
+
refusal !== null && refusal !== void 0 ? refusal : (refusal = reason);
|
|
186
|
+
}
|
|
187
|
+
return refusal;
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=nested-write-policy.js.map
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which nested relation writes a `user` principal may make. Pure; no I/O.
|
|
3
|
+
*
|
|
4
|
+
* ## Why each hop is judged on its own
|
|
5
|
+
*
|
|
6
|
+
* A root mutation's authorization proves one thing: the caller may write THAT
|
|
7
|
+
* row (they own the account, it is their user row, it sits in a tenant they
|
|
8
|
+
* are entitled to). A nested write walks from that row along a relation into
|
|
9
|
+
* another model's rows, and from there into another's. Nothing about the
|
|
10
|
+
* root's proof survives the first hop into rows the caller does not own:
|
|
11
|
+
* `updateOneUser(self) → managedFunds → operator.update` edits a different
|
|
12
|
+
* person's user row, and `updateOneAlpacaAccount(own) → brokerageAccount →
|
|
13
|
+
* fund → …` reaches every account the fund is bridged to.
|
|
14
|
+
*
|
|
15
|
+
* So each nested container is decided against the model that HOLDS the
|
|
16
|
+
* relation (its parent), the relation itself, whether the parent row is being
|
|
17
|
+
* created or updated, and its depth — never against the root. The rule is an
|
|
18
|
+
* allowlist; everything not named here is refused:
|
|
19
|
+
*
|
|
20
|
+
* - **Entitlement rows are never written nested.** `OrgMembership`,
|
|
21
|
+
* `FundAssignment` and a fund's `manager` / `operator` relations are what
|
|
22
|
+
* fund entitlement is read from (`resolveEntitlement`), and fund
|
|
23
|
+
* entitlement authorises writes to every account bridged to the fund. A
|
|
24
|
+
* nested write to them has no scope check of its own, so it would let a
|
|
25
|
+
* caller mint the entitlement it is then checked against.
|
|
26
|
+
* - **`connect` may only move the parent row, never the connected one.** When
|
|
27
|
+
* the foreign key sits on the parent (`FundAssignment.fund`), a `connect`
|
|
28
|
+
* writes only the parent; when it sits on the connected row
|
|
29
|
+
* (`Organization.funds`, `User.alpacaAccounts`), the connected row — someone
|
|
30
|
+
* else's — is re-pointed. Only the first kind is admitted, and then only:
|
|
31
|
+
* - into a user-authored (`authenticated`) model;
|
|
32
|
+
* - into a tenant-scoped model while the parent row is being CREATED (the
|
|
33
|
+
* root's tenant check reads exactly that connect); re-tenanting an
|
|
34
|
+
* existing row is refused;
|
|
35
|
+
* - into the caller's own `User` row while the parent is being created;
|
|
36
|
+
* - into any `User` row as the member of a root `OrgMembership` or
|
|
37
|
+
* `FundAssignment` create: adding a person to a team is what those
|
|
38
|
+
* creates are for, and the root decision reads that connect and requires
|
|
39
|
+
* authority over the tenant (`./membership-write-authority.ts`);
|
|
40
|
+
* - into `AlpacaAccount` only as the policy's own account on a root
|
|
41
|
+
* TradingPolicy create, whose ownership check reads that connect.
|
|
42
|
+
* - **Content writes into an owned model** (account, policy, user row) are
|
|
43
|
+
* admitted only on the three edges whose target row is the ROOT row's own
|
|
44
|
+
* counterpart, and only at depth 1: an account's own policy, a policy's own
|
|
45
|
+
* account, and a brokerage binding's own engine account. The root decision
|
|
46
|
+
* has already authorised that exact account.
|
|
47
|
+
* - **New user-authored rows** (`create` into an `authenticated` model) may be
|
|
48
|
+
* attached anywhere the walk is otherwise admitted.
|
|
49
|
+
* - `set`, `disconnect`, `delete`, `deleteMany`, `updateMany`,
|
|
50
|
+
* `connectOrCreate` and `createMany` are never admitted nested.
|
|
51
|
+
*
|
|
52
|
+
* @module auth/nested-write-policy
|
|
53
|
+
*/
|
|
54
|
+
import { type MutationAuthReason } from './mutation-authorization';
|
|
55
|
+
import type { NestedWrite } from './nested-write-inspector';
|
|
56
|
+
/** Where a relation's foreign key lives, as the Prisma data model states it. */
|
|
57
|
+
export interface RelationFacts {
|
|
58
|
+
/**
|
|
59
|
+
* Whether `model.relation` holds the foreign key (Prisma
|
|
60
|
+
* `relationFromFields` is non-empty on that side). `undefined` for a
|
|
61
|
+
* relation the facts do not know, which every rule treats as "not on the
|
|
62
|
+
* parent" — the refusing answer.
|
|
63
|
+
*/
|
|
64
|
+
fkOnParent(model: string, relation: string): boolean | undefined;
|
|
65
|
+
}
|
|
66
|
+
/** The models fund entitlement is read from. */
|
|
67
|
+
export declare const ENTITLEMENT_MODELS: ReadonlySet<string>;
|
|
68
|
+
/** The relations that name a fund's manager or operator, from either side. */
|
|
69
|
+
export declare const ENTITLEMENT_RELATIONS: ReadonlySet<string>;
|
|
70
|
+
/** Why a nested write was refused (a bounded metric label). */
|
|
71
|
+
export type NestedWriteRefusal = Extract<MutationAuthReason, 'nested_write_not_user_writable' | 'nested_entitlement_write'>;
|
|
72
|
+
/**
|
|
73
|
+
* Whether a user principal may make one nested write.
|
|
74
|
+
*
|
|
75
|
+
* @param write - The nested container, with its parent context.
|
|
76
|
+
* @param callerId - The user principal's subject (`User.id`).
|
|
77
|
+
* @param relations - Foreign-key placement per relation.
|
|
78
|
+
* @returns `null` when the write is admitted, otherwise the refusal reason.
|
|
79
|
+
*/
|
|
80
|
+
export declare function nestedWriteRefusalForUser(write: NestedWrite, callerId: string, relations: RelationFacts): NestedWriteRefusal | null;
|
|
81
|
+
/**
|
|
82
|
+
* Whether a nested container writes rows of its OWN model. A container whose
|
|
83
|
+
* only operation is `connect` over a relation whose foreign key sits on the
|
|
84
|
+
* parent writes only the parent row (it sets the parent's key); anything else
|
|
85
|
+
* — a create, an update, a connect that re-points the connected row, a
|
|
86
|
+
* disconnect — writes the nested model. The guard decides a mutation at the
|
|
87
|
+
* strictest mode among the models it writes, so this is what decides whether
|
|
88
|
+
* an escalated nested model governs the mutation.
|
|
89
|
+
*
|
|
90
|
+
* @param write - The nested container.
|
|
91
|
+
* @param relations - Foreign-key placement per relation.
|
|
92
|
+
*/
|
|
93
|
+
export declare function writesNestedModelRows(write: NestedWrite, relations: RelationFacts): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* The first refusal among a mutation's nested writes, entitlement refusals
|
|
96
|
+
* first (they are the more specific signal), or `null` when all are admitted.
|
|
97
|
+
*/
|
|
98
|
+
export declare function firstNestedRefusal(writes: readonly NestedWrite[], callerId: string, relations: RelationFacts): NestedWriteRefusal | null;
|
|
99
|
+
//# sourceMappingURL=nested-write-policy.d.ts.map
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Service-to-service principal minted from a dedicated HS256 secret.
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS EXISTS AS A THIRD PATH RATHER THAN REUSING EITHER EXISTING ONE.
|
|
6
|
+
* `verifyBackendToken` already knows two ways to arrive at a non-user caller,
|
|
7
|
+
* and both are wrong for a long-lived internal service:
|
|
8
|
+
*
|
|
9
|
+
* - `SERVER_AUTH_TOKEN` is an exact string match against a static value. It
|
|
10
|
+
* never expires, carries no audience, names no caller, and cannot be
|
|
11
|
+
* rotated without a simultaneous restart of every holder. A copy taken
|
|
12
|
+
* from a log or a process listing is a permanent credential.
|
|
13
|
+
* - An app-issued JWT verifies against `jwtSecret` — the SAME secret that
|
|
14
|
+
* signs end-user sessions. A service credential keyed on it would make
|
|
15
|
+
* every holder of a user secret able to mint a service identity and vice
|
|
16
|
+
* versa, and it yields `kind: "user"`, which is then subject to
|
|
17
|
+
* per-user tenancy scoping that a service must not be subject to.
|
|
18
|
+
*
|
|
19
|
+
* So the service path is keyed on `BACKEND_SERVICE_JWT_SECRET`, a secret whose
|
|
20
|
+
* ONLY purpose is service identity. It is deliberately distinct from
|
|
21
|
+
* `JWT_SECRET` so that the blast radius of either one leaking stops at that
|
|
22
|
+
* one trust domain, and the verifier refuses to run if the two are ever set to
|
|
23
|
+
* the same value — a configuration that would silently collapse the
|
|
24
|
+
* separation this module exists to create.
|
|
25
|
+
*
|
|
26
|
+
* ABSENCE DISABLES THE PATH; IT NEVER WIDENS IT. With no secret provisioned
|
|
27
|
+
* `verifyServiceToken` returns `null` and the caller falls through to the
|
|
28
|
+
* existing paths, which reject. A service that cannot prove itself is refused,
|
|
29
|
+
* never admitted.
|
|
30
|
+
*
|
|
31
|
+
* @module auth/service-token
|
|
32
|
+
*/
|
|
33
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
34
|
+
if (k2 === undefined) k2 = k;
|
|
35
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
36
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
37
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
38
|
+
}
|
|
39
|
+
Object.defineProperty(o, k2, desc);
|
|
40
|
+
}) : (function(o, m, k, k2) {
|
|
41
|
+
if (k2 === undefined) k2 = k;
|
|
42
|
+
o[k2] = m[k];
|
|
43
|
+
}));
|
|
44
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
45
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
46
|
+
}) : function(o, v) {
|
|
47
|
+
o["default"] = v;
|
|
48
|
+
});
|
|
49
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
50
|
+
var ownKeys = function(o) {
|
|
51
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
52
|
+
var ar = [];
|
|
53
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
54
|
+
return ar;
|
|
55
|
+
};
|
|
56
|
+
return ownKeys(o);
|
|
57
|
+
};
|
|
58
|
+
return function (mod) {
|
|
59
|
+
if (mod && mod.__esModule) return mod;
|
|
60
|
+
var result = {};
|
|
61
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
62
|
+
__setModuleDefault(result, mod);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
})();
|
|
66
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
67
|
+
exports.MAX_SERVICE_TOKEN_CLOCK_SKEW_SEC = exports.MAX_SERVICE_TOKEN_LIFETIME_SEC = exports.MINIMUM_SERVICE_SECRET_LENGTH = exports.SERVICE_TOKEN_AUDIENCE = exports.SERVICE_TOKEN_ISSUER = void 0;
|
|
68
|
+
exports.verifyServiceToken = verifyServiceToken;
|
|
69
|
+
const jsonwebtoken_1 = __importStar(require("jsonwebtoken"));
|
|
70
|
+
const jwtConfig_1 = require("../config/jwtConfig.cjs");
|
|
71
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
72
|
+
const token_verifier_1 = require("./token-verifier.cjs");
|
|
73
|
+
/**
|
|
74
|
+
* Issuer every service credential must carry.
|
|
75
|
+
*
|
|
76
|
+
* Pinned rather than free-form so a token minted for some other HS256 system
|
|
77
|
+
* that happens to share the secret cannot be replayed here.
|
|
78
|
+
*/
|
|
79
|
+
exports.SERVICE_TOKEN_ISSUER = 'adaptic-service';
|
|
80
|
+
/**
|
|
81
|
+
* Audience every service credential must carry.
|
|
82
|
+
*
|
|
83
|
+
* This backend is the only intended recipient. Binding the audience is what
|
|
84
|
+
* stops a credential minted for a sibling service from being replayed against
|
|
85
|
+
* the data tier.
|
|
86
|
+
*/
|
|
87
|
+
exports.SERVICE_TOKEN_AUDIENCE = 'adaptic-backend';
|
|
88
|
+
/** Minimum length for the dedicated service secret, in characters. */
|
|
89
|
+
exports.MINIMUM_SERVICE_SECRET_LENGTH = 32;
|
|
90
|
+
/**
|
|
91
|
+
* Largest lifetime this backend will honour on a service credential, seconds.
|
|
92
|
+
*
|
|
93
|
+
* A credential's own `exp` bounds the replay window on a leak, so a minter is
|
|
94
|
+
* free to choose a shorter one — but it may not choose a longer one and
|
|
95
|
+
* thereby re-create the non-expiring static bearer this path replaces. One
|
|
96
|
+
* hour is comfortably above the 15-minute lifetime the engine mints and far
|
|
97
|
+
* below "effectively permanent".
|
|
98
|
+
*/
|
|
99
|
+
exports.MAX_SERVICE_TOKEN_LIFETIME_SEC = 3600;
|
|
100
|
+
/**
|
|
101
|
+
* How far in the future, seconds, a credential's `iat` may sit before it is
|
|
102
|
+
* refused.
|
|
103
|
+
*
|
|
104
|
+
* The lifetime ceiling is measured from `iat`, so an `iat` the verifier does
|
|
105
|
+
* not bound would let a secret holder date a token years ahead and hold a
|
|
106
|
+
* credential valid until then. One minute absorbs ordinary clock drift between
|
|
107
|
+
* a minter and this host and nothing more.
|
|
108
|
+
*/
|
|
109
|
+
exports.MAX_SERVICE_TOKEN_CLOCK_SKEW_SEC = 60;
|
|
110
|
+
/**
|
|
111
|
+
* Validate one raw secret value, or `null` when it cannot serve as one.
|
|
112
|
+
*
|
|
113
|
+
* @param name - Env var name, for the operator-facing log line.
|
|
114
|
+
* @param raw - The raw env value.
|
|
115
|
+
* @returns The trimmed secret, or `null` when unset, blank, or too short.
|
|
116
|
+
*/
|
|
117
|
+
function readSecret(name, raw) {
|
|
118
|
+
if (typeof raw !== 'string')
|
|
119
|
+
return null;
|
|
120
|
+
const secret = raw.trim();
|
|
121
|
+
if (secret.length === 0)
|
|
122
|
+
return null;
|
|
123
|
+
if (secret.length < exports.MINIMUM_SERVICE_SECRET_LENGTH) {
|
|
124
|
+
logger_1.logger.error(`[auth] ${name} is set but shorter than the minimum ` +
|
|
125
|
+
`${exports.MINIMUM_SERVICE_SECRET_LENGTH} characters; it will not be used to verify service tokens.`, { secretLength: secret.length });
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return secret;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Resolve the service secrets to try, in order, or `null` when the path is not
|
|
132
|
+
* provisioned.
|
|
133
|
+
*
|
|
134
|
+
* Read per call rather than cached at import so an operator rotating the
|
|
135
|
+
* Railway variable takes effect on the next request rather than the next
|
|
136
|
+
* restart — the same discipline `SERVER_AUTH_TOKEN` already follows.
|
|
137
|
+
*
|
|
138
|
+
* WHY A SECOND SLOT. With one secret, rotation means every minter and this
|
|
139
|
+
* verifier must change at the same instant or service calls fail in between.
|
|
140
|
+
* `BACKEND_SERVICE_JWT_SECRET_PREVIOUS` lets the verifier accept the outgoing
|
|
141
|
+
* key while minters move to the new one, so the swap is: set PREVIOUS to the
|
|
142
|
+
* current value and the primary to the new one, move the minters, watch the
|
|
143
|
+
* `previous` log line drain to zero, then unset PREVIOUS.
|
|
144
|
+
*
|
|
145
|
+
* The previous slot never stands alone: with no valid primary the whole path
|
|
146
|
+
* stays disabled, so an operator cannot half-finish a rotation into a state
|
|
147
|
+
* where only the retiring key is honoured.
|
|
148
|
+
*
|
|
149
|
+
* @returns The slots to try, primary first, or `null` when unprovisioned.
|
|
150
|
+
*/
|
|
151
|
+
function resolveServiceSecrets() {
|
|
152
|
+
var _a;
|
|
153
|
+
const primary = readSecret('BACKEND_SERVICE_JWT_SECRET', process.env.BACKEND_SERVICE_JWT_SECRET);
|
|
154
|
+
if (primary === null) {
|
|
155
|
+
if ((_a = process.env.BACKEND_SERVICE_JWT_SECRET_PREVIOUS) === null || _a === void 0 ? void 0 : _a.trim()) {
|
|
156
|
+
logger_1.logger.error('[auth] BACKEND_SERVICE_JWT_SECRET_PREVIOUS is set without a valid ' +
|
|
157
|
+
'BACKEND_SERVICE_JWT_SECRET; the service-principal path is DISABLED. ' +
|
|
158
|
+
'The previous slot only extends a provisioned primary, it never replaces one.');
|
|
159
|
+
}
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
const slots = [
|
|
163
|
+
{ slot: 'primary', secret: primary },
|
|
164
|
+
];
|
|
165
|
+
const previous = readSecret('BACKEND_SERVICE_JWT_SECRET_PREVIOUS', process.env.BACKEND_SERVICE_JWT_SECRET_PREVIOUS);
|
|
166
|
+
// Equal to the primary adds nothing; skip it so the log never claims a
|
|
167
|
+
// `previous` verification that was really the primary.
|
|
168
|
+
if (previous !== null && previous !== primary) {
|
|
169
|
+
slots.push({ slot: 'previous', secret: previous });
|
|
170
|
+
}
|
|
171
|
+
return slots;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Verify a token's signature and bound claims against one secret.
|
|
175
|
+
*
|
|
176
|
+
* @returns The payload, or `null` when the signature is not this secret's.
|
|
177
|
+
* @throws {AuthError} When the signature matched but the token is unacceptable.
|
|
178
|
+
*/
|
|
179
|
+
function verifyAgainst(token, secret) {
|
|
180
|
+
try {
|
|
181
|
+
// Algorithm pinned to HS256 for the same reason path 2 pins it: an
|
|
182
|
+
// unpinned verify accepts `alg: "none"` on some versions, which turns a
|
|
183
|
+
// forged unsigned token into an authenticated service principal.
|
|
184
|
+
const verified = jsonwebtoken_1.default.verify(token, secret, {
|
|
185
|
+
algorithms: ['HS256'],
|
|
186
|
+
issuer: exports.SERVICE_TOKEN_ISSUER,
|
|
187
|
+
audience: exports.SERVICE_TOKEN_AUDIENCE,
|
|
188
|
+
});
|
|
189
|
+
if (typeof verified === 'string') {
|
|
190
|
+
throw new token_verifier_1.AuthError('invalid_token', 'malformed');
|
|
191
|
+
}
|
|
192
|
+
return verified;
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error instanceof token_verifier_1.AuthError)
|
|
196
|
+
throw error;
|
|
197
|
+
// A valid signature with an expired `exp` is unambiguously our token:
|
|
198
|
+
// `jsonwebtoken` checks the signature before the claims, so reaching
|
|
199
|
+
// TokenExpiredError proves the secret matched. Report the real reason.
|
|
200
|
+
if (error instanceof jsonwebtoken_1.TokenExpiredError) {
|
|
201
|
+
throw new token_verifier_1.AuthError('invalid_token', 'expired');
|
|
202
|
+
}
|
|
203
|
+
if (error instanceof jsonwebtoken_1.JsonWebTokenError) {
|
|
204
|
+
const message = (error.message || '').toLowerCase();
|
|
205
|
+
// Signature mismatch means this is simply not this secret's credential —
|
|
206
|
+
// the caller tries the next slot, then falls through to the app-JWT and
|
|
207
|
+
// Google paths.
|
|
208
|
+
if (message.includes('invalid signature') ||
|
|
209
|
+
message.includes('invalid algorithm')) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
// Signature matched but a bound claim did not. That IS a service token
|
|
213
|
+
// aimed at the wrong recipient; reject it rather than fall through.
|
|
214
|
+
if (message.includes('audience') || message.includes('issuer')) {
|
|
215
|
+
logger_1.logger.warn('[auth] service token rejected: claim binding mismatch', {
|
|
216
|
+
errorMessage: error.message,
|
|
217
|
+
});
|
|
218
|
+
throw new token_verifier_1.AuthError('invalid_token', 'bad_audience');
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Attempt to establish a service principal from a bearer token.
|
|
227
|
+
*
|
|
228
|
+
* Returns `null` — meaning "not a service credential, keep looking" — only
|
|
229
|
+
* when the path is unprovisioned or the signature does not belong to the
|
|
230
|
+
* service secret. Once a token IS proven to carry that signature, every
|
|
231
|
+
* subsequent problem with it (expiry, wrong audience, missing subject,
|
|
232
|
+
* over-long lifetime) throws, because at that point the caller's intent is
|
|
233
|
+
* unambiguous and falling through would report a misleading `bad_signature`
|
|
234
|
+
* for what is actually an expired or mis-scoped service token.
|
|
235
|
+
*
|
|
236
|
+
* @param token - Raw bearer token; assumed to be three dot-separated segments.
|
|
237
|
+
* @returns The verified service principal, or `null` to fall through.
|
|
238
|
+
* @throws {AuthError} When the token is ours but unacceptable.
|
|
239
|
+
*/
|
|
240
|
+
function verifyServiceToken(token, nowMs = Date.now()) {
|
|
241
|
+
const slots = resolveServiceSecrets();
|
|
242
|
+
if (slots === null)
|
|
243
|
+
return null;
|
|
244
|
+
// A service secret set equal to the user-session secret would let any
|
|
245
|
+
// end-user JWT that carries our issuer/audience become a `server` principal,
|
|
246
|
+
// which bypasses every tenancy scope and role gate. Refuse rather than
|
|
247
|
+
// silently operate with the separation collapsed. This holds for the
|
|
248
|
+
// previous slot too: a rotation must not reopen the hole.
|
|
249
|
+
if (slots.some(({ secret }) => secret === jwtConfig_1.jwtSecret)) {
|
|
250
|
+
logger_1.logger.error('[auth] BACKEND_SERVICE_JWT_SECRET (or its _PREVIOUS slot) is identical to JWT_SECRET. ' +
|
|
251
|
+
'These MUST be distinct secrets — sharing them collapses the ' +
|
|
252
|
+
'separation between end-user and service identity. Refusing to ' +
|
|
253
|
+
'verify service tokens until they differ.');
|
|
254
|
+
throw new token_verifier_1.AuthError('invalid_token', 'misconfigured');
|
|
255
|
+
}
|
|
256
|
+
let payload = null;
|
|
257
|
+
let keySlot = 'primary';
|
|
258
|
+
for (const { slot, secret } of slots) {
|
|
259
|
+
payload = verifyAgainst(token, secret);
|
|
260
|
+
if (payload !== null) {
|
|
261
|
+
keySlot = slot;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (payload === null)
|
|
266
|
+
return null;
|
|
267
|
+
const sub = typeof payload.sub === 'string' ? payload.sub.trim() : '';
|
|
268
|
+
if (sub.length === 0) {
|
|
269
|
+
// An unattributable service credential defeats the audit trail this path
|
|
270
|
+
// is supposed to provide over the static token it replaces.
|
|
271
|
+
logger_1.logger.warn('[auth] service token rejected: missing sub claim');
|
|
272
|
+
throw new token_verifier_1.AuthError('invalid_token', 'malformed');
|
|
273
|
+
}
|
|
274
|
+
const iat = payload.iat;
|
|
275
|
+
const exp = payload.exp;
|
|
276
|
+
if (typeof exp !== 'number' || !Number.isFinite(exp)) {
|
|
277
|
+
// Without an expiry this is a permanent bearer — exactly the property the
|
|
278
|
+
// service path exists to avoid.
|
|
279
|
+
logger_1.logger.warn('[auth] service token rejected: missing exp claim', { sub });
|
|
280
|
+
throw new token_verifier_1.AuthError('invalid_token', 'malformed');
|
|
281
|
+
}
|
|
282
|
+
if (typeof iat !== 'number' || !Number.isFinite(iat)) {
|
|
283
|
+
// The lifetime ceiling is `exp - iat`. Without an `iat` there is nothing to
|
|
284
|
+
// measure it from, and a far-future `exp` would pass as a long-lived
|
|
285
|
+
// bearer — so an undated credential is refused, not waved through.
|
|
286
|
+
logger_1.logger.warn('[auth] service token rejected: missing iat claim', { sub });
|
|
287
|
+
throw new token_verifier_1.AuthError('invalid_token', 'malformed');
|
|
288
|
+
}
|
|
289
|
+
const nowSec = Math.floor(nowMs / 1000);
|
|
290
|
+
if (iat > nowSec + exports.MAX_SERVICE_TOKEN_CLOCK_SKEW_SEC) {
|
|
291
|
+
// A forward-dated `iat` moves the ceiling's window into the future with it:
|
|
292
|
+
// `exp - iat` stays small while `exp - now` is unbounded.
|
|
293
|
+
logger_1.logger.warn('[auth] service token rejected: iat is in the future', {
|
|
294
|
+
sub,
|
|
295
|
+
aheadSec: iat - nowSec,
|
|
296
|
+
skewSec: exports.MAX_SERVICE_TOKEN_CLOCK_SKEW_SEC,
|
|
297
|
+
});
|
|
298
|
+
throw new token_verifier_1.AuthError('invalid_token', 'malformed');
|
|
299
|
+
}
|
|
300
|
+
if (exp - iat > exports.MAX_SERVICE_TOKEN_LIFETIME_SEC) {
|
|
301
|
+
logger_1.logger.warn('[auth] service token rejected: lifetime exceeds ceiling', {
|
|
302
|
+
sub,
|
|
303
|
+
lifetimeSec: exp - iat,
|
|
304
|
+
ceilingSec: exports.MAX_SERVICE_TOKEN_LIFETIME_SEC,
|
|
305
|
+
});
|
|
306
|
+
throw new token_verifier_1.AuthError('invalid_token', 'bad_audience');
|
|
307
|
+
}
|
|
308
|
+
// Which key verified is the rotation's progress signal: once `previous`
|
|
309
|
+
// stops appearing, every minter is on the new key and the slot can go.
|
|
310
|
+
// `previous` logs at info so it shows under any production LOG_LEVEL short
|
|
311
|
+
// of warn; `primary` is the steady state and stays at debug.
|
|
312
|
+
const keyLog = keySlot === 'previous' ? logger_1.logger.info : logger_1.logger.debug;
|
|
313
|
+
keyLog('[auth] service token verified', { sub, keySlot });
|
|
314
|
+
return { kind: 'server', sub };
|
|
315
|
+
}
|
|
316
|
+
//# sourceMappingURL=service-token.js.map
|