@odatano/core 2.0.0-rc.4 → 2.0.0-rc.6
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/@cds-models/CardanoAgentService/index.d.ts +255 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +28 -0
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/odatano/cardano/index.d.ts +86 -0
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +53 -3
- package/db/schema.cds +105 -0
- package/package.json +4 -3
- package/src/index.d.ts +6 -0
- package/src/index.js +21 -1
- package/src/plugin.js +33 -30
- package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
- package/srv/blockchain/backends/ogmios-backend.js +72 -5
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
- package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
- package/srv/blockchain/wallet-worker/job-store.js +42 -9
- package/srv/cardano-agent-service.cds +150 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +16 -0
- package/srv/cardano-indexer-service.cds +20 -0
- package/srv/cardano-indexer-service.js +3 -0
- package/srv/server.d.ts +2 -1
- package/srv/server.js +12 -0
- package/srv/utils/agent-grants-config.d.ts +64 -0
- package/srv/utils/agent-grants-config.js +144 -0
- package/srv/utils/agent-grants.d.ts +314 -0
- package/srv/utils/agent-grants.js +821 -0
- package/srv/utils/agent-token-auth.d.ts +106 -0
- package/srv/utils/agent-token-auth.js +239 -0
- package/srv/utils/liveness.d.ts +23 -0
- package/srv/utils/liveness.js +49 -0
- package/srv/utils/rate-limiter.d.ts +57 -0
- package/srv/utils/rate-limiter.js +126 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport authentication with lanes: CAP's configured strategy PLUS an
|
|
3
|
+
* `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
|
|
4
|
+
*
|
|
5
|
+
* CAP's auth middleware 401s a request without transport credentials before any
|
|
6
|
+
* service hook runs, so an agent holding only an `odat_` token could never
|
|
7
|
+
* reach a service. This middleware is installed as `cds.requires.auth.impl` by
|
|
8
|
+
* src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
|
|
9
|
+
*
|
|
10
|
+
* - runs every registered LANE first. The built-in lane admits a request that
|
|
11
|
+
* carries `x-agent-token` on one of the six ODATANO service paths (exact
|
|
12
|
+
* segment match, no lookalike prefixes): the token is authenticated HERE
|
|
13
|
+
* (unknown 401, expired 410, non-leaking) and the request continues as the
|
|
14
|
+
* principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
|
|
15
|
+
* rides on the express request (`req.agentGrant`) for the enforcement hook.
|
|
16
|
+
* Other packages (@odatano/x402) add lanes with `registerTransportLane`
|
|
17
|
+
* instead of fighting for the single `auth.impl` slot.
|
|
18
|
+
* - otherwise DELEGATES to CAP's own strategy for the configured kind
|
|
19
|
+
* (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
|
|
20
|
+
* for every request without a token is exactly what it was before.
|
|
21
|
+
*
|
|
22
|
+
* Failed token attempts are throttled per client address (20 per 15 minutes):
|
|
23
|
+
* one static hash lookup must not become an offline-speed guessing oracle.
|
|
24
|
+
*/
|
|
25
|
+
import cds from '@sap/cds';
|
|
26
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
27
|
+
import { type AgentGrantRow } from './agent-grants';
|
|
28
|
+
type ExpressReq = IncomingMessage & {
|
|
29
|
+
headers: Record<string, string | string[] | undefined>;
|
|
30
|
+
originalUrl?: string;
|
|
31
|
+
baseUrl?: string;
|
|
32
|
+
path?: string;
|
|
33
|
+
ip?: string;
|
|
34
|
+
user?: unknown;
|
|
35
|
+
agentGrant?: AgentGrantRow;
|
|
36
|
+
};
|
|
37
|
+
type ExpressRes = ServerResponse & {
|
|
38
|
+
status?: (code: number) => ExpressRes;
|
|
39
|
+
set?: (name: string, value: string) => ExpressRes;
|
|
40
|
+
json?: (body: unknown) => void;
|
|
41
|
+
};
|
|
42
|
+
type Next = (err?: unknown) => void;
|
|
43
|
+
export type AuthMiddleware = (req: ExpressReq, res: ExpressRes, next: Next) => unknown;
|
|
44
|
+
/** What a lane's `authenticate` may answer. */
|
|
45
|
+
export type LaneOutcome =
|
|
46
|
+
/** The lane authenticated the request; continue as this principal. */
|
|
47
|
+
{
|
|
48
|
+
user: cds.User;
|
|
49
|
+
}
|
|
50
|
+
/** The lane already sent a response (401/410/429); stop here. */
|
|
51
|
+
| {
|
|
52
|
+
handled: true;
|
|
53
|
+
}
|
|
54
|
+
/** Not this lane's request after all; try the next lane, then the delegate. */
|
|
55
|
+
| null;
|
|
56
|
+
export interface TransportLane {
|
|
57
|
+
/** Unique name; registering the same name twice replaces the lane. */
|
|
58
|
+
name: string;
|
|
59
|
+
/** Cheap check on headers/path; no I/O. */
|
|
60
|
+
match: (req: ExpressReq) => boolean;
|
|
61
|
+
/** Authenticate; may respond itself. */
|
|
62
|
+
authenticate: (req: ExpressReq, res: ExpressRes) => Promise<LaneOutcome>;
|
|
63
|
+
}
|
|
64
|
+
/** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
|
|
65
|
+
export declare function registerTransportLane(lane: TransportLane): void;
|
|
66
|
+
/** Registered lane names, in order (tests, diagnostics). */
|
|
67
|
+
export declare function transportLanes(): string[];
|
|
68
|
+
/** Remove every lane except the built-in one (tests). */
|
|
69
|
+
export declare function __resetTransportLanesForTests(): void;
|
|
70
|
+
/** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
|
|
71
|
+
export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
|
|
72
|
+
/** Mount paths of the six services, read from `cds.services` once they are served. */
|
|
73
|
+
export declare function agentServicePaths(): string[];
|
|
74
|
+
/** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
|
|
75
|
+
export declare function inAgentLane(path: string, servicePaths?: string[]): boolean;
|
|
76
|
+
export declare const agentTokenLane: TransportLane;
|
|
77
|
+
interface AuthOptions {
|
|
78
|
+
kind?: string;
|
|
79
|
+
impl?: string;
|
|
80
|
+
/** Set by activateAgentGrants: the strategy that keeps authenticating non-token requests. */
|
|
81
|
+
agentGrantsDelegate?: string;
|
|
82
|
+
/**
|
|
83
|
+
* Set by activateAgentGrants when the host had its own `auth.impl` before us:
|
|
84
|
+
* that module (path as configured, resolved like CAP does it) is the delegate,
|
|
85
|
+
* whatever `kind` says. The host's gate keeps running for every non-token
|
|
86
|
+
* request, on every path.
|
|
87
|
+
*/
|
|
88
|
+
agentGrantsDelegateImpl?: string;
|
|
89
|
+
[key: string]: unknown;
|
|
90
|
+
}
|
|
91
|
+
/** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
|
|
92
|
+
/**
|
|
93
|
+
* Resolve a host-configured `auth.impl` the way CAP's auth factory does
|
|
94
|
+
* (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
|
|
95
|
+
* cds.root, else with a `./` prefix. Exported for the unit tests.
|
|
96
|
+
*/
|
|
97
|
+
export declare function resolveCustomImpl(impl: string, root?: string): string;
|
|
98
|
+
export declare function loadDelegate(options: AuthOptions, kind: string): AuthMiddleware;
|
|
99
|
+
export declare function createAgentTokenAuth(options: AuthOptions, delegate?: AuthMiddleware): AuthMiddleware;
|
|
100
|
+
/**
|
|
101
|
+
* CAP requires this module and, seeing a function with fewer than three
|
|
102
|
+
* parameters, calls it with the merged auth options to obtain the middleware.
|
|
103
|
+
*/
|
|
104
|
+
export default function agentTokenAuthFactory(options: AuthOptions): AuthMiddleware;
|
|
105
|
+
export {};
|
|
106
|
+
//# sourceMappingURL=agent-token-auth.d.ts.map
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Transport authentication with lanes: CAP's configured strategy PLUS an
|
|
4
|
+
* `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
|
|
5
|
+
*
|
|
6
|
+
* CAP's auth middleware 401s a request without transport credentials before any
|
|
7
|
+
* service hook runs, so an agent holding only an `odat_` token could never
|
|
8
|
+
* reach a service. This middleware is installed as `cds.requires.auth.impl` by
|
|
9
|
+
* src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
|
|
10
|
+
*
|
|
11
|
+
* - runs every registered LANE first. The built-in lane admits a request that
|
|
12
|
+
* carries `x-agent-token` on one of the six ODATANO service paths (exact
|
|
13
|
+
* segment match, no lookalike prefixes): the token is authenticated HERE
|
|
14
|
+
* (unknown 401, expired 410, non-leaking) and the request continues as the
|
|
15
|
+
* principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
|
|
16
|
+
* rides on the express request (`req.agentGrant`) for the enforcement hook.
|
|
17
|
+
* Other packages (@odatano/x402) add lanes with `registerTransportLane`
|
|
18
|
+
* instead of fighting for the single `auth.impl` slot.
|
|
19
|
+
* - otherwise DELEGATES to CAP's own strategy for the configured kind
|
|
20
|
+
* (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
|
|
21
|
+
* for every request without a token is exactly what it was before.
|
|
22
|
+
*
|
|
23
|
+
* Failed token attempts are throttled per client address (20 per 15 minutes):
|
|
24
|
+
* one static hash lookup must not become an offline-speed guessing oracle.
|
|
25
|
+
*/
|
|
26
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
27
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
28
|
+
};
|
|
29
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
+
exports.agentTokenLane = void 0;
|
|
31
|
+
exports.registerTransportLane = registerTransportLane;
|
|
32
|
+
exports.transportLanes = transportLanes;
|
|
33
|
+
exports.__resetTransportLanesForTests = __resetTransportLanesForTests;
|
|
34
|
+
exports.__setAgentServicePathsForTests = __setAgentServicePathsForTests;
|
|
35
|
+
exports.agentServicePaths = agentServicePaths;
|
|
36
|
+
exports.inAgentLane = inAgentLane;
|
|
37
|
+
exports.resolveCustomImpl = resolveCustomImpl;
|
|
38
|
+
exports.loadDelegate = loadDelegate;
|
|
39
|
+
exports.createAgentTokenAuth = createAgentTokenAuth;
|
|
40
|
+
exports.default = agentTokenAuthFactory;
|
|
41
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
42
|
+
const agent_grants_1 = require("./agent-grants");
|
|
43
|
+
const rate_limiter_1 = require("./rate-limiter");
|
|
44
|
+
const lanes = [];
|
|
45
|
+
/** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
|
|
46
|
+
function registerTransportLane(lane) {
|
|
47
|
+
const i = lanes.findIndex((l) => l.name === lane.name);
|
|
48
|
+
if (i >= 0)
|
|
49
|
+
lanes[i] = lane;
|
|
50
|
+
else
|
|
51
|
+
lanes.push(lane);
|
|
52
|
+
}
|
|
53
|
+
/** Registered lane names, in order (tests, diagnostics). */
|
|
54
|
+
function transportLanes() {
|
|
55
|
+
return lanes.map((l) => l.name);
|
|
56
|
+
}
|
|
57
|
+
/** Remove every lane except the built-in one (tests). */
|
|
58
|
+
function __resetTransportLanesForTests() {
|
|
59
|
+
lanes.length = 0;
|
|
60
|
+
tokenFailures.reset();
|
|
61
|
+
servicePathsCache = null;
|
|
62
|
+
servicePathsPinned = false;
|
|
63
|
+
}
|
|
64
|
+
/** Built-in CAP strategies by kind, same table as @sap/cds/lib/srv/middlewares/auth/index.js. */
|
|
65
|
+
const BUILTIN = {
|
|
66
|
+
mocked: 'basic-auth',
|
|
67
|
+
basic: 'basic-auth',
|
|
68
|
+
ias: 'ias-auth',
|
|
69
|
+
jwt: 'jwt-auth',
|
|
70
|
+
xsuaa: 'jwt-auth',
|
|
71
|
+
dummy: 'dummy-auth',
|
|
72
|
+
};
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// Built-in lane: x-agent-token on the ODATANO service paths
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
const tokenFailures = new rate_limiter_1.RateLimiter({ windowMs: 15 * 60 * 1000, maxRequests: 20, maxKeys: 10_000 });
|
|
77
|
+
let servicePathsCache = null;
|
|
78
|
+
let servicePathsPinned = false;
|
|
79
|
+
/** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
|
|
80
|
+
function __setAgentServicePathsForTests(paths) {
|
|
81
|
+
servicePathsCache = paths;
|
|
82
|
+
servicePathsPinned = paths !== null;
|
|
83
|
+
}
|
|
84
|
+
/** Mount paths of the six services, read from `cds.services` once they are served. */
|
|
85
|
+
function agentServicePaths() {
|
|
86
|
+
if (servicePathsPinned && servicePathsCache)
|
|
87
|
+
return servicePathsCache;
|
|
88
|
+
if (servicePathsCache && servicePathsCache.length === agent_grants_1.AGENT_SERVICE_NAMES.length)
|
|
89
|
+
return servicePathsCache;
|
|
90
|
+
const services = cds_1.default.services ?? {};
|
|
91
|
+
const paths = Object.values(services)
|
|
92
|
+
.filter((s) => s && agent_grants_1.AGENT_SERVICE_NAMES.includes(String(s.name)) && typeof s.path === 'string')
|
|
93
|
+
.map((s) => String(s.path).replace(/\/+$/, ''));
|
|
94
|
+
servicePathsCache = paths;
|
|
95
|
+
return paths;
|
|
96
|
+
}
|
|
97
|
+
function requestPath(req) {
|
|
98
|
+
const raw = String(req.originalUrl || req.url || req.path || '');
|
|
99
|
+
return raw.split('?')[0];
|
|
100
|
+
}
|
|
101
|
+
/** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
|
|
102
|
+
function inAgentLane(path, servicePaths = agentServicePaths()) {
|
|
103
|
+
return servicePaths.some((p) => path === p || path.startsWith(p + '/'));
|
|
104
|
+
}
|
|
105
|
+
function clientKey(req) {
|
|
106
|
+
const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
|
|
107
|
+
return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
|
|
108
|
+
}
|
|
109
|
+
function respond(res, status, message, retryAfterMs) {
|
|
110
|
+
if (retryAfterMs !== undefined)
|
|
111
|
+
res.set?.('Retry-After', String(Math.max(1, Math.ceil(retryAfterMs / 1000))));
|
|
112
|
+
const body = { error: { code: String(status), message } };
|
|
113
|
+
if (typeof res.status === 'function' && typeof res.json === 'function') {
|
|
114
|
+
res.status(status);
|
|
115
|
+
res.json(body);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
res.statusCode = status;
|
|
119
|
+
res.setHeader('content-type', 'application/json');
|
|
120
|
+
res.end(JSON.stringify(body));
|
|
121
|
+
}
|
|
122
|
+
return { handled: true };
|
|
123
|
+
}
|
|
124
|
+
exports.agentTokenLane = {
|
|
125
|
+
name: 'agent-token',
|
|
126
|
+
match: (req) => typeof req.headers?.[agent_grants_1.AGENT_TOKEN_HEADER] === 'string' && req.headers[agent_grants_1.AGENT_TOKEN_HEADER].length > 0,
|
|
127
|
+
authenticate: async (req, res) => {
|
|
128
|
+
const token = req.headers[agent_grants_1.AGENT_TOKEN_HEADER];
|
|
129
|
+
if (!inAgentLane(requestPath(req))) {
|
|
130
|
+
// A token on any other path is not ours to admit; the delegate decides
|
|
131
|
+
// (and will 401 a request that carries nothing else).
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
const key = clientKey(req);
|
|
135
|
+
const locked = tokenFailures.peek(key);
|
|
136
|
+
if (!locked.allowed)
|
|
137
|
+
return respond(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
|
|
138
|
+
const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
|
|
139
|
+
if (!resolution.ok) {
|
|
140
|
+
const failed = tokenFailures.check(key);
|
|
141
|
+
if (!failed.allowed)
|
|
142
|
+
return respond(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
|
|
143
|
+
return respond(res, resolution.status, resolution.message);
|
|
144
|
+
}
|
|
145
|
+
req.agentGrant = resolution.grant;
|
|
146
|
+
return { user: (0, agent_grants_1.makeAgentUser)(resolution.grant) };
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
function ensureBuiltinLane() {
|
|
150
|
+
if (!lanes.some((l) => l.name === exports.agentTokenLane.name))
|
|
151
|
+
lanes.unshift(exports.agentTokenLane);
|
|
152
|
+
}
|
|
153
|
+
/** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
|
|
154
|
+
/**
|
|
155
|
+
* Resolve a host-configured `auth.impl` the way CAP's auth factory does
|
|
156
|
+
* (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
|
|
157
|
+
* cds.root, else with a `./` prefix. Exported for the unit tests.
|
|
158
|
+
*/
|
|
159
|
+
function resolveCustomImpl(impl, root = String(cds_1.default.root ?? process.cwd())) {
|
|
160
|
+
try {
|
|
161
|
+
return require.resolve(impl, { paths: [root] });
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return require.resolve(`./${impl}`, { paths: [root] });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function asMiddleware(loaded, delegateOptions, what) {
|
|
168
|
+
// default export of an ESM / .ts module
|
|
169
|
+
const candidate = loaded?.default ?? loaded;
|
|
170
|
+
const mw = typeof candidate === 'function' && candidate.length < 3
|
|
171
|
+
? candidate(delegateOptions)
|
|
172
|
+
: candidate;
|
|
173
|
+
if (typeof mw !== 'function') {
|
|
174
|
+
throw new Error(`agent-token-auth: ${what} did not yield a middleware function`);
|
|
175
|
+
}
|
|
176
|
+
return mw;
|
|
177
|
+
}
|
|
178
|
+
function loadDelegate(options, kind) {
|
|
179
|
+
// The delegate must not see our impl (it would recurse) nor our private keys.
|
|
180
|
+
const delegateOptions = { ...options };
|
|
181
|
+
delete delegateOptions.impl;
|
|
182
|
+
delete delegateOptions.agentGrantsDelegate;
|
|
183
|
+
delete delegateOptions.agentGrantsDelegateImpl;
|
|
184
|
+
// A host that brought its own auth.impl keeps it: whatever it enforced
|
|
185
|
+
// before agent grants were switched on, it still enforces for every request
|
|
186
|
+
// that does not carry a token, on every path.
|
|
187
|
+
const custom = options.agentGrantsDelegateImpl;
|
|
188
|
+
if (custom) {
|
|
189
|
+
const resolved = resolveCustomImpl(custom);
|
|
190
|
+
return asMiddleware(require(resolved), { ...delegateOptions, impl: custom }, `custom auth impl '${custom}'`);
|
|
191
|
+
}
|
|
192
|
+
const builtin = BUILTIN[kind.replace(/-auth$/, '')];
|
|
193
|
+
if (!builtin)
|
|
194
|
+
throw new Error(`agent-token-auth: no built-in CAP auth strategy for kind '${kind}'`);
|
|
195
|
+
// Same module CAP itself would have loaded for this kind. Pinned by the
|
|
196
|
+
// @sap/cds peer dependency; the self-test in asMiddleware fails fast if the shape moves.
|
|
197
|
+
const factory = require(`@sap/cds/lib/srv/middlewares/auth/${builtin}`);
|
|
198
|
+
return asMiddleware(factory, { ...delegateOptions, kind }, `CAP auth strategy '${builtin}'`);
|
|
199
|
+
}
|
|
200
|
+
function createAgentTokenAuth(options, delegate) {
|
|
201
|
+
const delegateKind = String(options.agentGrantsDelegate ?? options.kind ?? 'mocked');
|
|
202
|
+
const inner = delegate ?? loadDelegate(options, delegateKind);
|
|
203
|
+
ensureBuiltinLane();
|
|
204
|
+
const delegateLabel = options.agentGrantsDelegateImpl ? `custom impl ${options.agentGrantsDelegateImpl}` : `'${delegateKind}'`;
|
|
205
|
+
cds_1.default.log('AgentGrants').info(`agent-token transport lane active, delegating other requests to ${delegateLabel}`);
|
|
206
|
+
return async function agentTokenAuth(req, res, next) {
|
|
207
|
+
for (const lane of lanes) {
|
|
208
|
+
if (!lane.match(req))
|
|
209
|
+
continue;
|
|
210
|
+
let outcome;
|
|
211
|
+
try {
|
|
212
|
+
outcome = await lane.authenticate(req, res);
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
cds_1.default.log('AgentGrants').error(`transport lane '${lane.name}' failed: ${String(err?.message ?? err)}`);
|
|
216
|
+
respond(res, 500, 'authentication lane failed');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (outcome === null)
|
|
220
|
+
continue;
|
|
221
|
+
if ('handled' in outcome)
|
|
222
|
+
return;
|
|
223
|
+
req.user = outcome.user;
|
|
224
|
+
const ctx = cds_1.default.context;
|
|
225
|
+
if (ctx)
|
|
226
|
+
ctx.user = outcome.user;
|
|
227
|
+
return next();
|
|
228
|
+
}
|
|
229
|
+
return inner(req, res, next);
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* CAP requires this module and, seeing a function with fewer than three
|
|
234
|
+
* parameters, calls it with the merged auth options to obtain the middleware.
|
|
235
|
+
*/
|
|
236
|
+
function agentTokenAuthFactory(options) {
|
|
237
|
+
return createAgentTokenAuth(options);
|
|
238
|
+
}
|
|
239
|
+
//# sourceMappingURL=agent-token-auth.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
|
|
3
|
+
* `@requires: 'any'`): process facts only. Never touches the app context, the
|
|
4
|
+
* backends or the DB, so it answers while those are still initializing or have
|
|
5
|
+
* failed — that is what a liveness probe is for; readiness stays with
|
|
6
|
+
* getStatus and the backend health entities, which remain authenticated.
|
|
7
|
+
*
|
|
8
|
+
* No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
|
|
9
|
+
* `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
|
|
10
|
+
* package version and the configured network.
|
|
11
|
+
*/
|
|
12
|
+
export interface Liveness {
|
|
13
|
+
status: 'alive';
|
|
14
|
+
timestamp: string;
|
|
15
|
+
/** Seconds since the process started. */
|
|
16
|
+
uptime: number;
|
|
17
|
+
/** @odatano/core version; '' when package.json is not where the in-place build puts it. */
|
|
18
|
+
version: string;
|
|
19
|
+
/** Configured network (cds.requires.odatano-core.network, NETWORK, default preview). */
|
|
20
|
+
network: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function buildLiveness(now?: Date): Liveness;
|
|
23
|
+
//# sourceMappingURL=liveness.d.ts.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
|
|
4
|
+
* `@requires: 'any'`): process facts only. Never touches the app context, the
|
|
5
|
+
* backends or the DB, so it answers while those are still initializing or have
|
|
6
|
+
* failed — that is what a liveness probe is for; readiness stays with
|
|
7
|
+
* getStatus and the backend health entities, which remain authenticated.
|
|
8
|
+
*
|
|
9
|
+
* No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
|
|
10
|
+
* `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
|
|
11
|
+
* package version and the configured network.
|
|
12
|
+
*/
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.buildLiveness = buildLiveness;
|
|
18
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
19
|
+
const path_1 = __importDefault(require("path"));
|
|
20
|
+
const processStartedAt = Date.now();
|
|
21
|
+
let cachedVersion = null;
|
|
22
|
+
function packageVersion() {
|
|
23
|
+
if (cachedVersion !== null)
|
|
24
|
+
return cachedVersion;
|
|
25
|
+
try {
|
|
26
|
+
// srv/utils → package root; the build compiles in place, so this holds in
|
|
27
|
+
// standalone and plugin mode alike.
|
|
28
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
29
|
+
const pkg = require(path_1.default.resolve(__dirname, '..', '..', 'package.json'));
|
|
30
|
+
cachedVersion = String(pkg.version ?? '');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
cachedVersion = '';
|
|
34
|
+
}
|
|
35
|
+
return cachedVersion;
|
|
36
|
+
}
|
|
37
|
+
function buildLiveness(now = new Date()) {
|
|
38
|
+
const requires = (cds_1.default.env?.requires ?? {});
|
|
39
|
+
const core = (requires['odatano-core'] ?? {});
|
|
40
|
+
const network = String(core.network || process.env.NETWORK || 'preview');
|
|
41
|
+
return {
|
|
42
|
+
status: 'alive',
|
|
43
|
+
timestamp: now.toISOString(),
|
|
44
|
+
uptime: Math.max(0, Math.floor((now.getTime() - processStartedAt) / 1000)),
|
|
45
|
+
version: packageVersion(),
|
|
46
|
+
network,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=liveness.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory sliding-window rate limiter, ported from NIGHTGATE
|
|
3
|
+
* (srv/utils/rate-limiter.ts). Used for grant administration and for failed
|
|
4
|
+
* agent-token attempts; nothing here touches the database.
|
|
5
|
+
*/
|
|
6
|
+
export interface RateLimiterOptions {
|
|
7
|
+
windowMs: number;
|
|
8
|
+
maxRequests: number;
|
|
9
|
+
/** Max tracked keys (default 10 000). */
|
|
10
|
+
maxKeys?: number;
|
|
11
|
+
/** Stale-key sweep interval (default 60 000 ms). */
|
|
12
|
+
sweepIntervalMs?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Max distinct keys ONE group may hold (default 64). The group is the key up
|
|
15
|
+
* to its first ':' (the principal in `principal:scope` keys). Bounds what a
|
|
16
|
+
* single caller can do to the shared table: without it, made-up scopes under
|
|
17
|
+
* one principal evicted every other caller's window.
|
|
18
|
+
*/
|
|
19
|
+
maxKeysPerGroup?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface RateCheckResult {
|
|
22
|
+
allowed: boolean;
|
|
23
|
+
retryAfterMs: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Rate-limit key for a CAP request: the principal (user, else client address)
|
|
27
|
+
* plus the scope. Batch parts carry no address and a proxy hides the real one,
|
|
28
|
+
* so the address is the last resort only. The principal is the limiter's GROUP
|
|
29
|
+
* (see maxKeysPerGroup), hence no ':' in it.
|
|
30
|
+
*/
|
|
31
|
+
export declare function principalRateKey(req: unknown, scope: string): string;
|
|
32
|
+
export declare class RateLimiter {
|
|
33
|
+
private readonly windowMs;
|
|
34
|
+
private readonly maxRequests;
|
|
35
|
+
private readonly maxKeys;
|
|
36
|
+
private readonly maxKeysPerGroup;
|
|
37
|
+
private readonly groupCounts;
|
|
38
|
+
private readonly hits;
|
|
39
|
+
private readonly sweepTimer;
|
|
40
|
+
constructor(opts: RateLimiterOptions);
|
|
41
|
+
check(key: string): RateCheckResult;
|
|
42
|
+
/** Would ONE more hit fit? Records nothing. */
|
|
43
|
+
peek(key: string): RateCheckResult;
|
|
44
|
+
/** Forget every key (tests). */
|
|
45
|
+
reset(): void;
|
|
46
|
+
/**
|
|
47
|
+
* Consume `count` slots atomically: either ALL fit into the window and are
|
|
48
|
+
* recorded, or NONE are (a rejected caller has consumed nothing).
|
|
49
|
+
*/
|
|
50
|
+
checkMany(key: string, count: number): RateCheckResult;
|
|
51
|
+
private dropKey;
|
|
52
|
+
/** Remove keys with no hits within the current window. */
|
|
53
|
+
private sweep;
|
|
54
|
+
/** Stop the background sweep timer. */
|
|
55
|
+
destroy(): void;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=rate-limiter.d.ts.map
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* In-memory sliding-window rate limiter, ported from NIGHTGATE
|
|
4
|
+
* (srv/utils/rate-limiter.ts). Used for grant administration and for failed
|
|
5
|
+
* agent-token attempts; nothing here touches the database.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.RateLimiter = void 0;
|
|
9
|
+
exports.principalRateKey = principalRateKey;
|
|
10
|
+
/** The group a key belongs to: everything before the first ':' (the principal). */
|
|
11
|
+
function groupOf(key) {
|
|
12
|
+
const i = key.indexOf(':');
|
|
13
|
+
return i < 0 ? key : key.slice(0, i);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Rate-limit key for a CAP request: the principal (user, else client address)
|
|
17
|
+
* plus the scope. Batch parts carry no address and a proxy hides the real one,
|
|
18
|
+
* so the address is the last resort only. The principal is the limiter's GROUP
|
|
19
|
+
* (see maxKeysPerGroup), hence no ':' in it.
|
|
20
|
+
*/
|
|
21
|
+
function principalRateKey(req, scope) {
|
|
22
|
+
const r = req;
|
|
23
|
+
const user = r?.user?.id;
|
|
24
|
+
const ip = r?._?.req?.ip ?? r?.http?.req?.ip ?? r?.ip;
|
|
25
|
+
const principal = user ? `user=${String(user)}`
|
|
26
|
+
: ip ? `ip=${String(ip).replace(/:/g, '.')}`
|
|
27
|
+
: 'anonymous';
|
|
28
|
+
return `${principal}:${scope}`;
|
|
29
|
+
}
|
|
30
|
+
class RateLimiter {
|
|
31
|
+
windowMs;
|
|
32
|
+
maxRequests;
|
|
33
|
+
maxKeys;
|
|
34
|
+
maxKeysPerGroup;
|
|
35
|
+
groupCounts = new Map();
|
|
36
|
+
hits = new Map();
|
|
37
|
+
sweepTimer;
|
|
38
|
+
constructor(opts) {
|
|
39
|
+
this.windowMs = opts.windowMs;
|
|
40
|
+
this.maxRequests = opts.maxRequests;
|
|
41
|
+
this.maxKeys = opts.maxKeys || 10_000;
|
|
42
|
+
this.maxKeysPerGroup = opts.maxKeysPerGroup || 64;
|
|
43
|
+
this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs || 60_000);
|
|
44
|
+
if (typeof this.sweepTimer.unref === 'function')
|
|
45
|
+
this.sweepTimer.unref();
|
|
46
|
+
}
|
|
47
|
+
check(key) {
|
|
48
|
+
return this.checkMany(key, 1);
|
|
49
|
+
}
|
|
50
|
+
/** Would ONE more hit fit? Records nothing. */
|
|
51
|
+
peek(key) {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
const inWindow = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
|
|
54
|
+
if (inWindow.length < this.maxRequests)
|
|
55
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
56
|
+
const oldest = Math.min(...inWindow);
|
|
57
|
+
return { allowed: false, retryAfterMs: Math.max(oldest + this.windowMs - now, 0) };
|
|
58
|
+
}
|
|
59
|
+
/** Forget every key (tests). */
|
|
60
|
+
reset() {
|
|
61
|
+
this.hits.clear();
|
|
62
|
+
this.groupCounts.clear();
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Consume `count` slots atomically: either ALL fit into the window and are
|
|
66
|
+
* recorded, or NONE are (a rejected caller has consumed nothing).
|
|
67
|
+
*/
|
|
68
|
+
checkMany(key, count) {
|
|
69
|
+
if (count <= 0)
|
|
70
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const windowStart = now - this.windowMs;
|
|
73
|
+
if (!this.hits.has(key)) {
|
|
74
|
+
const group = groupOf(key);
|
|
75
|
+
if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
|
|
76
|
+
return { allowed: false, retryAfterMs: this.windowMs };
|
|
77
|
+
}
|
|
78
|
+
// At capacity a NEW key evicts the least recently used one (the map is
|
|
79
|
+
// insertion ordered and `set` below re-inserts on every hit).
|
|
80
|
+
if (this.hits.size >= this.maxKeys) {
|
|
81
|
+
const oldest = this.hits.keys().next().value;
|
|
82
|
+
if (oldest !== undefined)
|
|
83
|
+
this.dropKey(oldest);
|
|
84
|
+
}
|
|
85
|
+
this.groupCounts.set(group, (this.groupCounts.get(group) ?? 0) + 1);
|
|
86
|
+
}
|
|
87
|
+
let timestamps = this.hits.get(key) || [];
|
|
88
|
+
timestamps = timestamps.filter((t) => t > windowStart);
|
|
89
|
+
this.hits.delete(key); // re-insert below = most recently used
|
|
90
|
+
if (timestamps.length + count > this.maxRequests) {
|
|
91
|
+
timestamps.sort((a, b) => a - b);
|
|
92
|
+
const oldestInWindow = timestamps[0];
|
|
93
|
+
const retryAfterMs = oldestInWindow === undefined ? this.windowMs : oldestInWindow + this.windowMs - now;
|
|
94
|
+
this.hits.set(key, timestamps);
|
|
95
|
+
return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 0) };
|
|
96
|
+
}
|
|
97
|
+
for (let i = 0; i < count; i++)
|
|
98
|
+
timestamps.push(now);
|
|
99
|
+
this.hits.set(key, timestamps);
|
|
100
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
101
|
+
}
|
|
102
|
+
dropKey(key) {
|
|
103
|
+
if (!this.hits.delete(key))
|
|
104
|
+
return;
|
|
105
|
+
const group = groupOf(key);
|
|
106
|
+
const n = (this.groupCounts.get(group) ?? 1) - 1;
|
|
107
|
+
if (n <= 0)
|
|
108
|
+
this.groupCounts.delete(group);
|
|
109
|
+
else
|
|
110
|
+
this.groupCounts.set(group, n);
|
|
111
|
+
}
|
|
112
|
+
/** Remove keys with no hits within the current window. */
|
|
113
|
+
sweep() {
|
|
114
|
+
const windowStart = Date.now() - this.windowMs;
|
|
115
|
+
for (const [key, timestamps] of this.hits) {
|
|
116
|
+
if (!timestamps.some((t) => t > windowStart))
|
|
117
|
+
this.dropKey(key);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Stop the background sweep timer. */
|
|
121
|
+
destroy() {
|
|
122
|
+
clearInterval(this.sweepTimer);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
exports.RateLimiter = RateLimiter;
|
|
126
|
+
//# sourceMappingURL=rate-limiter.js.map
|