@adaptic/backend 0.0.1048 → 0.0.1050

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 (38) hide show
  1. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +5 -0
  2. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -1
  3. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -1
  4. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +38 -8
  5. package/esm/middleware/credential-field-guard.d.ts +7 -1
  6. package/esm/middleware/credential-field-guard.d.ts.map +1 -1
  7. package/esm/middleware/credential-field-guard.js.map +1 -1
  8. package/esm/middleware/credential-field-guard.mjs +7 -2
  9. package/esm/middleware/mutation-auth-guard.d.ts +16 -0
  10. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -1
  11. package/esm/middleware/mutation-auth-guard.js.map +1 -1
  12. package/esm/middleware/mutation-auth-guard.mjs +68 -0
  13. package/esm/resolvers/custom/AccountEquityCurveResolver.d.ts +32 -0
  14. package/esm/resolvers/custom/AccountEquityCurveResolver.d.ts.map +1 -0
  15. package/esm/resolvers/custom/AccountEquityCurveResolver.js.map +1 -0
  16. package/esm/resolvers/custom/AccountEquityCurveResolver.mjs +206 -0
  17. package/esm/resolvers/custom/account-audit-read.d.ts +182 -0
  18. package/esm/resolvers/custom/account-audit-read.d.ts.map +1 -0
  19. package/esm/resolvers/custom/account-audit-read.js.map +1 -0
  20. package/esm/resolvers/custom/account-audit-read.mjs +315 -0
  21. package/esm/resolvers/custom/index.d.ts +1 -0
  22. package/esm/resolvers/custom/index.d.ts.map +1 -1
  23. package/esm/resolvers/custom/index.js.map +1 -1
  24. package/esm/resolvers/custom/index.mjs +1 -0
  25. package/package.json +1 -1
  26. package/resolvers/custom/AccountEquityCurveResolver.cjs +233 -0
  27. package/resolvers/custom/AccountEquityCurveResolver.d.ts +32 -0
  28. package/resolvers/custom/AccountEquityCurveResolver.d.ts.map +1 -0
  29. package/resolvers/custom/AccountEquityCurveResolver.js.map +1 -0
  30. package/resolvers/custom/account-audit-read.cjs +333 -0
  31. package/resolvers/custom/account-audit-read.d.ts +182 -0
  32. package/resolvers/custom/account-audit-read.d.ts.map +1 -0
  33. package/resolvers/custom/account-audit-read.js.map +1 -0
  34. package/resolvers/custom/index.cjs +5 -1
  35. package/resolvers/custom/index.d.ts +1 -0
  36. package/resolvers/custom/index.d.ts.map +1 -1
  37. package/resolvers/custom/index.js.map +1 -1
  38. package/server.cjs +1 -0
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Server-side audit read of an account's equity curve.
3
+ *
4
+ * The audit toolkit used to read an account's broker key and secret and call
5
+ * Alpaca itself, which meant issuing an audit principal handed out live broker
6
+ * credentials. This read moves the Alpaca call here: the caller names an
7
+ * account and receives the curve, and the key never leaves this process.
8
+ *
9
+ * Everything in this module is pure or takes its collaborators as arguments
10
+ * (`fetchImpl`, `nowMs`), so it is unit-testable without a database or network.
11
+ *
12
+ * @module resolvers/custom/account-audit-read
13
+ */
14
+ import { GraphQLError } from 'graphql';
15
+ import jwt from 'jsonwebtoken';
16
+ import { logger } from '../../utils/logger.mjs';
17
+ /** `sub` prefix the audit toolkit mints (`adaptic-audit:<who>@<host>:<pid>`). */
18
+ export const AUDIT_SUBJECT_PREFIX = 'adaptic-audit:';
19
+ /** Env var holding the comma-separated operators admitted to the audit-read role. */
20
+ export const AUDIT_READ_OPERATORS_ENV = 'AUDIT_READ_OPERATORS';
21
+ /** Env var holding the HS256 secret that signs audit-read tokens, and nothing else. */
22
+ export const AUDIT_READ_JWT_SECRET_ENV = 'AUDIT_READ_JWT_SECRET';
23
+ /**
24
+ * Request header the audit token travels in.
25
+ *
26
+ * Not `Authorization`: the shared verifier would refuse a token it cannot
27
+ * verify with HTTP 401 before any resolver ran, and teaching it this secret
28
+ * would make audit-read one more way to become a `server` principal. A
29
+ * separate header keeps the two trust roots apart.
30
+ */
31
+ export const AUDIT_READ_TOKEN_HEADER = 'x-adaptic-audit-token';
32
+ /** Issuer every audit-read token must carry. */
33
+ export const AUDIT_READ_ISSUER = 'adaptic-audit';
34
+ /** Audience every audit-read token must carry. */
35
+ export const AUDIT_READ_AUDIENCE = 'adaptic-backend:audit-read';
36
+ /** Minimum length for the audit-read secret, in characters. */
37
+ export const MINIMUM_AUDIT_SECRET_LENGTH = 32;
38
+ /** Largest lifetime (`exp - iat`) honoured on an audit-read token, and the longest it is accepted ahead of its `exp`, seconds. */
39
+ export const MAX_AUDIT_TOKEN_LIFETIME_SEC = 300;
40
+ /** How far in the future an `iat` may sit before the token is refused, seconds. */
41
+ export const MAX_AUDIT_TOKEN_CLOCK_SKEW_SEC = 60;
42
+ /** Upstream Alpaca requests allowed per account per window, shared by every operator reading it. */
43
+ export const ACCOUNT_REQUEST_BUDGET = 40;
44
+ /** Length of the per-account budget window, ms. */
45
+ export const ACCOUNT_BUDGET_WINDOW_MS = 60_000;
46
+ /** Longest one Alpaca request may take before it is abandoned, ms. */
47
+ export const ALPACA_TIMEOUT_MS = 10_000;
48
+ const PAPER_TRADE_HOST = 'https://paper-api.alpaca.markets';
49
+ /**
50
+ * A sliding-window request budget per account.
51
+ *
52
+ * Audit reads spend the book's own trading key, so the window is keyed on the
53
+ * account (the key being protected), not the operator: several operators on one
54
+ * book share one budget, and the engine's order traffic cannot be starved. State is
55
+ * in-process: with several backend instances the effective ceiling is the
56
+ * budget times the instance count, still bounded.
57
+ *
58
+ * @param limit - Requests allowed per window.
59
+ * @param windowMs - Window length.
60
+ * @param now - Clock, injectable for tests.
61
+ * @returns A function that returns the account's `RequestBudget`.
62
+ */
63
+ export function createAccountBudgets(limit = ACCOUNT_REQUEST_BUDGET, windowMs = ACCOUNT_BUDGET_WINDOW_MS, now = Date.now) {
64
+ const spent = new Map();
65
+ return (accountId) => (n = 1) => {
66
+ const t = now();
67
+ const live = (spent.get(accountId) ?? []).filter((at) => at > t - windowMs);
68
+ if (live.length + n > limit) {
69
+ spent.set(accountId, live);
70
+ throw new GraphQLError('Audit read rate budget exhausted; retry shortly', {
71
+ extensions: { code: 'RATE_LIMITED', retryAfterMs: windowMs },
72
+ });
73
+ }
74
+ for (let i = 0; i < n; i++)
75
+ live.push(t);
76
+ spent.set(accountId, live);
77
+ };
78
+ }
79
+ /**
80
+ * The audit-read token from a request's headers, or null when absent.
81
+ *
82
+ * A repeated header arrives as an array and is refused rather than guessed at.
83
+ */
84
+ export function auditTokenFromHeaders(headers) {
85
+ const raw = headers?.[AUDIT_READ_TOKEN_HEADER];
86
+ if (typeof raw !== 'string')
87
+ return null;
88
+ const token = raw.trim();
89
+ return token.length > 0 ? token : null;
90
+ }
91
+ /**
92
+ * The audit-read role, enforced in the resolver.
93
+ *
94
+ * Fail-closed, and independent of the request's principal. A `server`
95
+ * principal otherwise bypasses every role gate and `@Authorized()` is
96
+ * shadow-first, so neither can carry this; and any holder of the shared
97
+ * service secret can mint a `server` principal with whatever `sub` it likes.
98
+ * So the caller must present a token signed with `AUDIT_READ_JWT_SECRET`, a
99
+ * secret with no other use, bound to this issuer and audience, short-lived,
100
+ * whose `sub` is `adaptic-audit:<who>@…` with `<who>` in
101
+ * `AUDIT_READ_OPERATORS`. A token signed with any other secret is refused
102
+ * whatever its `sub` says. An unset secret or an empty list admits nobody.
103
+ *
104
+ * @param token - The raw audit-read token, or null/undefined when absent.
105
+ * @param env - Environment to read the secret and operator list from.
106
+ * @param nowSec - Current time, seconds since the epoch.
107
+ * @returns The operator the read is attributed to.
108
+ * @throws {GraphQLError} `UNAUTHENTICATED` without a token, `FORBIDDEN` otherwise.
109
+ */
110
+ export function assertAuditRead(token, env = process.env, nowSec = Math.floor(Date.now() / 1000)) {
111
+ if (!token) {
112
+ throw new GraphQLError('Authentication required', { extensions: { code: 'UNAUTHENTICATED' } });
113
+ }
114
+ const forbidden = () => {
115
+ throw new GraphQLError('audit-read role required', { extensions: { code: 'FORBIDDEN' } });
116
+ };
117
+ const secret = (env[AUDIT_READ_JWT_SECRET_ENV] ?? '').trim();
118
+ if (secret.length < MINIMUM_AUDIT_SECRET_LENGTH) {
119
+ if (secret.length > 0) {
120
+ logger.error(`[audit-read] ${AUDIT_READ_JWT_SECRET_ENV} is shorter than ${MINIMUM_AUDIT_SECRET_LENGTH} characters; audit reads are disabled.`);
121
+ }
122
+ return forbidden();
123
+ }
124
+ // Equal to any other trust root collapses the separation this secret exists for.
125
+ const others = [
126
+ env.BACKEND_SERVICE_JWT_SECRET,
127
+ env.BACKEND_SERVICE_JWT_SECRET_PREVIOUS,
128
+ env.JWT_SECRET,
129
+ env.NEXTAUTH_SECRET,
130
+ ].map((v) => (v ?? '').trim());
131
+ if (others.includes(secret)) {
132
+ logger.error(`[audit-read] ${AUDIT_READ_JWT_SECRET_ENV} equals another auth secret; audit reads are disabled until it is distinct.`);
133
+ return forbidden();
134
+ }
135
+ let payload;
136
+ try {
137
+ const verified = jwt.verify(token, secret, {
138
+ algorithms: ['HS256'],
139
+ issuer: AUDIT_READ_ISSUER,
140
+ audience: AUDIT_READ_AUDIENCE,
141
+ clockTimestamp: nowSec,
142
+ });
143
+ if (typeof verified === 'string')
144
+ return forbidden();
145
+ payload = verified;
146
+ }
147
+ catch {
148
+ return forbidden();
149
+ }
150
+ const { iat, exp } = payload;
151
+ if (typeof iat !== 'number' || typeof exp !== 'number')
152
+ return forbidden();
153
+ // The ceiling holds on the token's own lifetime and on the time it is honoured:
154
+ // an `iat` skewed ahead would otherwise stretch acceptance past it.
155
+ if (exp - iat > MAX_AUDIT_TOKEN_LIFETIME_SEC || exp - nowSec > MAX_AUDIT_TOKEN_LIFETIME_SEC)
156
+ return forbidden();
157
+ if (iat > nowSec + MAX_AUDIT_TOKEN_CLOCK_SKEW_SEC)
158
+ return forbidden();
159
+ const sub = typeof payload.sub === 'string' ? payload.sub : '';
160
+ if (!sub.startsWith(AUDIT_SUBJECT_PREFIX))
161
+ return forbidden();
162
+ const who = sub.slice(AUDIT_SUBJECT_PREFIX.length).split('@')[0].trim();
163
+ const allowed = (env[AUDIT_READ_OPERATORS_ENV] ?? '')
164
+ .split(',')
165
+ .map((s) => s.trim())
166
+ .filter((s) => s.length > 0);
167
+ if (who.length === 0 || !allowed.includes(who))
168
+ return forbidden();
169
+ return who;
170
+ }
171
+ /**
172
+ * A read refused after the audit token verified, so the operator is known.
173
+ *
174
+ * Token failures from `assertAuditRead` are plain `GraphQLError`s and leave no
175
+ * record: the caller is unattributed. This class marks the refusals that do get
176
+ * an AuditLog row, and carries the reason that goes on it.
177
+ */
178
+ export class AuditReadRefused extends GraphQLError {
179
+ reason;
180
+ constructor(reason, message, code) {
181
+ super(message, { extensions: { code, reason } });
182
+ this.name = 'AuditReadRefused';
183
+ this.reason = reason;
184
+ }
185
+ }
186
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
187
+ /**
188
+ * Refuse an account id that cannot name a stored account.
189
+ *
190
+ * `AlpacaAccount.id` is a Postgres uuid, and Prisma throws on a non-uuid
191
+ * lookup, so a malformed id would otherwise surface as an internal error with
192
+ * no refusal recorded.
193
+ *
194
+ * @throws {AuditReadRefused} `ACCOUNT_NOT_FOUND` for anything but a uuid.
195
+ */
196
+ export function assertAccountIdShape(accountId) {
197
+ if (!UUID_RE.test(accountId)) {
198
+ throw new AuditReadRefused('ACCOUNT_NOT_FOUND', 'Account not found', 'NOT_FOUND');
199
+ }
200
+ }
201
+ /** Audit reads are PAPER-only; a LIVE account is refused. */
202
+ export function assertAccountReadable(account) {
203
+ if (account.type !== 'PAPER') {
204
+ throw new AuditReadRefused('ACCOUNT_NOT_PAPER', `Account ${account.id} is ${account.type}; audit reads are PAPER-only`, 'FORBIDDEN');
205
+ }
206
+ }
207
+ /**
208
+ * The snapshot's `equity` and `last_equity` as finite numbers.
209
+ *
210
+ * Alpaca sends both as decimal strings. A missing, empty or non-numeric value
211
+ * refuses the read rather than serving `NaN` (or `0`, which `Number('')` and
212
+ * `Number(null)` would give): either reads as a real figure to whoever audits it.
213
+ *
214
+ * @throws {AuditReadRefused} `SNAPSHOT_INCOMPLETE` naming the unusable fields.
215
+ */
216
+ export function snapshotEquity(snap) {
217
+ const s = (snap ?? {});
218
+ const num = (v) => typeof v === 'number' || (typeof v === 'string' && v.trim() !== '') ? Number(v) : NaN;
219
+ const equity = num(s.equity);
220
+ const lastEquity = num(s.last_equity);
221
+ const bad = [
222
+ ...(Number.isFinite(equity) ? [] : ['equity']),
223
+ ...(Number.isFinite(lastEquity) ? [] : ['last_equity']),
224
+ ];
225
+ if (bad.length > 0) {
226
+ // Field names only: the vendor values are not echoed.
227
+ throw new AuditReadRefused('SNAPSHOT_INCOMPLETE', `Broker account snapshot has no finite ${bad.join(' or ')}`, 'BAD_GATEWAY');
228
+ }
229
+ return { equity, lastEquity };
230
+ }
231
+ /** The ET calendar date of an instant, YYYY-MM-DD. */
232
+ export function etDateOf(ms) {
233
+ return new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York' }).format(new Date(ms));
234
+ }
235
+ /**
236
+ * Validate a `YYYY-MM-DD` session date.
237
+ *
238
+ * @throws {GraphQLError} `BAD_USER_INPUT` for anything else, so nothing the
239
+ * caller sends is ever spliced into a URL unchecked.
240
+ */
241
+ export function parseSessionDate(raw) {
242
+ if (raw == null || raw === '')
243
+ return null;
244
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(raw) || Number.isNaN(Date.parse(`${raw}T00:00:00Z`))) {
245
+ throw new GraphQLError('sessionDate must be YYYY-MM-DD', { extensions: { code: 'BAD_USER_INPUT' } });
246
+ }
247
+ return raw;
248
+ }
249
+ async function alpacaGet(account, fetchImpl, url, budget) {
250
+ budget();
251
+ const badGateway = (message, upstreamStatus) => {
252
+ // Status only: the vendor body can echo request detail.
253
+ throw new GraphQLError(message, { extensions: { code: 'BAD_GATEWAY', upstreamStatus } });
254
+ };
255
+ let res;
256
+ let text;
257
+ try {
258
+ res = await fetchImpl(url, {
259
+ headers: { 'APCA-API-KEY-ID': account.APIKey, 'APCA-API-SECRET-KEY': account.APISecret },
260
+ signal: AbortSignal.timeout(ALPACA_TIMEOUT_MS),
261
+ });
262
+ text = await res.text();
263
+ }
264
+ catch {
265
+ return badGateway('Broker read failed (no response)');
266
+ }
267
+ if (!res.ok)
268
+ return badGateway(`Broker read failed (HTTP ${res.status})`, res.status);
269
+ if (!text)
270
+ return null;
271
+ try {
272
+ return JSON.parse(text);
273
+ }
274
+ catch {
275
+ return badGateway(`Broker read failed (unreadable response, HTTP ${res.status})`, res.status);
276
+ }
277
+ }
278
+ /**
279
+ * Read one session's 1-minute equity curve and the account snapshot.
280
+ *
281
+ * @param p.account - The stored account row (carries the key; not returned).
282
+ * @param p.sessionDate - Pin a past session, or null for today's ET date.
283
+ * @param p.fetchImpl - Injected HTTP client.
284
+ * @throws {AuditReadRefused} for a LIVE account or an incomplete snapshot.
285
+ */
286
+ export async function readEquityCurve(p) {
287
+ const { account, fetchImpl, budget } = p;
288
+ assertAccountReadable(account);
289
+ const base = PAPER_TRADE_HOST;
290
+ const sessionDate = p.sessionDate ?? etDateOf(p.nowMs);
291
+ // Checked before the history call, so a refused read spends one request, not two.
292
+ const snap = snapshotEquity(await alpacaGet(account, fetchImpl, `${base}/v2/account`, budget));
293
+ const hist = (await alpacaGet(account, fetchImpl, `${base}/v2/account/portfolio/history?period=1D&timeframe=1Min&intraday_reporting=market_hours&pnl_reset=per_day` +
294
+ (p.sessionDate ? `&date_end=${p.sessionDate}` : ''), budget));
295
+ const ts = hist?.timestamp ?? [];
296
+ const eq = hist?.equity ?? [];
297
+ const points = [];
298
+ for (let i = 0; i < ts.length; i++) {
299
+ const equity = eq[i];
300
+ if (typeof equity === 'number' && Number.isFinite(equity))
301
+ points.push({ ms: ts[i] * 1000, equity });
302
+ }
303
+ const cfg = account.configuration;
304
+ return {
305
+ accountId: account.id,
306
+ accountType: account.type,
307
+ accountName: typeof cfg?.name === 'string' && cfg.name ? cfg.name : account.id,
308
+ sessionDate,
309
+ points,
310
+ lastEquity: snap.lastEquity,
311
+ equity: snap.equity,
312
+ source: 'alpaca-portfolio-history',
313
+ };
314
+ }
315
+ //# sourceMappingURL=account-audit-read.js.map
@@ -7,4 +7,5 @@ export { OptionsGreeksHistoryCustomResolver } from './OptionsGreeksHistoryCustom
7
7
  export { BrokerageAccountCredentialStatusResolver, hasStoredApiCredentials, } from './BrokerageAccountCredentialStatusResolver';
