@adaptic/backend-legacy 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
package/auth/totp.cjs
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TOTP second factor: RFC 6238 codes, secret encryption at rest, and
|
|
4
|
+
* recovery codes. Pure functions over explicit inputs (time, key, bytes); the
|
|
5
|
+
* resolver in `src/resolvers/custom/UserTotpResolver.ts` supplies them and
|
|
6
|
+
* owns every database effect.
|
|
7
|
+
*
|
|
8
|
+
* - Codes are RFC 6238 with the RFC 4226 dynamic truncation: HMAC-SHA1, a
|
|
9
|
+
* 30-second step, six digits — the parameters every authenticator app
|
|
10
|
+
* defaults to, written into the otpauth URI so none is left implicit.
|
|
11
|
+
* - Verification accepts the current step and one step either side (clock
|
|
12
|
+
* skew between the device and the server), compares in constant time, and
|
|
13
|
+
* returns the matched step so the caller can refuse a replay of it.
|
|
14
|
+
* - The shared secret is stored encrypted with AES-256-GCM under
|
|
15
|
+
* `TOTP_ENCRYPTION_KEY` (32 bytes, base64). A missing or malformed key is an
|
|
16
|
+
* error, never a fallback: a TOTP secret stored in the clear, or under a
|
|
17
|
+
* default key, is not a second factor.
|
|
18
|
+
* - Recovery codes are 80 random bits each, shown once, and stored as SHA-256
|
|
19
|
+
* hashes. Their entropy is what makes an unsalted fast hash adequate: there
|
|
20
|
+
* is no dictionary to run against them.
|
|
21
|
+
*
|
|
22
|
+
* @module auth/totp
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.TotpKeyError = exports.RECOVERY_CODE_COUNT = exports.TOTP_SECRET_BYTES = exports.TOTP_WINDOW_STEPS = exports.TOTP_DIGITS = exports.TOTP_STEP_SECONDS = exports.TOTP_ENCRYPTION_KEY_ENV = void 0;
|
|
26
|
+
exports.readTotpEncryptionKey = readTotpEncryptionKey;
|
|
27
|
+
exports.base32Encode = base32Encode;
|
|
28
|
+
exports.totpStep = totpStep;
|
|
29
|
+
exports.hotp = hotp;
|
|
30
|
+
exports.totpCode = totpCode;
|
|
31
|
+
exports.verifyTotp = verifyTotp;
|
|
32
|
+
exports.generateTotpSecret = generateTotpSecret;
|
|
33
|
+
exports.otpauthUri = otpauthUri;
|
|
34
|
+
exports.encryptTotpSecret = encryptTotpSecret;
|
|
35
|
+
exports.decryptTotpSecret = decryptTotpSecret;
|
|
36
|
+
exports.normalizeRecoveryCode = normalizeRecoveryCode;
|
|
37
|
+
exports.hashRecoveryCode = hashRecoveryCode;
|
|
38
|
+
exports.generateRecoveryCodes = generateRecoveryCodes;
|
|
39
|
+
const node_crypto_1 = require("node:crypto");
|
|
40
|
+
/** Environment variable holding the 32-byte AES-256-GCM key, base64-encoded. */
|
|
41
|
+
exports.TOTP_ENCRYPTION_KEY_ENV = 'TOTP_ENCRYPTION_KEY';
|
|
42
|
+
/** RFC 6238 time step, in seconds. */
|
|
43
|
+
exports.TOTP_STEP_SECONDS = 30;
|
|
44
|
+
/** Digits in a code. */
|
|
45
|
+
exports.TOTP_DIGITS = 6;
|
|
46
|
+
/** Steps accepted either side of the current one. */
|
|
47
|
+
exports.TOTP_WINDOW_STEPS = 1;
|
|
48
|
+
/** Bytes of shared secret: 160 bits, the HMAC-SHA1 block-size recommendation of RFC 4226 §4. */
|
|
49
|
+
exports.TOTP_SECRET_BYTES = 20;
|
|
50
|
+
/** Recovery codes issued per enrolment. */
|
|
51
|
+
exports.RECOVERY_CODE_COUNT = 10;
|
|
52
|
+
/** Bytes of randomness per recovery code (80 bits → 16 base32 characters). */
|
|
53
|
+
const RECOVERY_CODE_BYTES = 10;
|
|
54
|
+
/** AES-256 key length in bytes. */
|
|
55
|
+
const AES_KEY_BYTES = 32;
|
|
56
|
+
/** GCM nonce length in bytes (the NIST SP 800-38D recommendation). */
|
|
57
|
+
const GCM_IV_BYTES = 12;
|
|
58
|
+
/** Version tag on the stored ciphertext, so a future key rotation can tell formats apart. */
|
|
59
|
+
const CIPHERTEXT_VERSION = 'v1';
|
|
60
|
+
const MS_PER_SECOND = 1000;
|
|
61
|
+
const DECIMAL_BASE = 10;
|
|
62
|
+
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
63
|
+
const BITS_PER_BASE32_CHAR = 5;
|
|
64
|
+
const BITS_PER_BYTE = 8;
|
|
65
|
+
const BASE32_MASK = 0x1f;
|
|
66
|
+
const BYTE_MASK = 0xff;
|
|
67
|
+
const TRUNCATION_OFFSET_MASK = 0x0f;
|
|
68
|
+
const TRUNCATION_SIGN_MASK = 0x7f;
|
|
69
|
+
const COUNTER_BYTES = 8;
|
|
70
|
+
const RECOVERY_GROUP = 4;
|
|
71
|
+
/** Raised when the encryption key is absent or malformed. */
|
|
72
|
+
class TotpKeyError extends Error {
|
|
73
|
+
constructor(message) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = 'TotpKeyError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
exports.TotpKeyError = TotpKeyError;
|
|
79
|
+
/**
|
|
80
|
+
* Read and validate the encryption key.
|
|
81
|
+
*
|
|
82
|
+
* @param env - Environment source; injectable for tests.
|
|
83
|
+
* @returns The 32-byte key.
|
|
84
|
+
* @throws TotpKeyError when the variable is unset or does not decode to 32 bytes.
|
|
85
|
+
*/
|
|
86
|
+
function readTotpEncryptionKey(env = process.env) {
|
|
87
|
+
var _a;
|
|
88
|
+
const raw = ((_a = env[exports.TOTP_ENCRYPTION_KEY_ENV]) !== null && _a !== void 0 ? _a : '').trim();
|
|
89
|
+
if (raw.length === 0) {
|
|
90
|
+
throw new TotpKeyError(`${exports.TOTP_ENCRYPTION_KEY_ENV} is not set; TOTP secrets cannot be encrypted or read`);
|
|
91
|
+
}
|
|
92
|
+
const key = Buffer.from(raw, 'base64');
|
|
93
|
+
if (key.length !== AES_KEY_BYTES || key.toString('base64') !== raw) {
|
|
94
|
+
throw new TotpKeyError(`${exports.TOTP_ENCRYPTION_KEY_ENV} must be ${AES_KEY_BYTES} bytes, base64-encoded`);
|
|
95
|
+
}
|
|
96
|
+
return key;
|
|
97
|
+
}
|
|
98
|
+
/** RFC 4648 base32 without padding (the form otpauth URIs carry). */
|
|
99
|
+
function base32Encode(bytes) {
|
|
100
|
+
let bits = 0;
|
|
101
|
+
let value = 0;
|
|
102
|
+
let out = '';
|
|
103
|
+
for (const byte of bytes) {
|
|
104
|
+
value = (value << BITS_PER_BYTE) | byte;
|
|
105
|
+
bits += BITS_PER_BYTE;
|
|
106
|
+
while (bits >= BITS_PER_BASE32_CHAR) {
|
|
107
|
+
out +=
|
|
108
|
+
BASE32_ALPHABET[(value >>> (bits - BITS_PER_BASE32_CHAR)) & BASE32_MASK];
|
|
109
|
+
bits -= BITS_PER_BASE32_CHAR;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (bits > 0)
|
|
113
|
+
out +=
|
|
114
|
+
BASE32_ALPHABET[(value << (BITS_PER_BASE32_CHAR - bits)) & BASE32_MASK];
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
/** The RFC 6238 time step containing `nowMs`. */
|
|
118
|
+
function totpStep(nowMs) {
|
|
119
|
+
return Math.floor(nowMs / MS_PER_SECOND / exports.TOTP_STEP_SECONDS);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The RFC 4226 HOTP value for one counter, as a zero-padded decimal string.
|
|
123
|
+
*
|
|
124
|
+
* @param secret - The shared secret bytes.
|
|
125
|
+
* @param counter - The moving factor (for TOTP, the time step).
|
|
126
|
+
* @param digits - Code length.
|
|
127
|
+
*/
|
|
128
|
+
function hotp(secret, counter, digits = exports.TOTP_DIGITS) {
|
|
129
|
+
const message = Buffer.alloc(COUNTER_BYTES);
|
|
130
|
+
message.writeBigUInt64BE(BigInt(counter));
|
|
131
|
+
const mac = (0, node_crypto_1.createHmac)('sha1', secret).update(message).digest();
|
|
132
|
+
const offset = mac[mac.length - 1] & TRUNCATION_OFFSET_MASK;
|
|
133
|
+
const binary = ((mac[offset] & TRUNCATION_SIGN_MASK) << 24) |
|
|
134
|
+
((mac[offset + 1] & BYTE_MASK) << 16) |
|
|
135
|
+
((mac[offset + 2] & BYTE_MASK) << 8) |
|
|
136
|
+
(mac[offset + 3] & BYTE_MASK);
|
|
137
|
+
return String(binary % DECIMAL_BASE ** digits).padStart(digits, '0');
|
|
138
|
+
}
|
|
139
|
+
/** The TOTP code for the step containing `nowMs`. */
|
|
140
|
+
function totpCode(secret, nowMs, digits = exports.TOTP_DIGITS) {
|
|
141
|
+
return hotp(secret, totpStep(nowMs), digits);
|
|
142
|
+
}
|
|
143
|
+
function constantTimeEqual(a, b) {
|
|
144
|
+
const left = Buffer.from(a, 'utf8');
|
|
145
|
+
const right = Buffer.from(b, 'utf8');
|
|
146
|
+
if (left.length !== right.length)
|
|
147
|
+
return false;
|
|
148
|
+
return (0, node_crypto_1.timingSafeEqual)(left, right);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Check a submitted code against the steps around `nowMs`.
|
|
152
|
+
*
|
|
153
|
+
* Every candidate step is compared, whatever matched first, so the time taken
|
|
154
|
+
* does not reveal which step (if any) the code belongs to.
|
|
155
|
+
*
|
|
156
|
+
* @param secret - The shared secret bytes.
|
|
157
|
+
* @param code - The submitted code (whitespace ignored).
|
|
158
|
+
* @param nowMs - The current time.
|
|
159
|
+
* @param lastUsedStep - The step of the last accepted code; that step and
|
|
160
|
+
* every earlier one are refused, so an observed code cannot be replayed.
|
|
161
|
+
* @returns The matched step, or `null` when the code is not valid now.
|
|
162
|
+
*/
|
|
163
|
+
function verifyTotp(secret, code, nowMs, lastUsedStep) {
|
|
164
|
+
const submitted = code.replace(/\s+/g, '');
|
|
165
|
+
if (!/^\d+$/.test(submitted) || submitted.length !== exports.TOTP_DIGITS)
|
|
166
|
+
return null;
|
|
167
|
+
const current = totpStep(nowMs);
|
|
168
|
+
let matched = null;
|
|
169
|
+
for (let delta = -exports.TOTP_WINDOW_STEPS; delta <= exports.TOTP_WINDOW_STEPS; delta++) {
|
|
170
|
+
const step = current + delta;
|
|
171
|
+
if (constantTimeEqual(hotp(secret, step), submitted) && matched === null)
|
|
172
|
+
matched = step;
|
|
173
|
+
}
|
|
174
|
+
if (matched === null)
|
|
175
|
+
return null;
|
|
176
|
+
if (lastUsedStep !== null && matched <= lastUsedStep)
|
|
177
|
+
return null;
|
|
178
|
+
return matched;
|
|
179
|
+
}
|
|
180
|
+
/** Fresh random shared-secret bytes. */
|
|
181
|
+
function generateTotpSecret(random = node_crypto_1.randomBytes) {
|
|
182
|
+
return random(exports.TOTP_SECRET_BYTES);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The `otpauth://` URI an authenticator app scans. Every parameter is
|
|
186
|
+
* explicit, so no app falls back to a default that differs from the server's.
|
|
187
|
+
*
|
|
188
|
+
* @param secret - The shared secret bytes.
|
|
189
|
+
* @param accountName - The label shown in the app (the user's email).
|
|
190
|
+
* @param issuer - The issuer shown in the app.
|
|
191
|
+
*/
|
|
192
|
+
function otpauthUri(secret, accountName, issuer) {
|
|
193
|
+
const label = encodeURIComponent(`${issuer}:${accountName}`);
|
|
194
|
+
const params = new URLSearchParams({
|
|
195
|
+
secret: base32Encode(secret),
|
|
196
|
+
issuer,
|
|
197
|
+
algorithm: 'SHA1',
|
|
198
|
+
digits: String(exports.TOTP_DIGITS),
|
|
199
|
+
period: String(exports.TOTP_STEP_SECONDS),
|
|
200
|
+
});
|
|
201
|
+
return `otpauth://totp/${label}?${params.toString()}`;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Encrypt a secret for storage: `v1.<iv>.<tag>.<ciphertext>`, each base64.
|
|
205
|
+
*
|
|
206
|
+
* @param secret - The shared secret bytes.
|
|
207
|
+
* @param key - The 32-byte key from {@link readTotpEncryptionKey}.
|
|
208
|
+
* @param random - Randomness source for the nonce; injectable for tests.
|
|
209
|
+
*/
|
|
210
|
+
function encryptTotpSecret(secret, key, random = node_crypto_1.randomBytes) {
|
|
211
|
+
const iv = random(GCM_IV_BYTES);
|
|
212
|
+
const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', key, iv);
|
|
213
|
+
const ciphertext = Buffer.concat([cipher.update(secret), cipher.final()]);
|
|
214
|
+
const tag = cipher.getAuthTag();
|
|
215
|
+
return [
|
|
216
|
+
CIPHERTEXT_VERSION,
|
|
217
|
+
iv.toString('base64'),
|
|
218
|
+
tag.toString('base64'),
|
|
219
|
+
ciphertext.toString('base64'),
|
|
220
|
+
].join('.');
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Decrypt a stored secret.
|
|
224
|
+
*
|
|
225
|
+
* @throws Error when the format is unknown or the authentication tag fails
|
|
226
|
+
* (a wrong key, or a tampered row).
|
|
227
|
+
*/
|
|
228
|
+
function decryptTotpSecret(stored, key) {
|
|
229
|
+
const parts = stored.split('.');
|
|
230
|
+
if (parts.length !== 4 || parts[0] !== CIPHERTEXT_VERSION) {
|
|
231
|
+
throw new Error('stored TOTP secret has an unrecognised format');
|
|
232
|
+
}
|
|
233
|
+
const [, iv, tag, ciphertext] = parts;
|
|
234
|
+
const decipher = (0, node_crypto_1.createDecipheriv)('aes-256-gcm', key, Buffer.from(iv, 'base64'));
|
|
235
|
+
decipher.setAuthTag(Buffer.from(tag, 'base64'));
|
|
236
|
+
return Buffer.concat([
|
|
237
|
+
decipher.update(Buffer.from(ciphertext, 'base64')),
|
|
238
|
+
decipher.final(),
|
|
239
|
+
]);
|
|
240
|
+
}
|
|
241
|
+
/** Normalise a recovery code as typed: uppercase, separators and spaces removed. */
|
|
242
|
+
function normalizeRecoveryCode(code) {
|
|
243
|
+
return code.replace(/[\s-]+/g, '').toUpperCase();
|
|
244
|
+
}
|
|
245
|
+
/** The stored hash of a recovery code (hex SHA-256 of its normalised form). */
|
|
246
|
+
function hashRecoveryCode(code) {
|
|
247
|
+
return (0, node_crypto_1.createHash)('sha256').update(normalizeRecoveryCode(code)).digest('hex');
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Fresh recovery codes, formatted `XXXX-XXXX-XXXX-XXXX` for reading aloud.
|
|
251
|
+
*
|
|
252
|
+
* @param random - Randomness source; injectable for tests.
|
|
253
|
+
*/
|
|
254
|
+
function generateRecoveryCodes(random = node_crypto_1.randomBytes) {
|
|
255
|
+
const codes = [];
|
|
256
|
+
for (let i = 0; i < exports.RECOVERY_CODE_COUNT; i++) {
|
|
257
|
+
const raw = base32Encode(random(RECOVERY_CODE_BYTES));
|
|
258
|
+
const groups = [];
|
|
259
|
+
for (let at = 0; at < raw.length; at += RECOVERY_GROUP)
|
|
260
|
+
groups.push(raw.slice(at, at + RECOVERY_GROUP));
|
|
261
|
+
codes.push(groups.join('-'));
|
|
262
|
+
}
|
|
263
|
+
return codes;
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=totp.js.map
|
package/auth/totp.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TOTP second factor: RFC 6238 codes, secret encryption at rest, and
|
|
3
|
+
* recovery codes. Pure functions over explicit inputs (time, key, bytes); the
|
|
4
|
+
* resolver in `src/resolvers/custom/UserTotpResolver.ts` supplies them and
|
|
5
|
+
* owns every database effect.
|
|
6
|
+
*
|
|
7
|
+
* - Codes are RFC 6238 with the RFC 4226 dynamic truncation: HMAC-SHA1, a
|
|
8
|
+
* 30-second step, six digits — the parameters every authenticator app
|
|
9
|
+
* defaults to, written into the otpauth URI so none is left implicit.
|
|
10
|
+
* - Verification accepts the current step and one step either side (clock
|
|
11
|
+
* skew between the device and the server), compares in constant time, and
|
|
12
|
+
* returns the matched step so the caller can refuse a replay of it.
|
|
13
|
+
* - The shared secret is stored encrypted with AES-256-GCM under
|
|
14
|
+
* `TOTP_ENCRYPTION_KEY` (32 bytes, base64). A missing or malformed key is an
|
|
15
|
+
* error, never a fallback: a TOTP secret stored in the clear, or under a
|
|
16
|
+
* default key, is not a second factor.
|
|
17
|
+
* - Recovery codes are 80 random bits each, shown once, and stored as SHA-256
|
|
18
|
+
* hashes. Their entropy is what makes an unsalted fast hash adequate: there
|
|
19
|
+
* is no dictionary to run against them.
|
|
20
|
+
*
|
|
21
|
+
* @module auth/totp
|
|
22
|
+
*/
|
|
23
|
+
/** Environment variable holding the 32-byte AES-256-GCM key, base64-encoded. */
|
|
24
|
+
export declare const TOTP_ENCRYPTION_KEY_ENV = "TOTP_ENCRYPTION_KEY";
|
|
25
|
+
/** RFC 6238 time step, in seconds. */
|
|
26
|
+
export declare const TOTP_STEP_SECONDS = 30;
|
|
27
|
+
/** Digits in a code. */
|
|
28
|
+
export declare const TOTP_DIGITS = 6;
|
|
29
|
+
/** Steps accepted either side of the current one. */
|
|
30
|
+
export declare const TOTP_WINDOW_STEPS = 1;
|
|
31
|
+
/** Bytes of shared secret: 160 bits, the HMAC-SHA1 block-size recommendation of RFC 4226 §4. */
|
|
32
|
+
export declare const TOTP_SECRET_BYTES = 20;
|
|
33
|
+
/** Recovery codes issued per enrolment. */
|
|
34
|
+
export declare const RECOVERY_CODE_COUNT = 10;
|
|
35
|
+
/** Raised when the encryption key is absent or malformed. */
|
|
36
|
+
export declare class TotpKeyError extends Error {
|
|
37
|
+
constructor(message: string);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Read and validate the encryption key.
|
|
41
|
+
*
|
|
42
|
+
* @param env - Environment source; injectable for tests.
|
|
43
|
+
* @returns The 32-byte key.
|
|
44
|
+
* @throws TotpKeyError when the variable is unset or does not decode to 32 bytes.
|
|
45
|
+
*/
|
|
46
|
+
export declare function readTotpEncryptionKey(env?: Record<string, string | undefined>): Buffer;
|
|
47
|
+
/** RFC 4648 base32 without padding (the form otpauth URIs carry). */
|
|
48
|
+
export declare function base32Encode(bytes: Buffer): string;
|
|
49
|
+
/** The RFC 6238 time step containing `nowMs`. */
|
|
50
|
+
export declare function totpStep(nowMs: number): number;
|
|
51
|
+
/**
|
|
52
|
+
* The RFC 4226 HOTP value for one counter, as a zero-padded decimal string.
|
|
53
|
+
*
|
|
54
|
+
* @param secret - The shared secret bytes.
|
|
55
|
+
* @param counter - The moving factor (for TOTP, the time step).
|
|
56
|
+
* @param digits - Code length.
|
|
57
|
+
*/
|
|
58
|
+
export declare function hotp(secret: Buffer, counter: number, digits?: number): string;
|
|
59
|
+
/** The TOTP code for the step containing `nowMs`. */
|
|
60
|
+
export declare function totpCode(secret: Buffer, nowMs: number, digits?: number): string;
|
|
61
|
+
/**
|
|
62
|
+
* Check a submitted code against the steps around `nowMs`.
|
|
63
|
+
*
|
|
64
|
+
* Every candidate step is compared, whatever matched first, so the time taken
|
|
65
|
+
* does not reveal which step (if any) the code belongs to.
|
|
66
|
+
*
|
|
67
|
+
* @param secret - The shared secret bytes.
|
|
68
|
+
* @param code - The submitted code (whitespace ignored).
|
|
69
|
+
* @param nowMs - The current time.
|
|
70
|
+
* @param lastUsedStep - The step of the last accepted code; that step and
|
|
71
|
+
* every earlier one are refused, so an observed code cannot be replayed.
|
|
72
|
+
* @returns The matched step, or `null` when the code is not valid now.
|
|
73
|
+
*/
|
|
74
|
+
export declare function verifyTotp(secret: Buffer, code: string, nowMs: number, lastUsedStep: number | null): number | null;
|
|
75
|
+
/** Fresh random shared-secret bytes. */
|
|
76
|
+
export declare function generateTotpSecret(random?: (size: number) => Buffer): Buffer;
|
|
77
|
+
/**
|
|
78
|
+
* The `otpauth://` URI an authenticator app scans. Every parameter is
|
|
79
|
+
* explicit, so no app falls back to a default that differs from the server's.
|
|
80
|
+
*
|
|
81
|
+
* @param secret - The shared secret bytes.
|
|
82
|
+
* @param accountName - The label shown in the app (the user's email).
|
|
83
|
+
* @param issuer - The issuer shown in the app.
|
|
84
|
+
*/
|
|
85
|
+
export declare function otpauthUri(secret: Buffer, accountName: string, issuer: string): string;
|
|
86
|
+
/**
|
|
87
|
+
* Encrypt a secret for storage: `v1.<iv>.<tag>.<ciphertext>`, each base64.
|
|
88
|
+
*
|
|
89
|
+
* @param secret - The shared secret bytes.
|
|
90
|
+
* @param key - The 32-byte key from {@link readTotpEncryptionKey}.
|
|
91
|
+
* @param random - Randomness source for the nonce; injectable for tests.
|
|
92
|
+
*/
|
|
93
|
+
export declare function encryptTotpSecret(secret: Buffer, key: Buffer, random?: (size: number) => Buffer): string;
|
|
94
|
+
/**
|
|
95
|
+
* Decrypt a stored secret.
|
|
96
|
+
*
|
|
97
|
+
* @throws Error when the format is unknown or the authentication tag fails
|
|
98
|
+
* (a wrong key, or a tampered row).
|
|
99
|
+
*/
|
|
100
|
+
export declare function decryptTotpSecret(stored: string, key: Buffer): Buffer;
|
|
101
|
+
/** Normalise a recovery code as typed: uppercase, separators and spaces removed. */
|
|
102
|
+
export declare function normalizeRecoveryCode(code: string): string;
|
|
103
|
+
/** The stored hash of a recovery code (hex SHA-256 of its normalised form). */
|
|
104
|
+
export declare function hashRecoveryCode(code: string): string;
|
|
105
|
+
/**
|
|
106
|
+
* Fresh recovery codes, formatted `XXXX-XXXX-XXXX-XXXX` for reading aloud.
|
|
107
|
+
*
|
|
108
|
+
* @param random - Randomness source; injectable for tests.
|
|
109
|
+
*/
|
|
110
|
+
export declare function generateRecoveryCodes(random?: (size: number) => Buffer): string[];
|
|
111
|
+
//# sourceMappingURL=totp.d.ts.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Content rules for the models a `user` principal may write without a
|
|
4
|
+
* row-ownership model: which FIELDS of their own `User` row they may set,
|
|
5
|
+
* what an `AuditLog` row they author may claim, and which `Configuration`
|
|
6
|
+
* rows are theirs. Pure; no I/O.
|
|
7
|
+
*
|
|
8
|
+
* - **User.** "Only your own row" is not enough when the row carries the
|
|
9
|
+
* caller's privilege (`role` is `OWNER | ADMIN | SUPERADMIN | USER`), their
|
|
10
|
+
* identity (`id`, `email`, `emailVerified`), a billing link (`customerId`,
|
|
11
|
+
* `plan`) or a stored credential (`openaiAPIKey`). A user may set only the
|
|
12
|
+
* profile and onboarding fields the platform's own routes write, and no
|
|
13
|
+
* relation at all through their row. Desk availability (`availability`,
|
|
14
|
+
* `availabilityUntil`) is the user's own statement of whether they are at
|
|
15
|
+
* the desk; deputy routing reads it, so only its owner may set it.
|
|
16
|
+
* - **AuditLog.** The attributed TradingPolicy trail is identified by
|
|
17
|
+
* `metadata.source = 'mutation-auth-guard'`. A user-authored row claiming
|
|
18
|
+
* that source, or naming someone else as its `userId`, is a forged
|
|
19
|
+
* attribution record, so both are refused. `fundId` places a row in that
|
|
20
|
+
* fund's desk ledger, which is the engine's record of what the desk did and
|
|
21
|
+
* is written by the service principal; a user-authored row setting it would
|
|
22
|
+
* be served as a ledger entry of a fund the user may not even belong to, so
|
|
23
|
+
* a user may not set it at all (`ledger_fund_reserved`).
|
|
24
|
+
* - **Configuration.** The table also holds system rows (LLM alias routing,
|
|
25
|
+
* engine settings) keyed by a unique `configKey`. The platform's per-user
|
|
26
|
+
* preference rows live under `platform.web.<surface>.user.<userId>`; a user
|
|
27
|
+
* may upsert only a key in that namespace ending in their own id, and may
|
|
28
|
+
* not rename it.
|
|
29
|
+
*
|
|
30
|
+
* @module auth/user-write-content
|
|
31
|
+
*/
|
|
32
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
33
|
+
exports.RESERVED_AUDIT_SOURCES = exports.USER_SELF_WRITABLE_FIELDS = void 0;
|
|
34
|
+
exports.userContentRefusal = userContentRefusal;
|
|
35
|
+
/** The `User` fields a user may set on their own row. */
|
|
36
|
+
exports.USER_SELF_WRITABLE_FIELDS = new Set([
|
|
37
|
+
'name',
|
|
38
|
+
'image',
|
|
39
|
+
'avatarUrl',
|
|
40
|
+
'bio',
|
|
41
|
+
'jobTitle',
|
|
42
|
+
'onboardingComplete',
|
|
43
|
+
'signupCategory',
|
|
44
|
+
'availability',
|
|
45
|
+
'availabilityUntil',
|
|
46
|
+
]);
|
|
47
|
+
/** `AuditLog.metadata.source` values only the backend itself may write. */
|
|
48
|
+
exports.RESERVED_AUDIT_SOURCES = new Set(['mutation-auth-guard']);
|
|
49
|
+
/** A per-user platform preference key: `platform.web.<surface>.user.<userId>`. */
|
|
50
|
+
const USER_CONFIG_KEY = /^platform\.web\.[a-z0-9][a-z0-9-]*\.user\.([0-9a-f-]{36})$/;
|
|
51
|
+
function asRecord(value) {
|
|
52
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
53
|
+
? value
|
|
54
|
+
: undefined;
|
|
55
|
+
}
|
|
56
|
+
function definedKeys(record) {
|
|
57
|
+
return Object.keys(record).filter((key) => record[key] !== undefined);
|
|
58
|
+
}
|
|
59
|
+
function userSelfRefusal(args) {
|
|
60
|
+
const data = asRecord(args.data);
|
|
61
|
+
if (!data)
|
|
62
|
+
return 'field_not_user_writable';
|
|
63
|
+
return definedKeys(data).every((key) => exports.USER_SELF_WRITABLE_FIELDS.has(key)) ? null : 'field_not_user_writable';
|
|
64
|
+
}
|
|
65
|
+
function auditLogRefusal(args, callerId) {
|
|
66
|
+
var _a;
|
|
67
|
+
const data = asRecord(args.data);
|
|
68
|
+
if (!data)
|
|
69
|
+
return 'reserved_audit_source';
|
|
70
|
+
const source = (_a = asRecord(data.metadata)) === null || _a === void 0 ? void 0 : _a.source;
|
|
71
|
+
if (typeof source === 'string' && exports.RESERVED_AUDIT_SOURCES.has(source))
|
|
72
|
+
return 'reserved_audit_source';
|
|
73
|
+
if (data.userId !== undefined && data.userId !== null && data.userId !== callerId) {
|
|
74
|
+
return 'audit_actor_mismatch';
|
|
75
|
+
}
|
|
76
|
+
if (data.fundId !== undefined && data.fundId !== null)
|
|
77
|
+
return 'ledger_fund_reserved';
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
function configurationRefusal(args, callerId) {
|
|
81
|
+
var _a, _b;
|
|
82
|
+
const where = asRecord(args.where);
|
|
83
|
+
const key = where === null || where === void 0 ? void 0 : where.configKey;
|
|
84
|
+
if (!where || typeof key !== 'string' || definedKeys(where).length !== 1)
|
|
85
|
+
return 'config_key_not_user_scoped';
|
|
86
|
+
const match = USER_CONFIG_KEY.exec(key);
|
|
87
|
+
if (!match || match[1] !== callerId)
|
|
88
|
+
return 'config_key_not_user_scoped';
|
|
89
|
+
const createKey = (_a = asRecord(args.create)) === null || _a === void 0 ? void 0 : _a.configKey;
|
|
90
|
+
if (createKey !== undefined && createKey !== key)
|
|
91
|
+
return 'config_key_not_user_scoped';
|
|
92
|
+
if (((_b = asRecord(args.update)) === null || _b === void 0 ? void 0 : _b.configKey) !== undefined)
|
|
93
|
+
return 'config_key_not_user_scoped';
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The content refusal for a user's write, or `null` when the content is
|
|
98
|
+
* admissible (or the model has no content rule).
|
|
99
|
+
*
|
|
100
|
+
* @param target - The classified root mutation field.
|
|
101
|
+
* @param args - The field's arguments.
|
|
102
|
+
* @param callerId - The user principal's subject.
|
|
103
|
+
*/
|
|
104
|
+
function userContentRefusal(target, args, callerId) {
|
|
105
|
+
switch (target.model) {
|
|
106
|
+
case 'User':
|
|
107
|
+
return userSelfRefusal(args);
|
|
108
|
+
case 'AuditLog':
|
|
109
|
+
return auditLogRefusal(args, callerId);
|
|
110
|
+
case 'Configuration':
|
|
111
|
+
return configurationRefusal(args, callerId);
|
|
112
|
+
default:
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
//# sourceMappingURL=user-write-content.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content rules for the models a `user` principal may write without a
|
|
3
|
+
* row-ownership model: which FIELDS of their own `User` row they may set,
|
|
4
|
+
* what an `AuditLog` row they author may claim, and which `Configuration`
|
|
5
|
+
* rows are theirs. Pure; no I/O.
|
|
6
|
+
*
|
|
7
|
+
* - **User.** "Only your own row" is not enough when the row carries the
|
|
8
|
+
* caller's privilege (`role` is `OWNER | ADMIN | SUPERADMIN | USER`), their
|
|
9
|
+
* identity (`id`, `email`, `emailVerified`), a billing link (`customerId`,
|
|
10
|
+
* `plan`) or a stored credential (`openaiAPIKey`). A user may set only the
|
|
11
|
+
* profile and onboarding fields the platform's own routes write, and no
|
|
12
|
+
* relation at all through their row. Desk availability (`availability`,
|
|
13
|
+
* `availabilityUntil`) is the user's own statement of whether they are at
|
|
14
|
+
* the desk; deputy routing reads it, so only its owner may set it.
|
|
15
|
+
* - **AuditLog.** The attributed TradingPolicy trail is identified by
|
|
16
|
+
* `metadata.source = 'mutation-auth-guard'`. A user-authored row claiming
|
|
17
|
+
* that source, or naming someone else as its `userId`, is a forged
|
|
18
|
+
* attribution record, so both are refused. `fundId` places a row in that
|
|
19
|
+
* fund's desk ledger, which is the engine's record of what the desk did and
|
|
20
|
+
* is written by the service principal; a user-authored row setting it would
|
|
21
|
+
* be served as a ledger entry of a fund the user may not even belong to, so
|
|
22
|
+
* a user may not set it at all (`ledger_fund_reserved`).
|
|
23
|
+
* - **Configuration.** The table also holds system rows (LLM alias routing,
|
|
24
|
+
* engine settings) keyed by a unique `configKey`. The platform's per-user
|
|
25
|
+
* preference rows live under `platform.web.<surface>.user.<userId>`; a user
|
|
26
|
+
* may upsert only a key in that namespace ending in their own id, and may
|
|
27
|
+
* not rename it.
|
|
28
|
+
*
|
|
29
|
+
* @module auth/user-write-content
|
|
30
|
+
*/
|
|
31
|
+
import type { MutationAuthReason, MutationTarget } from './mutation-authorization';
|
|
32
|
+
/** The `User` fields a user may set on their own row. */
|
|
33
|
+
export declare const USER_SELF_WRITABLE_FIELDS: ReadonlySet<string>;
|
|
34
|
+
/** `AuditLog.metadata.source` values only the backend itself may write. */
|
|
35
|
+
export declare const RESERVED_AUDIT_SOURCES: ReadonlySet<string>;
|
|
36
|
+
/** Why a user's write content was refused (a bounded metric label). */
|
|
37
|
+
export type ContentRefusal = Extract<MutationAuthReason, 'field_not_user_writable' | 'reserved_audit_source' | 'audit_actor_mismatch' | 'ledger_fund_reserved' | 'config_key_not_user_scoped'>;
|
|
38
|
+
/**
|
|
39
|
+
* The content refusal for a user's write, or `null` when the content is
|
|
40
|
+
* admissible (or the model has no content rule).
|
|
41
|
+
*
|
|
42
|
+
* @param target - The classified root mutation field.
|
|
43
|
+
* @param args - The field's arguments.
|
|
44
|
+
* @param callerId - The user principal's subject.
|
|
45
|
+
*/
|
|
46
|
+
export declare function userContentRefusal(target: MutationTarget, args: Record<string, unknown>, callerId: string): ContentRefusal | null;
|
|
47
|
+
//# sourceMappingURL=user-write-content.d.ts.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseBearerToken = parseBearerToken;
|
|
4
|
+
exports.decideWsAuth = decideWsAuth;
|
|
5
|
+
exports.unauthenticatedWsError = unauthenticatedWsError;
|
|
6
|
+
/**
|
|
7
|
+
* WebSocket connection-auth decision for the `/subscriptions` transport.
|
|
8
|
+
*
|
|
9
|
+
* graphql-ws invokes the `context` callback lazily, on Subscribe. Whatever that
|
|
10
|
+
* callback throws terminates the socket: graphql-ws catches it in its message
|
|
11
|
+
* handler and closes with `CloseCode.InternalServerError` (4500), carrying the
|
|
12
|
+
* error message as the close reason. There is deliberately no path that keeps
|
|
13
|
+
* an unverified socket open with a degraded context — a subscription that
|
|
14
|
+
* streams data to a caller whose token did not verify is an authentication
|
|
15
|
+
* bypass, not a degraded mode.
|
|
16
|
+
*
|
|
17
|
+
* The decision is separated from its effects (metrics, logging, Prisma
|
|
18
|
+
* attachment) so the security-relevant predicate is a pure function that can be
|
|
19
|
+
* exercised, and mutation-proven, without booting the server.
|
|
20
|
+
*/
|
|
21
|
+
const graphql_1 = require("graphql");
|
|
22
|
+
const token_verifier_1 = require("./token-verifier.cjs");
|
|
23
|
+
/**
|
|
24
|
+
* Extract the raw token from an `Authorization` value. Returns the empty string
|
|
25
|
+
* for anything that is not a well-formed `Bearer <token>` header, which the
|
|
26
|
+
* caller treats as "no token presented" rather than as a malformed token.
|
|
27
|
+
*/
|
|
28
|
+
function parseBearerToken(authHeader) {
|
|
29
|
+
if (!authHeader || !authHeader.startsWith('Bearer '))
|
|
30
|
+
return '';
|
|
31
|
+
return authHeader.slice('Bearer '.length).trim();
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Classify a WebSocket connection's credentials.
|
|
35
|
+
*
|
|
36
|
+
* A presented-but-unverifiable token always yields `rejected`, never
|
|
37
|
+
* `anonymous`. Downgrading a failed verification to an anonymous session would
|
|
38
|
+
* convert an authentication failure into a weaker session that still serves
|
|
39
|
+
* data — the bypass this function exists to make unrepresentable.
|
|
40
|
+
*
|
|
41
|
+
* Verification failures that are not `AuthError` are classified
|
|
42
|
+
* `bad_signature` rather than escaping, so an unexpected verifier fault still
|
|
43
|
+
* fails closed (socket closed) instead of surfacing as an unhandled rejection.
|
|
44
|
+
*/
|
|
45
|
+
async function decideWsAuth(authHeader, verify = token_verifier_1.verifyBackendToken) {
|
|
46
|
+
const token = parseBearerToken(authHeader);
|
|
47
|
+
if (!token)
|
|
48
|
+
return { kind: 'anonymous' };
|
|
49
|
+
try {
|
|
50
|
+
const principal = await verify(token);
|
|
51
|
+
return { kind: 'authenticated', principal };
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
const reason = e instanceof token_verifier_1.AuthError ? e.reason : 'bad_signature';
|
|
55
|
+
return { kind: 'rejected', reason };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The error a rejected WebSocket connection throws from its `context` callback.
|
|
60
|
+
*
|
|
61
|
+
* `extensions.http.status` is carried for symmetry with the HTTP context: the
|
|
62
|
+
* WebSocket transport closes rather than producing an HTTP response, but any
|
|
63
|
+
* future code that funnels a WS rejection into an HTTP reply gets the correct
|
|
64
|
+
* status without a second definition of it.
|
|
65
|
+
*/
|
|
66
|
+
function unauthenticatedWsError(reason) {
|
|
67
|
+
return new graphql_1.GraphQLError('Unauthenticated', {
|
|
68
|
+
extensions: {
|
|
69
|
+
code: 'UNAUTHENTICATED',
|
|
70
|
+
reason,
|
|
71
|
+
http: { status: 401 },
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=ws-auth-context.js.map
|