@adaptic/backend-legacy 0.0.1057 → 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.
Files changed (111) hide show
  1. package/auth/authorization-map.cjs +306 -0
  2. package/auth/authorization-map.d.ts +143 -0
  3. package/auth/cortex-auth-checker.cjs +172 -0
  4. package/auth/cortex-auth-checker.d.ts +114 -0
  5. package/auth/credential-fields.cjs +51 -0
  6. package/auth/credential-fields.d.ts +19 -0
  7. package/auth/credential-redaction.cjs +134 -0
  8. package/auth/credential-redaction.d.ts +60 -0
  9. package/auth/graphql-auth-shadow.cjs +317 -0
  10. package/auth/graphql-auth-shadow.d.ts +194 -0
  11. package/auth/membership-write-authority.cjs +131 -0
  12. package/auth/membership-write-authority.d.ts +110 -0
  13. package/auth/mutation-authorization.cjs +376 -0
  14. package/auth/mutation-authorization.d.ts +261 -0
  15. package/auth/nested-write-inspector.cjs +189 -0
  16. package/auth/nested-write-inspector.d.ts +94 -0
  17. package/auth/nested-write-policy.cjs +189 -0
  18. package/auth/nested-write-policy.d.ts +99 -0
  19. package/auth/service-token.cjs +316 -0
  20. package/auth/service-token.d.ts +94 -0
  21. package/auth/tenancy-scope.cjs +736 -0
  22. package/auth/tenancy-scope.d.ts +347 -0
  23. package/auth/token-verifier.cjs +451 -0
  24. package/auth/token-verifier.d.ts +153 -0
  25. package/auth/totp.cjs +265 -0
  26. package/auth/totp.d.ts +111 -0
  27. package/auth/user-write-content.cjs +116 -0
  28. package/auth/user-write-content.d.ts +47 -0
  29. package/auth/ws-auth-context.cjs +75 -0
  30. package/auth/ws-auth-context.d.ts +69 -0
  31. package/config/jwtConfig.cjs +52 -0
  32. package/config/jwtConfig.d.ts +16 -0
  33. package/config/metrics.cjs +356 -0
  34. package/config/metrics.d.ts +128 -0
  35. package/config/persisted-queries.cjs +122 -0
  36. package/config/persisted-queries.d.ts +40 -0
  37. package/config/server-only-models.cjs +166 -0
  38. package/config/server-only-models.d.ts +89 -0
  39. package/config/tracing.d.ts +24 -0
  40. package/generated/typegraphql-prisma/enhance.cjs +3 -3
  41. package/generated/typegraphql-prisma/index.cjs +6 -6
  42. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  43. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  44. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  45. package/middleware/audit-log-write-redaction.cjs +143 -0
  46. package/middleware/audit-log-write-redaction.d.ts +82 -0
  47. package/middleware/audit-logger.cjs +378 -0
  48. package/middleware/audit-logger.d.ts +158 -0
  49. package/middleware/audit-payload-guard.cjs +107 -0
  50. package/middleware/audit-payload-guard.d.ts +85 -0
  51. package/middleware/auth.cjs +66 -0
  52. package/middleware/auth.d.ts +41 -0
  53. package/middleware/credential-field-guard.cjs +514 -0
  54. package/middleware/credential-field-guard.d.ts +173 -0
  55. package/middleware/generated-type-names.cjs +77 -0
  56. package/middleware/generated-type-names.d.ts +44 -0
  57. package/middleware/graphql-validation-plugin.cjs +310 -0
  58. package/middleware/graphql-validation-plugin.d.ts +98 -0
  59. package/middleware/guard-log-throttle.cjs +89 -0
  60. package/middleware/guard-log-throttle.d.ts +80 -0
  61. package/middleware/index.cjs +57 -0
  62. package/middleware/index.d.ts +14 -0
  63. package/middleware/input-validator.cjs +220 -0
  64. package/middleware/input-validator.d.ts +63 -0
  65. package/middleware/mandate-version-validation.cjs +131 -0
  66. package/middleware/mandate-version-validation.d.ts +41 -0
  67. package/middleware/mutation-account-facts.cjs +223 -0
  68. package/middleware/mutation-account-facts.d.ts +143 -0
  69. package/middleware/mutation-auth-guard.cjs +536 -0
  70. package/middleware/mutation-auth-guard.d.ts +100 -0
  71. package/middleware/mutation-membership-facts.cjs +276 -0
  72. package/middleware/mutation-membership-facts.d.ts +133 -0
  73. package/middleware/mutation-tenant-facts.cjs +132 -0
  74. package/middleware/mutation-tenant-facts.d.ts +81 -0
  75. package/middleware/query-complexity.cjs +182 -0
  76. package/middleware/query-complexity.d.ts +56 -0
  77. package/middleware/rate-limiter.cjs +223 -0
  78. package/middleware/rate-limiter.d.ts +93 -0
  79. package/middleware/rate-tier.cjs +111 -0
  80. package/middleware/rate-tier.d.ts +56 -0
  81. package/middleware/soft-delete.cjs +175 -0
  82. package/middleware/soft-delete.d.ts +146 -0
  83. package/middleware/tenancy-scoping.cjs +229 -0
  84. package/middleware/tenancy-scoping.d.ts +67 -0
  85. package/middleware/trading-policy-audit.cjs +353 -0
  86. package/middleware/trading-policy-audit.d.ts +184 -0
  87. package/middleware/types.cjs +17 -0
  88. package/middleware/types.d.ts +87 -0
  89. package/middleware/validation-examples.cjs +398 -0
  90. package/middleware/validation-examples.d.ts +76 -0
  91. package/package.json +10 -2
  92. package/readers/index.cjs +15 -0
  93. package/readers/index.d.ts +10 -0
  94. package/readers/intraday-lane-prefs.cjs +76 -0
  95. package/readers/intraday-lane-prefs.d.ts +45 -0
  96. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  97. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  98. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  99. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  100. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  101. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  102. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  103. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  104. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  105. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  106. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  107. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  108. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  109. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  110. package/health.cjs +0 -274
  111. package/server.cjs +0 -607
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Audit payload guard: credential values inside `AuditLog` JSON payloads
3
+ * reach only the principals allowed to read those payloads raw.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * The audit trail records what each mutation asked for. An audit logger that
8
+ * copies mutation variables verbatim stores a broker-key update's key and
9
+ * secret in `changedFields` (`data.APIKey.set`, `data.APISecret.set`), and a
10
+ * user create's nested account keys under
11
+ * `input.alpacaAccounts.connectOrCreate[…].create`. Redacting payloads before
12
+ * they are written does not reach rows already stored, and `AuditLog` is
13
+ * readable by any principal the endpoint admits. Without this guard the
14
+ * credential-field guard's server-only rule for a column is bypassed by
15
+ * reading its copy in the audit trail.
16
+ *
17
+ * ## What it guards
18
+ *
19
+ * 1. **Output.** For a principal that may not read payloads raw, the value a
20
+ * payload column resolves to on any output type that carries it
21
+ * (`AuditLog`, `AuditLogGroupBy`, `CreateManyAndReturnAuditLog`, …) goes
22
+ * through {@link redactCredentials} before it leaves the resolver: each
23
+ * credential-named key's value is replaced and the rest of the payload is
24
+ * served as stored. The rule applies where the field resolves, so it covers
25
+ * root reads, aliases, fragments, bulk-write return rows and any type that
26
+ * nests `AuditLog`.
27
+ * 2. **Predicates.** A filter, sort, cursor, `having`, `by` or `distinct` over
28
+ * a payload column is an oracle over whatever the payload holds:
29
+ * `changedFields: { path: ["data", "APISecret", "set"], string_starts_with: "a" }`
30
+ * reads a secret one character at a time without selecting it. Nothing in
31
+ * a JSON filter alone shows that it cannot reach a credential inside the
32
+ * payload, so every predicate over a payload column is refused for the
33
+ * same principals.
34
+ *
35
+ * `server` and `admin` principals read payloads raw; `user` and anonymous
36
+ * callers read them redacted. The mode is the credential-field guard's
37
+ * (`CREDENTIAL_FIELD_GUARD_MODE`, read per request): `shadow` serves payloads
38
+ * as stored and counts every read that enforcement would change, `enforce`
39
+ * redacts and refuses, `off` does neither.
40
+ *
41
+ * @module middleware/audit-payload-guard
42
+ */
43
+ import type { GraphQLResolveInfo } from 'graphql';
44
+ import { type CredentialKeyPath } from '../auth/credential-redaction';
45
+ import type { BackendPrincipal } from '../auth/token-verifier';
46
+ /** JSON payload columns that can hold a copy of a credential, by model. */
47
+ export declare const AUDIT_PAYLOAD_FIELDS: ReadonlyMap<string, ReadonlySet<string>>;
48
+ /** Whether `principal` reads audit payloads as stored. */
49
+ export declare function readsAuditPayloadRaw(principal: BackendPrincipal | null): boolean;
50
+ /**
51
+ * The payload columns an output type carries as values, or `undefined`.
52
+ *
53
+ * @internal Exported for the schema-coverage test.
54
+ */
55
+ export declare function auditPayloadOutputFieldsFor(typeName: string): ReadonlySet<string> | undefined;
56
+ /**
57
+ * The payload columns an input type's keys can reference as a predicate, or
58
+ * `undefined`.
59
+ *
60
+ * @internal Exported for the input walk and the schema-coverage test.
61
+ */
62
+ export declare function auditPayloadPredicateFieldsFor(typeName: string): ReadonlySet<string> | undefined;
63
+ /**
64
+ * The payload columns a `<Model>ScalarFieldEnum` can name, or `undefined`.
65
+ *
66
+ * @internal Exported for the input walk and the schema-coverage test.
67
+ */
68
+ export declare function auditPayloadEnumFieldsFor(typeName: string): ReadonlySet<string> | undefined;
69
+ /** The payload column this resolver outputs, as `TypeName.field`, if any. */
70
+ export declare function auditPayloadOutputField(info: Pick<GraphQLResolveInfo, 'parentType' | 'fieldName'>): string | undefined;
71
+ /** A payload as a principal that may not read it raw receives it. */
72
+ export interface AuditPayloadRedaction {
73
+ /** The payload with every credential value replaced. */
74
+ redacted: unknown;
75
+ /** Where the replaced values were; empty when the payload held none. */
76
+ paths: CredentialKeyPath[];
77
+ }
78
+ /**
79
+ * Redact one payload value and say where its credentials were.
80
+ *
81
+ * @param value - The value a payload column resolved to.
82
+ * @returns The redacted copy and the replaced key paths.
83
+ */
84
+ export declare function redactAuditPayload(value: unknown): AuditPayloadRedaction;
85
+ //# sourceMappingURL=audit-payload-guard.d.ts.map
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.authMiddleware = void 0;
4
+ const token_verifier_1 = require("../auth/token-verifier.cjs");
5
+ const logger_1 = require("../utils/logger.cjs");
6
+ /**
7
+ * Map a verified `BackendPrincipal` to the legacy `req.user` shape used by
8
+ * existing middleware (audit-logger, authorization checks). New consumers
9
+ * should read `req.principal` directly for the typed union.
10
+ */
11
+ function principalToUser(principal) {
12
+ var _a, _b;
13
+ switch (principal.kind) {
14
+ case 'server':
15
+ return { sub: 'server', name: 'Server Auth', role: 'server' };
16
+ case 'admin':
17
+ return {
18
+ sub: principal.sub,
19
+ role: 'admin',
20
+ ...(principal.email ? { name: principal.email } : {}),
21
+ };
22
+ case 'user':
23
+ return {
24
+ sub: principal.sub,
25
+ role: (_b = (_a = principal.roles.find((r) => r !== 'user')) !== null && _a !== void 0 ? _a : principal.roles[0]) !== null && _b !== void 0 ? _b : 'user',
26
+ ...(principal.email ? { name: principal.email } : {}),
27
+ };
28
+ }
29
+ }
30
+ /**
31
+ * Express middleware that establishes the verified principal from the
32
+ * `Authorization: Bearer …` header. Replaces the historical implementation
33
+ * that prefix-matched `ya29.` and accepted any string as a Google OAuth
34
+ * principal without verification.
35
+ *
36
+ * Failure modes:
37
+ * - Missing `Authorization` header -> 401 with `{ error: "unauthorized" }`.
38
+ * - Failed verification -> 401 with `{ error: "invalid_token", reason }`
39
+ * where `reason` is one of the discriminated `AuthErrorReason` values.
40
+ *
41
+ * Success: sets `req.user` (legacy shape) and `req.principal` (typed union),
42
+ * then calls `next()`.
43
+ */
44
+ const authMiddleware = (req, res, next) => {
45
+ const authHeader = req.header('Authorization') || '';
46
+ const token = authHeader.startsWith('Bearer ')
47
+ ? authHeader.slice('Bearer '.length).trim()
48
+ : '';
49
+ if (!token) {
50
+ res.status(401).json({ error: 'unauthorized' });
51
+ return;
52
+ }
53
+ (0, token_verifier_1.verifyBackendToken)(token)
54
+ .then((principal) => {
55
+ req.principal = principal;
56
+ req.user = principalToUser(principal);
57
+ next();
58
+ })
59
+ .catch((e) => {
60
+ const reason = e instanceof token_verifier_1.AuthError ? e.reason : 'bad_signature';
61
+ logger_1.logger.warn('[auth] Express middleware rejected token', { reason });
62
+ res.status(401).json({ error: 'invalid_token', reason });
63
+ });
64
+ };
65
+ exports.authMiddleware = authMiddleware;
66
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1,41 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { JwtPayload } from 'jsonwebtoken';
3
+ import { type BackendPrincipal } from '../auth/token-verifier';
4
+ /**
5
+ * Express request shape with the verified principal attached.
6
+ *
7
+ * Legacy code reads `req.user?.role === 'server'`, `req.user.sub`, etc., so we
8
+ * adapt the `BackendPrincipal` discriminated union into the same shape that
9
+ * `audit-logger` and resolver-side guards already expect.
10
+ */
11
+ interface AuthUser extends JwtPayload {
12
+ provider?: string;
13
+ token?: string;
14
+ name?: string;
15
+ role?: string;
16
+ }
17
+ export interface AuthenticatedRequest extends Request {
18
+ user?: AuthUser | string;
19
+ /**
20
+ * The verified `BackendPrincipal` from `verifyBackendToken`. New consumers
21
+ * should prefer this discriminated union over the legacy `user` shape.
22
+ */
23
+ principal?: BackendPrincipal;
24
+ }
25
+ /**
26
+ * Express middleware that establishes the verified principal from the
27
+ * `Authorization: Bearer …` header. Replaces the historical implementation
28
+ * that prefix-matched `ya29.` and accepted any string as a Google OAuth
29
+ * principal without verification.
30
+ *
31
+ * Failure modes:
32
+ * - Missing `Authorization` header -> 401 with `{ error: "unauthorized" }`.
33
+ * - Failed verification -> 401 with `{ error: "invalid_token", reason }`
34
+ * where `reason` is one of the discriminated `AuthErrorReason` values.
35
+ *
36
+ * Success: sets `req.user` (legacy shape) and `req.principal` (typed union),
37
+ * then calls `next()`.
38
+ */
39
+ export declare const authMiddleware: (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
40
+ export {};
41
+ //# sourceMappingURL=auth.d.ts.map