@adaptic/backend 0.0.1057 → 0.0.1059

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 (114) 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 +339 -0
  20. package/auth/service-token.d.ts +106 -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 +57 -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/esm/auth/service-token.d.ts +12 -0
  41. package/esm/auth/service-token.mjs +27 -5
  42. package/esm/config/jwtConfig.mjs +5 -1
  43. package/generated/typegraphql-prisma/enhance.cjs +3 -3
  44. package/generated/typegraphql-prisma/index.cjs +6 -6
  45. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  46. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  47. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  48. package/middleware/audit-log-write-redaction.cjs +143 -0
  49. package/middleware/audit-log-write-redaction.d.ts +82 -0
  50. package/middleware/audit-logger.cjs +378 -0
  51. package/middleware/audit-logger.d.ts +158 -0
  52. package/middleware/audit-payload-guard.cjs +107 -0
  53. package/middleware/audit-payload-guard.d.ts +85 -0
  54. package/middleware/auth.cjs +66 -0
  55. package/middleware/auth.d.ts +41 -0
  56. package/middleware/credential-field-guard.cjs +514 -0
  57. package/middleware/credential-field-guard.d.ts +173 -0
  58. package/middleware/generated-type-names.cjs +77 -0
  59. package/middleware/generated-type-names.d.ts +44 -0
  60. package/middleware/graphql-validation-plugin.cjs +310 -0
  61. package/middleware/graphql-validation-plugin.d.ts +98 -0
  62. package/middleware/guard-log-throttle.cjs +89 -0
  63. package/middleware/guard-log-throttle.d.ts +80 -0
  64. package/middleware/index.cjs +57 -0
  65. package/middleware/index.d.ts +14 -0
  66. package/middleware/input-validator.cjs +220 -0
  67. package/middleware/input-validator.d.ts +63 -0
  68. package/middleware/mandate-version-validation.cjs +131 -0
  69. package/middleware/mandate-version-validation.d.ts +41 -0
  70. package/middleware/mutation-account-facts.cjs +223 -0
  71. package/middleware/mutation-account-facts.d.ts +143 -0
  72. package/middleware/mutation-auth-guard.cjs +536 -0
  73. package/middleware/mutation-auth-guard.d.ts +100 -0
  74. package/middleware/mutation-membership-facts.cjs +276 -0
  75. package/middleware/mutation-membership-facts.d.ts +133 -0
  76. package/middleware/mutation-tenant-facts.cjs +132 -0
  77. package/middleware/mutation-tenant-facts.d.ts +81 -0
  78. package/middleware/query-complexity.cjs +182 -0
  79. package/middleware/query-complexity.d.ts +56 -0
  80. package/middleware/rate-limiter.cjs +223 -0
  81. package/middleware/rate-limiter.d.ts +93 -0
  82. package/middleware/rate-tier.cjs +111 -0
  83. package/middleware/rate-tier.d.ts +56 -0
  84. package/middleware/soft-delete.cjs +175 -0
  85. package/middleware/soft-delete.d.ts +146 -0
  86. package/middleware/tenancy-scoping.cjs +229 -0
  87. package/middleware/tenancy-scoping.d.ts +67 -0
  88. package/middleware/trading-policy-audit.cjs +353 -0
  89. package/middleware/trading-policy-audit.d.ts +184 -0
  90. package/middleware/types.cjs +17 -0
  91. package/middleware/types.d.ts +87 -0
  92. package/middleware/validation-examples.cjs +398 -0
  93. package/middleware/validation-examples.d.ts +76 -0
  94. package/package.json +10 -2
  95. package/readers/index.cjs +15 -0
  96. package/readers/index.d.ts +10 -0
  97. package/readers/intraday-lane-prefs.cjs +76 -0
  98. package/readers/intraday-lane-prefs.d.ts +45 -0
  99. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  100. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  101. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  102. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  103. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  104. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  105. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  106. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  107. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  108. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  109. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  110. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  111. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  112. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  113. package/health.cjs +0 -274
  114. package/server.cjs +0 -607