8
8
  export { OptionsGreeksHistorySystemSummary } from './OptionsGreeksHistorySystemSummary';
9
9
  export { TradingSettingsResolver, TradingSettings, TradingSettingsInput, OrgTradingDefaultsPayload, FundTradingOverridesPayload, } from './TradingSettingsResolver';
10
+ export { AccountEquityCurveResolver, AccountEquityCurve, EquityCurvePoint, } from './AccountEquityCurveResolver';
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/resolvers/custom/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,wCAAwC,EACxC,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/resolvers/custom/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,wCAAwC,EACxC,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,8BAA8B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/resolvers/custom/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,wCAAwC,EACxC,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/resolvers/custom/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,wCAAwC,EACxC,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,8BAA8B,CAAC"}
@@ -7,4 +7,5 @@ export { OptionsGreeksHistoryCustomResolver } from './OptionsGreeksHistoryCusto
7
7
  export { BrokerageAccountCredentialStatusResolver, hasStoredApiCredentials, } from './BrokerageAccountCredentialStatusResolver.mjs';
8
8
  export { OptionsGreeksHistorySystemSummary } from './OptionsGreeksHistorySystemSummary.mjs';
9
9
  export { TradingSettingsResolver, TradingSettings, TradingSettingsInput, OrgTradingDefaultsPayload, FundTradingOverridesPayload, } from './TradingSettingsResolver.mjs';