@@ -0,0 +1,451 @@
1
+ "use strict";
2
+ /**
3
+ * Verified identity for backend tokens.
4
+ *
5
+ * `verifyBackendToken` is the SOLE entry point for establishing principal
6
+ * identity from a bearer token presented at the GraphQL HTTP, GraphQL WebSocket,
7
+ * or Express middleware layer of `@adaptic/backend`.
8
+ *
9
+ * It rejects, in priority order:
10
+ *
11
+ * 1. **Server-to-server static token.** `process.env.SERVER_AUTH_TOKEN`
12
+ * exact match -> `{ kind: "server" }`. Configured via the environment;
13
+ * never read at request time without a non-empty env value.
14
+ * 2. **App-issued JWT.** `jwt.verify(token, jwtSecret)` against the shared
15
+ * backend `jwtSecret`. Returns `{ kind: "user", sub, roles }` or
16
+ * `{ kind: "admin", … }` when the JWT carries an admin role.
17
+ * 3. **Google ID token.** `OAuth2Client.verifyIdToken({ idToken, audience })`
18
+ * against the configured Google client IDs. Note that an *access* token
19
+ * (`ya29.…`) is NOT an ID token and cannot be verified offline — those
20
+ * are rejected explicitly with reason `opaque_access_token_rejected`.
21
+ *
22
+ * On every failure path, throws an `AuthError` whose `reason` is a finite
23
+ * discriminated string. Callers map `AuthError` to HTTP 401 / GraphQL
24
+ * `UNAUTHENTICATED` extension code at the transport layer.
25
+ *
26
+ * No path silently downgrades to an unverified principal. No path returns
27
+ * `null`. No path logs the token value — only a length and an 8-char prefix
28
+ * masked with an ellipsis.
29
+ *
30
+ * @see backend-legacy/src/auth/__tests__/token-verifier.test.ts for full
31
+ * coverage of every reason branch.
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.AuthError = void 0;
68
+ exports.googleAudienceList = googleAudienceList;
69
+ exports.assertGoogleAudienceConfiguredForProd = assertGoogleAudienceConfiguredForProd;
70
+ exports._resetGoogleAudienceCacheForTests = _resetGoogleAudienceCacheForTests;
71
+ exports.parseRolesFromJWT = parseRolesFromJWT;
72
+ exports.verifyBackendToken = verifyBackendToken;
73
+ const jsonwebtoken_1 = __importStar(require("jsonwebtoken"));
74
+ const google_auth_library_1 = require("google-auth-library");
75
+ const jwtConfig_1 = require("../config/jwtConfig.cjs");
76
+ const logger_1 = require("../utils/logger.cjs");
77
+ const service_token_1 = require("./service-token.cjs");
78
+ /**
79
+ * Typed authentication error. The `reason` discriminates the failure case;
80
+ * callers may map `reason` to a transport-specific error code (HTTP 401,
81
+ * GraphQL `UNAUTHENTICATED`) and a structured log entry.
82
+ *
83
+ * Never include token contents in messages. The `reason` is sufficient.
84
+ */
85
+ class AuthError extends Error {
86
+ constructor(code, reason, message) {
87
+ super(message !== null && message !== void 0 ? message : `${code}: ${reason}`);
88
+ this.name = 'AuthError';
89
+ this.code = code;
90
+ this.reason = reason;
91
+ // Restore prototype chain for `instanceof` after transpilation to ES5/CJS.
92
+ Object.setPrototypeOf(this, AuthError.prototype);
93
+ }
94
+ }
95
+ exports.AuthError = AuthError;
96
+ // -----------------------------------------------------------------------------
97
+ // Configuration: Google audience allowlist
98
+ // -----------------------------------------------------------------------------
99
+ /**
100
+ * Sentinel for the lazy-cached Google audience list. We resolve at first call
101
+ * rather than at module load so tests can set `process.env.GOOGLE_OAUTH_CLIENT_IDS`
102
+ * before importing this module without import-order dance.
103
+ */
104
+ let cachedAudienceList;
105
+ let cachedAudienceListResolved = false;
106
+ /**
107
+ * Resolve the comma-separated list of accepted Google OAuth client IDs from
108
+ * `GOOGLE_OAUTH_CLIENT_IDS`.
109
+ *
110
+ * - In production (`NODE_ENV=production`): if the env is missing or empty,
111
+ * throw `AuthError("invalid_token", "misconfigured")` at the FIRST call.
112
+ * This serialises the failure into the request response rather than crashing
113
+ * the process; the boot-time invariant check at `assertGoogleAudienceConfiguredForProd`
114
+ * handles fail-fast-at-startup.
115
+ * - In dev/test: log a single warning and return `[]`. With an empty audience
116
+ * list, the Google ID-token verification branch will always fail — acceptable
117
+ * in non-prod because trusted paths use `SERVER_AUTH_TOKEN` or app JWTs.
118
+ *
119
+ * @internal exported for testing
120
+ */
121
+ function googleAudienceList() {
122
+ var _a;
123
+ if (cachedAudienceListResolved) {
124
+ return cachedAudienceList !== null && cachedAudienceList !== void 0 ? cachedAudienceList : [];
125
+ }
126
+ const raw = ((_a = process.env.GOOGLE_OAUTH_CLIENT_IDS) !== null && _a !== void 0 ? _a : '').trim();
127
+ const isProd = process.env.NODE_ENV === 'production';
128
+ if (raw.length === 0) {
129
+ if (isProd) {
130
+ // Do not cache the empty list in prod — we want subsequent verifier
131
+ // calls to surface the misconfiguration too.
132
+ throw new AuthError('invalid_token', 'misconfigured', 'GOOGLE_OAUTH_CLIENT_IDS is required in production but is not set');
133
+ }
134
+ logger_1.logger.warn('[auth] GOOGLE_OAUTH_CLIENT_IDS is not set; Google ID-token verification will reject all tokens until configured. This is acceptable for local dev only.');
135
+ cachedAudienceList = [];
136
+ cachedAudienceListResolved = true;
137
+ return cachedAudienceList;
138
+ }
139
+ const list = raw
140
+ .split(',')
141
+ .map((s) => s.trim())
142
+ .filter((s) => s.length > 0);
143
+ cachedAudienceList = list;
144
+ cachedAudienceListResolved = true;
145
+ return list;
146
+ }
147
+ /**
148
+ * Boot-time invariant: in production, require `GOOGLE_OAUTH_CLIENT_IDS` to be
149
+ * a non-empty allowlist. Call this once during server startup so the process
150
+ * refuses to boot with an invalid identity configuration.
151
+ *
152
+ * Throws a plain `Error` (not `AuthError`) so the startup harness logs it as
153
+ * a fatal config error rather than a per-request auth failure.
154
+ */
155
+ function assertGoogleAudienceConfiguredForProd() {
156
+ var _a;
157
+ const isProd = process.env.NODE_ENV === 'production';
158
+ if (!isProd)
159
+ return;
160
+ const raw = ((_a = process.env.GOOGLE_OAUTH_CLIENT_IDS) !== null && _a !== void 0 ? _a : '').trim();
161
+ if (raw.length === 0) {
162
+ const msg = '[SECURITY] FATAL: GOOGLE_OAUTH_CLIENT_IDS is required in production. ' +
163
+ 'Set it to a comma-separated allowlist of Google OAuth client IDs ' +
164
+ '(e.g. "1234.apps.googleusercontent.com,5678.apps.googleusercontent.com"). ' +
165
+ 'Without this, no Google ID token can be safely verified.';
166
+ logger_1.logger.error(msg);
167
+ throw new Error('GOOGLE_OAUTH_CLIENT_IDS is required in production. Set it to a comma-separated list of accepted Google OAuth client IDs.');
168
+ }
169
+ }
170
+ /**
171
+ * Test-only escape hatch to reset the cached audience list. Wired into the
172
+ * public surface so tests in this package can mutate env between cases and
173
+ * have the next call to `googleAudienceList()` re-read the environment.
174
+ *
175
+ * @internal
176
+ */
177
+ function _resetGoogleAudienceCacheForTests() {
178
+ cachedAudienceList = undefined;
179
+ cachedAudienceListResolved = false;
180
+ }
181
+ // -----------------------------------------------------------------------------
182
+ // OAuth2Client singleton
183
+ // -----------------------------------------------------------------------------
184
+ /**
185
+ * Lazy-instantiated `OAuth2Client`. Constructing one is cheap, but doing it at
186
+ * module load would force the test suite to mock `google-auth-library` before
187
+ * any unrelated import path touches this module. Lazy avoids that fragility.
188
+ */
189
+ let oauthClient;
190
+ function getOAuthClient() {
191
+ if (!oauthClient) {
192
+ oauthClient = new google_auth_library_1.OAuth2Client();
193
+ }
194
+ return oauthClient;
195
+ }
196
+ // -----------------------------------------------------------------------------
197
+ // Helpers
198
+ // -----------------------------------------------------------------------------
199
+ /**
200
+ * Extract a roles array from a verified JWT payload, normalising the two
201
+ * shapes the platform emits:
202
+ * - `{ roles: ["user", "admin"] }` (preferred)
203
+ * - `{ role: "admin" }` (legacy single-string)
204
+ *
205
+ * Returns an empty array when neither claim is present. The Apollo `AuthChecker`
206
+ * treats an empty roles array as "authenticated user with no privileged role".
207
+ */
208
+ function parseRolesFromJWT(payload) {
209
+ if (!payload || typeof payload === 'string')
210
+ return [];
211
+ const out = [];
212
+ const rolesClaim = payload.roles;
213
+ if (Array.isArray(rolesClaim)) {
214
+ for (const r of rolesClaim) {
215
+ if (typeof r === 'string' && r.length > 0)
216
+ out.push(r);
217
+ }
218
+ }
219
+ const roleClaim = payload.role;
220
+ if (typeof roleClaim === 'string' && roleClaim.length > 0) {
221
+ if (!out.includes(roleClaim))
222
+ out.push(roleClaim);
223
+ }
224
+ return out;
225
+ }
226
+ /**
227
+ * Redact a token for safe logging. Returns the first 8 characters followed by
228
+ * an ellipsis and the total length. Never returns the full token.
229
+ */
230
+ function redactToken(token) {
231
+ if (!token)
232
+ return '<empty>';
233
+ if (token.length <= 8)
234
+ return `<len=${token.length}>`;
235
+ return `${token.slice(0, 8)}…<len=${token.length}>`;
236
+ }
237
+ /**
238
+ * Classify a JWT verification failure into a discriminated `AuthErrorReason`.
239
+ * `jsonwebtoken` throws specific subclasses we can branch on; falls back to
240
+ * `bad_signature` for the generic case.
241
+ */
242
+ function classifyJwtError(error) {
243
+ if (error instanceof jsonwebtoken_1.TokenExpiredError)
244
+ return 'expired';
245
+ if (error instanceof jsonwebtoken_1.JsonWebTokenError) {
246
+ const msg = (error.message || '').toLowerCase();
247
+ if (msg.includes('malformed') || msg.includes('jwt must be')) {
248
+ return 'malformed';
249
+ }
250
+ return 'bad_signature';
251
+ }
252
+ return 'bad_signature';
253
+ }
254
+ // -----------------------------------------------------------------------------
255
+ // Main entry point
256
+ // -----------------------------------------------------------------------------
257
+ /**
258
+ * Verify a bearer token and return a typed `BackendPrincipal`.
259
+ *
260
+ * Throws `AuthError("invalid_token", reason)` on every failure path. Callers
261
+ * are required to handle the throw — there is no silent fallback to an
262
+ * unauthenticated principal.
263
+ *
264
+ * Structural validation pipeline:
265
+ *
266
+ * - Empty or whitespace-only -> `malformed`.
267
+ * - Exact match with `SERVER_AUTH_TOKEN` -> `{ kind: "server" }`.
268
+ * - HS256 JWT signed with `BACKEND_SERVICE_JWT_SECRET`, issuer `adaptic-service`,
269
+ * audience `adaptic-backend` -> `{ kind: "server" }`. See `./service-token`.
270
+ * - Single segment (no dots) -> `opaque_access_token_rejected`. This is the
271
+ * structural catch for OAuth access tokens, which cannot be verified offline.
272
+ * - Exactly 3 dot-separated segments -> attempt local JWT verify, then Google
273
+ * ID-token verify. The Google branch only runs if the local JWT branch
274
+ * fails AND the configured Google audience list is non-empty.
275
+ * - Any other segment count -> `malformed`.
276
+ *
277
+ * @param token Raw bearer token (the value after `Bearer ` in the header).
278
+ * @returns A verified `BackendPrincipal` on success.
279
+ * @throws `AuthError` on any failure.
280
+ */
281
+ async function verifyBackendToken(token) {
282
+ var _a;
283
+ // ---- structural rejection of empty input ---------------------------------
284
+ if (typeof token !== 'string' || token.trim().length === 0) {
285
+ throw new AuthError('invalid_token', 'malformed');
286
+ }
287
+ // ---- path 1: server-to-server static token -------------------------------
288
+ // Read once per call so a runtime env change is honoured. The exact-match
289
+ // check guards against the historical bug of allowing the empty string to
290
+ // authenticate when SERVER_AUTH_TOKEN is unset.
291
+ const serverAuthToken = process.env.SERVER_AUTH_TOKEN;
292
+ if (typeof serverAuthToken === 'string' &&
293
+ serverAuthToken.length > 0 &&
294
+ token === serverAuthToken) {
295
+ return { kind: 'server' };
296
+ }
297
+ // ---- structural classification --------------------------------------------
298
+ const segments = token.split('.');
299
+ // Single segment (no dots) -> opaque OAuth access token (or similar).
300
+ // These tokens (ya29.…, but technically any non-dotted bearer) cannot be
301
+ // verified offline. Reject explicitly so the caller surfaces a clear reason.
302
+ if (segments.length === 1) {
303
+ logger_1.logger.warn('[auth] opaque access token rejected', {
304
+ tokenPrefix: redactToken(token),
305
+ });
306
+ throw new AuthError('invalid_token', 'opaque_access_token_rejected');
307
+ }
308
+ // Anything other than 3 segments is not a valid JWT or Google ID token.
309
+ // This catches the historical `ya29.<single-payload>` form (2 segments) and
310
+ // any other malformed shape.
311
+ if (segments.length !== 3) {
312
+ logger_1.logger.warn('[auth] malformed token rejected', {
313
+ tokenPrefix: redactToken(token),
314
+ segmentCount: segments.length,
315
+ });
316
+ throw new AuthError('invalid_token', 'malformed');
317
+ }
318
+ // ---- path 1b: dedicated service credential -------------------------------
319
+ // Checked before the app-JWT path because a service credential is signed
320
+ // with a DIFFERENT secret: reaching path 2 first would classify it as
321
+ // `bad_signature` and report an unprovisioned-service outage as a forgery.
322
+ // Returns null when the path is unprovisioned or the signature is not ours,
323
+ // which leaves every existing token's behaviour byte-identical.
324
+ const servicePrincipal = (0, service_token_1.verifyServiceToken)(token);
325
+ if (servicePrincipal !== null) {
326
+ return servicePrincipal;
327
+ }
328
+ // ---- path 2: app-issued JWT ----------------------------------------------
329
+ // Try local JWT verification first. On success, return a user principal.
330
+ // On failure, capture the reason but DO NOT throw yet — we may still be
331
+ // looking at a Google ID token, which is structurally a JWT signed by Google.
332
+ let localJwtFailure;
333
+ try {
334
+ // Pin algorithm to HS256. Without this, `jsonwebtoken.verify` accepts
335
+ // `alg: "none"` (silently!) for older versions of the library — a
336
+ // well-known footgun where an attacker forges an unsigned token and
337
+ // the server accepts it as authentic. Pinning also ensures forward
338
+ // compatibility: if we ever sign with a different alg, every verifier
339
+ // is forced to update in lockstep with the signer.
340
+ const payload = jsonwebtoken_1.default.verify(token, jwtConfig_1.jwtSecret, { algorithms: ['HS256'] });
341
+ if (typeof payload === 'string') {
342
+ // String-payload JWTs are not used by this platform and carry no claims
343
+ // we can convert into a principal. Treat as malformed.
344
+ throw new AuthError('invalid_token', 'malformed');
345
+ }
346
+ const sub = typeof payload.sub === 'string' ? payload.sub : undefined;
347
+ if (!sub) {
348
+ // No sub claim -> no principal. Treat as malformed identity.
349
+ throw new AuthError('invalid_token', 'malformed');
350
+ }
351
+ const roles = parseRolesFromJWT(payload);
352
+ const isAdmin = roles.includes('admin');
353
+ const emailClaim = payload.email;
354
+ const email = typeof emailClaim === 'string' && emailClaim.length > 0
355
+ ? emailClaim
356
+ : undefined;
357
+ return isAdmin
358
+ ? { kind: 'admin', sub, email, roles }
359
+ : { kind: 'user', sub, email, roles };
360
+ }
361
+ catch (e) {
362
+ // AuthError thrown from inside the try-block (e.g. no-sub case) must
363
+ // propagate without being reclassified.
364
+ if (e instanceof AuthError) {
365
+ throw e;
366
+ }
367
+ localJwtFailure = classifyJwtError(e);
368
+ // Expired tokens are unambiguous: we know they were signed by us. Surface
369
+ // the expiry reason immediately rather than falling through to Google.
370
+ if (localJwtFailure === 'expired') {
371
+ throw new AuthError('invalid_token', 'expired');
372
+ }
373
+ // Otherwise, fall through to Google ID-token verification below.
374
+ }
375
+ // ---- path 3: Google ID token ---------------------------------------------
376
+ // Only attempt Google verification when an audience list is configured.
377
+ // The list is empty in dev/test by default, which causes this branch to
378
+ // throw the most-precise reason from the local JWT path above.
379
+ const audience = googleAudienceList();
380
+ if (audience.length === 0) {
381
+ // No Google verification possible. Bubble up the local JWT reason.
382
+ throw new AuthError('invalid_token', localJwtFailure !== null && localJwtFailure !== void 0 ? localJwtFailure : 'bad_signature');
383
+ }
384
+ // A 3-segment token reaching this point is presumed to be either a Google
385
+ // ID token or a forgery. Local JWT verify against our secret has already
386
+ // failed (otherwise we returned above). We surface Google's diagnosis as
387
+ // the authoritative one — `localJwtFailure` is captured only for the case
388
+ // where the audience list is empty (handled above) so we can bubble the
389
+ // best-available signal to the caller.
390
+ let ticketResult;
391
+ try {
392
+ ticketResult = await getOAuthClient().verifyIdToken({
393
+ idToken: token,
394
+ audience,
395
+ });
396
+ }
397
+ catch (e) {
398
+ // google-auth-library throws plain Errors with messages like
399
+ // "Wrong recipient, payload audience != requiredAudience" for bad audience,
400
+ // "Token used too late" for expiry, and "Invalid token signature" for
401
+ // tampering. Classify into the closest discriminated reason.
402
+ const msg = e instanceof Error ? e.message.toLowerCase() : '';
403
+ logger_1.logger.warn('[auth] Google ID token verification failed', {
404
+ tokenPrefix: redactToken(token),
405
+ errorMessage: e instanceof Error ? e.message : 'unknown',
406
+ localJwtReason: localJwtFailure !== null && localJwtFailure !== void 0 ? localJwtFailure : 'n/a',
407
+ });
408
+ if (msg.includes('used too late') || msg.includes('expired')) {
409
+ throw new AuthError('invalid_token', 'expired');
410
+ }
411
+ if (msg.includes('signature') || msg.includes('invalid token')) {
412
+ throw new AuthError('invalid_token', 'bad_signature');
413
+ }
414
+ // Default classification for Google verification failures is
415
+ // `bad_audience` — BUT: when local-JWT path 2 already failed (the
416
+ // common case, since the app mints HS256 tokens that Google cannot
417
+ // recognise), the user is almost certainly NOT presenting a Google
418
+ // ID token at all. Surfacing `bad_audience` in that case hides the
419
+ // real upstream failure (typically `bad_signature` from path 2)
420
+ // behind an irrelevant fallback diagnosis. Prefer the local-JWT
421
+ // reason when present; only fall back to `bad_audience` when there
422
+ // is no local-JWT failure to bubble (i.e. a token that decoded as
423
+ // a JWT but somehow didn't reach the local-JWT branch — defensive).
424
+ throw new AuthError('invalid_token', localJwtFailure !== null && localJwtFailure !== void 0 ? localJwtFailure : 'bad_audience');
425
+ }
426
+ // ticketResult must be defined here because the catch above always throws.
427
+ const payload = (_a = ticketResult === null || ticketResult === void 0 ? void 0 : ticketResult.getPayload) === null || _a === void 0 ? void 0 : _a.call(ticketResult);
428
+ if (!payload) {
429
+ // Google verified the token but returned no payload — treat as a
430
+ // signature failure since we cannot extract a principal.
431
+ logger_1.logger.warn('[auth] Google verifyIdToken returned no payload', {
432
+ tokenPrefix: redactToken(token),
433
+ });
434
+ throw new AuthError('invalid_token', 'bad_signature');
435
+ }
436
+ const sub = payload.sub;
437
+ if (typeof sub !== 'string' || sub.length === 0) {
438
+ // No `sub` claim from Google -> no principal we can use.
439
+ logger_1.logger.warn('[auth] Google payload missing sub claim', {
440
+ tokenPrefix: redactToken(token),
441
+ });
442
+ throw new AuthError('invalid_token', 'bad_signature');
443
+ }
444
+ return {
445
+ kind: 'user',
446
+ sub,
447
+ email: typeof payload.email === 'string' ? payload.email : undefined,
448
+ roles: ['user'],
449
+ };
450
+ }
451
+ //# sourceMappingURL=token-verifier.js.map
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Verified identity for backend tokens.
3
+ *
4
+ * `verifyBackendToken` is the SOLE entry point for establishing principal
5
+ * identity from a bearer token presented at the GraphQL HTTP, GraphQL WebSocket,
6
+ * or Express middleware layer of `@adaptic/backend`.
7
+ *
8
+ * It rejects, in priority order:
9
+ *
10
+ * 1. **Server-to-server static token.** `process.env.SERVER_AUTH_TOKEN`
11
+ * exact match -> `{ kind: "server" }`. Configured via the environment;
12
+ * never read at request time without a non-empty env value.
13
+ * 2. **App-issued JWT.** `jwt.verify(token, jwtSecret)` against the shared
14
+ * backend `jwtSecret`. Returns `{ kind: "user", sub, roles }` or
15
+ * `{ kind: "admin", … }` when the JWT carries an admin role.
16
+ * 3. **Google ID token.** `OAuth2Client.verifyIdToken({ idToken, audience })`
17
+ * against the configured Google client IDs. Note that an *access* token
18
+ * (`ya29.…`) is NOT an ID token and cannot be verified offline — those
19
+ * are rejected explicitly with reason `opaque_access_token_rejected`.
20
+ *
21
+ * On every failure path, throws an `AuthError` whose `reason` is a finite
22
+ * discriminated string. Callers map `AuthError` to HTTP 401 / GraphQL
23
+ * `UNAUTHENTICATED` extension code at the transport layer.
24
+ *
25
+ * No path silently downgrades to an unverified principal. No path returns
26
+ * `null`. No path logs the token value — only a length and an 8-char prefix
27
+ * masked with an ellipsis.
28
+ *
29
+ * @see backend-legacy/src/auth/__tests__/token-verifier.test.ts for full
30
+ * coverage of every reason branch.
31
+ */
32
+ import jwt from 'jsonwebtoken';
33
+ /**
34
+ * Finite, discriminated set of reasons `verifyBackendToken` can fail.
35
+ *
36
+ * The set is closed by design: every new failure mode added to the verifier
37
+ * must be classified into one of these reasons (or a new reason added here
38
+ * with explicit consumer-side handling).
39
+ */
40
+ export type AuthErrorReason = 'malformed' | 'expired' | 'bad_audience' | 'bad_signature' | 'opaque_access_token_rejected' | 'misconfigured';
41
+ /**
42
+ * Backend principal — the verified caller identity attached to a request.
43
+ *
44
+ * - `server`: trusted server-to-server caller (Next.js route handler, internal
45
+ * service). Authenticated by the static `SERVER_AUTH_TOKEN` (no `sub`: the
46
+ * static token names no caller) or by a service JWT, whose `sub` names the
47
+ * minting process so audit rows can attribute a service write.
48
+ * - `user`: end-user authenticated via app-issued JWT or Google ID token.
49
+ * - `admin`: same as `user` but with an `admin` role explicitly listed.
50
+ *
51
+ * The discriminator is `kind`. Callers `switch` on `kind` and the TypeScript
52
+ * compiler enforces exhaustive handling.
53
+ */
54
+ export type BackendPrincipal = {
55
+ kind: 'server';
56
+ /**
57
+ * The `sub` a signed service credential names (e.g.
58
+ * `adaptic-engine:<host>:<pid>`). Absent for the static
59
+ * `SERVER_AUTH_TOKEN`, which names no caller.
60
+ */
61
+ sub?: string;
62
+ } | {
63
+ kind: 'user';
64
+ sub: string;
65
+ email?: string;
66
+ roles: string[];
67
+ } | {
68
+ kind: 'admin';
69
+ sub: string;
70
+ email?: string;
71
+ roles: string[];
72
+ };
73
+ /**
74
+ * Typed authentication error. The `reason` discriminates the failure case;
75
+ * callers may map `reason` to a transport-specific error code (HTTP 401,
76
+ * GraphQL `UNAUTHENTICATED`) and a structured log entry.
77
+ *
78
+ * Never include token contents in messages. The `reason` is sufficient.
79
+ */
80
+ export declare class AuthError extends Error {
81
+ readonly code: 'invalid_token';
82
+ readonly reason: AuthErrorReason;
83
+ constructor(code: 'invalid_token', reason: AuthErrorReason, message?: string);
84
+ }
85
+ /**
86
+ * Resolve the comma-separated list of accepted Google OAuth client IDs from
87
+ * `GOOGLE_OAUTH_CLIENT_IDS`.
88
+ *
89
+ * - In production (`NODE_ENV=production`): if the env is missing or empty,
90
+ * throw `AuthError("invalid_token", "misconfigured")` at the FIRST call.
91
+ * This serialises the failure into the request response rather than crashing
92
+ * the process; the boot-time invariant check at `assertGoogleAudienceConfiguredForProd`
93
+ * handles fail-fast-at-startup.
94
+ * - In dev/test: log a single warning and return `[]`. With an empty audience
95
+ * list, the Google ID-token verification branch will always fail — acceptable
96
+ * in non-prod because trusted paths use `SERVER_AUTH_TOKEN` or app JWTs.
97
+ *
98
+ * @internal exported for testing
99
+ */
100
+ export declare function googleAudienceList(): string[];
101
+ /**
102
+ * Boot-time invariant: in production, require `GOOGLE_OAUTH_CLIENT_IDS` to be
103
+ * a non-empty allowlist. Call this once during server startup so the process
104
+ * refuses to boot with an invalid identity configuration.
105
+ *
106
+ * Throws a plain `Error` (not `AuthError`) so the startup harness logs it as
107
+ * a fatal config error rather than a per-request auth failure.
108
+ */
109
+ export declare function assertGoogleAudienceConfiguredForProd(): void;
110
+ /**
111
+ * Test-only escape hatch to reset the cached audience list. Wired into the
112
+ * public surface so tests in this package can mutate env between cases and
113
+ * have the next call to `googleAudienceList()` re-read the environment.
114
+ *
115
+ * @internal
116
+ */
117
+ export declare function _resetGoogleAudienceCacheForTests(): void;
118
+ /**
119
+ * Extract a roles array from a verified JWT payload, normalising the two
120
+ * shapes the platform emits:
121
+ * - `{ roles: ["user", "admin"] }` (preferred)
122
+ * - `{ role: "admin" }` (legacy single-string)
123
+ *
124
+ * Returns an empty array when neither claim is present. The Apollo `AuthChecker`
125
+ * treats an empty roles array as "authenticated user with no privileged role".
126
+ */
127
+ export declare function parseRolesFromJWT(payload: jwt.JwtPayload | string | undefined): string[];
128
+ /**
129
+ * Verify a bearer token and return a typed `BackendPrincipal`.
130
+ *
131
+ * Throws `AuthError("invalid_token", reason)` on every failure path. Callers
132
+ * are required to handle the throw — there is no silent fallback to an
133
+ * unauthenticated principal.
134
+ *
135
+ * Structural validation pipeline:
136
+ *
137
+ * - Empty or whitespace-only -> `malformed`.
138
+ * - Exact match with `SERVER_AUTH_TOKEN` -> `{ kind: "server" }`.
139
+ * - HS256 JWT signed with `BACKEND_SERVICE_JWT_SECRET`, issuer `adaptic-service`,
140
+ * audience `adaptic-backend` -> `{ kind: "server" }`. See `./service-token`.
141
+ * - Single segment (no dots) -> `opaque_access_token_rejected`. This is the
142
+ * structural catch for OAuth access tokens, which cannot be verified offline.
143
+ * - Exactly 3 dot-separated segments -> attempt local JWT verify, then Google
144
+ * ID-token verify. The Google branch only runs if the local JWT branch
145
+ * fails AND the configured Google audience list is non-empty.
146
+ * - Any other segment count -> `malformed`.
147
+ *
148
+ * @param token Raw bearer token (the value after `Bearer ` in the header).
149
+ * @returns A verified `BackendPrincipal` on success.
150
+ * @throws `AuthError` on any failure.
151
+ */
152
+ export declare function verifyBackendToken(token: string): Promise<BackendPrincipal>;
153
+ //# sourceMappingURL=token-verifier.d.ts.map