10
+ export { AccountEquityCurveResolver, AccountEquityCurve, EquityCurvePoint, } from './AccountEquityCurveResolver.mjs';
10
11
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adaptic/backend",
3
- "version": "0.0.1048",
3
+ "version": "0.0.1050",
4
4
  "description": "Backend executable CRUD functions with dynamic variables construction, and type definitions for the Adaptic AI platform.",
5
5
  "type": "module",
6
6
  "types": "index.d.ts",
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
45
+ return function (target, key) { decorator(target, key, paramIndex); }
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.AccountEquityCurveResolver = exports.alpacaFetch = exports.AccountEquityCurve = exports.EquityCurvePoint = void 0;
49
+ /**
50
+ * `accountEquityCurve` — server-side audit read.
51
+ *
52
+ * Returns an account's 1-minute equity curve without the caller ever holding
53
+ * the account's broker key. Requires an audit-read token in the
54
+ * `x-adaptic-audit-token` header (see `assertAuditRead`) and refuses LIVE
55
+ * accounts.
56
+ * Read-only on the broker; every read spends a per-account request budget and
57
+ * writes an `AuditLog` row naming the operator, account and operation. Once the
58
+ * token verifies, a refusal (unknown or deleted account, LIVE account, incomplete
59
+ * broker snapshot) also writes a row, with its reason. No row is written for an
60
+ * unverified caller, a bad `sessionDate`, a failed account lookup, or a rate-limited
61
+ * or failed broker call (those after the read row leave only that row).
62
+ *
63
+ * @module resolvers/custom/AccountEquityCurveResolver
64
+ */
65
+ const TypeGraphQL = __importStar(require("type-graphql"));
66
+ const graphql_1 = require("graphql");
67
+ const helpers_1 = require("../../generated/typegraphql-prisma/helpers.cjs");
68
+ const logger_1 = require("../../utils/logger.cjs");
69
+ const account_audit_read_1 = require("./account-audit-read.cjs");
70
+ let EquityCurvePoint = class EquityCurvePoint {
71
+ };
72
+ exports.EquityCurvePoint = EquityCurvePoint;
73
+ __decorate([
74
+ TypeGraphQL.Field((_t) => TypeGraphQL.Float),
75
+ __metadata("design:type", Number)
76
+ ], EquityCurvePoint.prototype, "ms", void 0);
77
+ __decorate([
78
+ TypeGraphQL.Field((_t) => TypeGraphQL.Float),
79
+ __metadata("design:type", Number)
80
+ ], EquityCurvePoint.prototype, "equity", void 0);
81
+ exports.EquityCurvePoint = EquityCurvePoint = __decorate([
82
+ TypeGraphQL.ObjectType('EquityCurvePoint', {})
83
+ ], EquityCurvePoint);
84
+ let AccountEquityCurve = class AccountEquityCurve {
85
+ };
86
+ exports.AccountEquityCurve = AccountEquityCurve;
87
+ __decorate([
88
+ TypeGraphQL.Field((_t) => String),
89
+ __metadata("design:type", String)
90
+ ], AccountEquityCurve.prototype, "accountId", void 0);
91
+ __decorate([
92
+ TypeGraphQL.Field((_t) => String),
93
+ __metadata("design:type", String)
94
+ ], AccountEquityCurve.prototype, "accountType", void 0);
95
+ __decorate([
96
+ TypeGraphQL.Field((_t) => String),
97
+ __metadata("design:type", String)
98
+ ], AccountEquityCurve.prototype, "accountName", void 0);
99
+ __decorate([
100
+ TypeGraphQL.Field((_t) => String),
101
+ __metadata("design:type", String)
102
+ ], AccountEquityCurve.prototype, "sessionDate", void 0);
103
+ __decorate([
104
+ TypeGraphQL.Field((_t) => [EquityCurvePoint]),
105
+ __metadata("design:type", Array)
106
+ ], AccountEquityCurve.prototype, "points", void 0);
107
+ __decorate([
108
+ TypeGraphQL.Field((_t) => TypeGraphQL.Float),
109
+ __metadata("design:type", Number)
110
+ ], AccountEquityCurve.prototype, "lastEquity", void 0);
111
+ __decorate([
112
+ TypeGraphQL.Field((_t) => TypeGraphQL.Float),
113
+ __metadata("design:type", Number)
114
+ ], AccountEquityCurve.prototype, "equity", void 0);
115
+ __decorate([
116
+ TypeGraphQL.Field((_t) => String),
117
+ __metadata("design:type", String)
118
+ ], AccountEquityCurve.prototype, "source", void 0);
119
+ exports.AccountEquityCurve = AccountEquityCurve = __decorate([
120
+ TypeGraphQL.ObjectType('AccountEquityCurve', {})
121
+ ], AccountEquityCurve);
122
+ /**
123
+ * Injectable HTTP client. Exported as a test seam only: nothing in production
124
+ * reassigns `current`, and the default is the global `fetch`.
125
+ */
126
+ exports.alpacaFetch = {
127
+ current: (url, init) => fetch(url, init),
128
+ };
129
+ const accountBudget = (0, account_audit_read_1.createAccountBudgets)();
130
+ /** Width of `AuditLog.recordId`; only a malformed (refused) account id can exceed it. */
131
+ const RECORD_ID_MAX = 255;
132
+ function auditRowData(p, outcome) {
133
+ const accountId = p.accountId.slice(0, RECORD_ID_MAX);
134
+ return {
135
+ operationType: 'CREATE',
136
+ modelName: 'AuditRead',
137
+ recordId: accountId,
138
+ operationName: p.op,
139
+ changedFields: {},
140
+ metadata: { operator: p.operator, accountId, op: p.op, ...p.detail, ...outcome },
141
+ };
142
+ }
143
+ /** `AuditLog.operationType` has no READ member, so a read is recorded as a CREATE of an `AuditRead` record. */
144
+ async function recordRead(prisma, p) {
145
+ try {
146
+ await prisma.auditLog.create({ data: auditRowData(p, { outcome: 'read' }) });
147
+ }
148
+ catch (err) {
149
+ // Fail closed: an unrecorded read is not served.
150
+ logger_1.logger.error('[audit-read] could not write the AuditLog row; refusing the read', { operator: p.operator, accountId: p.accountId, op: p.op, ...errDetail(err) });
151
+ throw new graphql_1.GraphQLError('Audit read could not be recorded', { extensions: { code: 'INTERNAL_SERVER_ERROR' } });
152
+ }
153
+ }
154
+ /**
155
+ * Record a refusal of a verified caller's read. The caller still gets the
156
+ * refusal if the row cannot be written: nothing is served either way, and the
157
+ * refusal is the truthful answer.
158
+ */
159
+ async function recordRefusal(prisma, p, reason) {
160
+ try {
161
+ await prisma.auditLog.create({ data: auditRowData(p, { outcome: 'refused', reason }) });
162
+ }
163
+ catch (err) {
164
+ logger_1.logger.error('[audit-read] could not write the AuditLog row for a refused read', { operator: p.operator, accountId: p.accountId, op: p.op, reason, ...errDetail(err) });
165
+ }
166
+ }
167
+ /** A soft-deleted account is not found. */
168
+ async function loadAccount(prisma, id) {
169
+ (0, account_audit_read_1.assertAccountIdShape)(id);
170
+ const account = await prisma.alpacaAccount.findFirst({
171
+ where: { id, deletedAt: null },
172
+ select: { id: true, type: true, APIKey: true, APISecret: true, configuration: true },
173
+ });
174
+ if (!account)
175
+ throw new account_audit_read_1.AuditReadRefused('ACCOUNT_NOT_FOUND', 'Account not found', 'NOT_FOUND');
176
+ return account;
177
+ }
178
+ /** The error's message and code, since logging the object itself serialises as `{}`. */
179
+ function errDetail(err) {
180
+ return {
181
+ err: err instanceof Error ? err.message : String(err),
182
+ code: err === null || err === void 0 ? void 0 : err.code,
183
+ };
184
+ }
185
+ let AccountEquityCurveResolver = class AccountEquityCurveResolver {
186
+ async accountEquityCurve(ctx, accountId, sessionDate) {
187
+ var _a;
188
+ // Throws before any row: a caller whose token does not verify is unattributed.
189
+ const operator = (0, account_audit_read_1.assertAuditRead)((0, account_audit_read_1.auditTokenFromHeaders)((_a = ctx.req) === null || _a === void 0 ? void 0 : _a.headers));
190
+ const date = (0, account_audit_read_1.parseSessionDate)(sessionDate);
191
+ const prisma = (0, helpers_1.getPrismaFromContext)(ctx);
192
+ // `row.accountId` is the caller's text until the lookup answers, then the
193
+ // stored id: Postgres matches a uuid in either case, so the budget and the
194
+ // rows key on the stored form or one account would get a budget per spelling.
195
+ const row = { operator, accountId, op: 'accountEquityCurve', detail: { sessionDate: date } };
196
+ try {
197
+ const account = await loadAccount(prisma, accountId);
198
+ row.accountId = account.id;
199
+ (0, account_audit_read_1.assertAccountReadable)(account);
200
+ await recordRead(prisma, row);
201
+ return await (0, account_audit_read_1.readEquityCurve)({
202
+ account,
203
+ sessionDate: date,
204
+ nowMs: Date.now(),
205
+ fetchImpl: exports.alpacaFetch.current,
206
+ budget: accountBudget(account.id),
207
+ });
208
+ }
209
+ catch (err) {
210
+ // An incomplete snapshot is refused after the read row is written, so
211
+ // that read leaves two rows: the key use, then the refusal.
212
+ if (err instanceof account_audit_read_1.AuditReadRefused)
213
+ await recordRefusal(prisma, row, err.reason);
214
+ throw err;
215
+ }
216
+ }
217
+ };
218
+ exports.AccountEquityCurveResolver = AccountEquityCurveResolver;
219
+ __decorate([
220
+ TypeGraphQL.Query((_returns) => AccountEquityCurve, {
221
+ description: 'A session’s 1-minute equity curve for one account, read server-side. Requires an audit-read token. PAPER accounts only.',
222
+ }),
223
+ __param(0, TypeGraphQL.Ctx()),
224
+ __param(1, TypeGraphQL.Arg('accountId', (_t) => String)),
225
+ __param(2, TypeGraphQL.Arg('sessionDate', (_t) => String, { nullable: true })),
226
+ __metadata("design:type", Function),
227
+ __metadata("design:paramtypes", [Object, String, String]),
228
+ __metadata("design:returntype", Promise)
229
+ ], AccountEquityCurveResolver.prototype, "accountEquityCurve", null);
230
+ exports.AccountEquityCurveResolver = AccountEquityCurveResolver = __decorate([
231
+ TypeGraphQL.Resolver()
232
+ ], AccountEquityCurveResolver);
233
+ //# sourceMappingURL=AccountEquityCurveResolver.js.map
@@ -0,0 +1,32 @@
1
+ import { type AlpacaFetch } from './account-audit-read';
2
+ export declare class EquityCurvePoint {
3
+ ms: number;
4
+ equity: number;
5
+ }
6
+ export declare class AccountEquityCurve {
7
+ accountId: string;
8
+ accountType: string;
9
+ accountName: string;
10
+ sessionDate: string;
11
+ points: EquityCurvePoint[];
12
+ lastEquity: number;
13
+ equity: number;
14
+ source: string;
15
+ }
16
+ interface GraphQLContext {
17
+ req?: {
18
+ headers?: Record<string, string | string[] | undefined>;
19
+ };
20
+ }
21
+ /**
22
+ * Injectable HTTP client. Exported as a test seam only: nothing in production
23
+ * reassigns `current`, and the default is the global `fetch`.
24
+ */
25
+ export declare const alpacaFetch: {
26
+ current: AlpacaFetch;
27
+ };
28
+ export declare class AccountEquityCurveResolver {
29
+ accountEquityCurve(ctx: GraphQLContext, accountId: string, sessionDate?: string): Promise<AccountEquityCurve>;
30
+ }
31
+ export {};
32
+ //# sourceMappingURL=AccountEquityCurveResolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccountEquityCurveResolver.d.ts","sourceRoot":"","sources":["../../../src/resolvers/custom/AccountEquityCurveResolver.ts"],"names":[],"mappings":"AAsBA,OAAO,EASL,KAAK,WAAW,EAGjB,MAAM,sBAAsB,CAAC;AAE9B,qBACa,gBAAgB;IAE3B,EAAE,EAAG,MAAM,CAAC;IAGZ,MAAM,EAAG,MAAM,CAAC;CACjB;AAED,qBACa,kBAAkB;IAE7B,SAAS,EAAG,MAAM,CAAC;IAGnB,WAAW,EAAG,MAAM,CAAC;IAGrB,WAAW,EAAG,MAAM,CAAC;IAGrB,WAAW,EAAG,MAAM,CAAC;IAGrB,MAAM,EAAG,gBAAgB,EAAE,CAAC;IAG5B,UAAU,EAAG,MAAM,CAAC;IAGpB,MAAM,EAAG,MAAM,CAAC;IAGhB,MAAM,EAAG,MAAM,CAAC;CACjB;AAED,UAAU,cAAc;IACtB,GAAG,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;KAAE,CAAC;CACnE;AAED;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE;IAAE,OAAO,EAAE,WAAW,CAAA;CAE/C,CAAC;AAqEF,qBACa,0BAA0B;IAK/B,kBAAkB,CACH,GAAG,EAAE,cAAc,EACQ,SAAS,EAAE,MAAM,EACK,WAAW,CAAC,EAAE,MAAM,GACvF,OAAO,CAAC,kBAAkB,CAAC;CA4B/B"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccountEquityCurveResolver.js","sourceRoot":"","sources":["../../../src/resolvers/custom/AccountEquityCurveResolver.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;GAeG;AACH,0DAA4C;AAE5C,qCAAuC;AAEvC,wEAAkF;AAClF,+CAA4C;AAC5C,6DAY8B;AAGvB,IAAM,gBA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