@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
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES = exports.WORKER_LEASE_TTL_MS = void 0;
|
|
7
|
+
exports.dedupKeyFor = dedupKeyFor;
|
|
7
8
|
exports.insertJob = insertJob;
|
|
8
9
|
exports.getJobById = getJobById;
|
|
9
10
|
exports.findDueJobs = findDueJobs;
|
|
@@ -160,6 +161,21 @@ function isUniqueViolation(err) {
|
|
|
160
161
|
return text.includes('unique constraint') || text.includes('duplicate key');
|
|
161
162
|
}
|
|
162
163
|
/** The job that currently owns an idempotency key, or null when it is free. */
|
|
164
|
+
/**
|
|
165
|
+
* The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
|
|
166
|
+
* submits. Two agents (two grants, two users) may both use `order-1` on the
|
|
167
|
+
* same wallet: each must get its own job, never a "deduplicated" answer that
|
|
168
|
+
* hands one the other's job id. A key from an owner-less caller (privileged
|
|
169
|
+
* test context) stays as-is; an owned key becomes a hash of owner + key, which
|
|
170
|
+
* fits the String(100) column whatever the owner id's length and never collides
|
|
171
|
+
* with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
|
|
172
|
+
*/
|
|
173
|
+
function dedupKeyFor(owner, idempotencyKey) {
|
|
174
|
+
const scope = owner?.trim() ?? '';
|
|
175
|
+
if (!scope)
|
|
176
|
+
return idempotencyKey;
|
|
177
|
+
return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
|
|
178
|
+
}
|
|
163
179
|
async function readDedupHolder(db, walletId, kind, dedupKey) {
|
|
164
180
|
const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
|
|
165
181
|
return row ? toJobRow(row) : null;
|
|
@@ -185,10 +201,12 @@ async function readDedupHolder(db, walletId, kind, dedupKey) {
|
|
|
185
201
|
*/
|
|
186
202
|
async function insertJob(db, args) {
|
|
187
203
|
const idempotencyKey = args.idempotencyKey ?? null;
|
|
188
|
-
|
|
204
|
+
// The claim is per principal: the same key from another owner is another job.
|
|
205
|
+
const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
|
|
206
|
+
if (claim) {
|
|
189
207
|
// Fast path: an owner exists (by construction it is non-terminal). Terminal
|
|
190
208
|
// jobs release their claim, so they never show up here.
|
|
191
|
-
const holder = await readDedupHolder(db, args.walletId, args.kind,
|
|
209
|
+
const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
|
|
192
210
|
if (holder) {
|
|
193
211
|
if (holder.status !== 'failed' && holder.status !== 'cancelled') {
|
|
194
212
|
return { jobId: holder.ID, status: holder.status, deduplicated: true };
|
|
@@ -208,7 +226,7 @@ async function insertJob(db, args) {
|
|
|
208
226
|
idempotencyKey,
|
|
209
227
|
// No key → the row's own ID: unique by construction, so keyless jobs never
|
|
210
228
|
// contend for the constraint.
|
|
211
|
-
dedupKey:
|
|
229
|
+
dedupKey: claim ?? jobId,
|
|
212
230
|
request: args.request,
|
|
213
231
|
priority: args.priority ?? 100,
|
|
214
232
|
notBefore: args.notBefore ?? null,
|
|
@@ -223,9 +241,9 @@ async function insertJob(db, args) {
|
|
|
223
241
|
catch (err) {
|
|
224
242
|
// Lost the race: another transaction committed the same key first. Its job is
|
|
225
243
|
// the one and only job for this key — hand it back instead of paying twice.
|
|
226
|
-
if (!
|
|
244
|
+
if (!claim || !isUniqueViolation(err))
|
|
227
245
|
throw err;
|
|
228
|
-
const winner = await readDedupHolder(db, args.walletId, args.kind,
|
|
246
|
+
const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
|
|
229
247
|
if (!winner)
|
|
230
248
|
throw err; // constraint fired for some other reason — do not mask it
|
|
231
249
|
logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
|
|
@@ -285,14 +303,29 @@ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
|
|
|
285
303
|
async function releaseDedupClaim(db, jobId) {
|
|
286
304
|
await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
|
|
287
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Move a job from one of `fromStatuses` to `set.status` and report whether THIS
|
|
308
|
+
* call did it. The guard is the conditional UPDATE; the answer is its affected
|
|
309
|
+
* row count (every @cap-js adapter returns a number). A second caller that
|
|
310
|
+
* finds the row already in the target state gets `false`: the transition, the
|
|
311
|
+
* wallet-stats bump and the terminal event belong to the first one only.
|
|
312
|
+
* Two trackers confirming the same job used to count it twice.
|
|
313
|
+
*
|
|
314
|
+
* Fallback for an adapter that returns something that is not a count: read
|
|
315
|
+
* the row back, and accept the target state only if the row was NOT already
|
|
316
|
+
* there before this call (checked with a pre-read in that branch).
|
|
317
|
+
*/
|
|
288
318
|
async function guardedTransition(db, jobId, fromStatuses, set) {
|
|
289
|
-
await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
|
|
319
|
+
const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
|
|
290
320
|
.set(set)
|
|
291
321
|
.where({ ID: jobId, status: { in: fromStatuses } }));
|
|
292
|
-
|
|
293
|
-
|
|
322
|
+
const n = typeof affected === 'number' ? affected : Number(affected);
|
|
323
|
+
if (Number.isFinite(n))
|
|
324
|
+
return n > 0;
|
|
325
|
+
// Unknown return shape: the row is in the target state AND that state is not
|
|
326
|
+
// one it could have been in before (the guard excludes it) means we moved it.
|
|
294
327
|
const row = await getJobById(db, jobId);
|
|
295
|
-
return row?.status === set.status;
|
|
328
|
+
return row?.status === set.status && !fromStatuses.includes(set.status);
|
|
296
329
|
}
|
|
297
330
|
/** pending → building. Increments the attempt counter. Returns false when lost. */
|
|
298
331
|
async function markBuilding(db, jobId, attempt) {
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
using {odatano.cardano as db} from '../db/schema';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cardano Agent Service (v2.0)
|
|
5
|
+
*
|
|
6
|
+
* Agent grants: scoped, budgeted bearer capabilities an Admin hands to an agent
|
|
7
|
+
* instead of a full user (see AGENT_GRANTS_DESIGN.md).
|
|
8
|
+
*
|
|
9
|
+
* - CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken / RevokeAgentGrant:
|
|
10
|
+
* Admin-only administration, rate limited per principal per hour
|
|
11
|
+
* (AGENT_GRANT_ADMIN_RATE_LIMIT, default 10). The token is returned ONCE from
|
|
12
|
+
* CreateAgentGrant and RotateAgentGrantToken and stored as SHA-256 only.
|
|
13
|
+
* - AgentGrants: Admin-only projection (no token hash). A request carrying a token
|
|
14
|
+
* runs as the principal `agent:<grantId>` with the role `agent-grant` and sees
|
|
15
|
+
* exactly its own row through the row-level restriction below.
|
|
16
|
+
* - GetGrantStatus: token self-service — what am I allowed to do, how much budget
|
|
17
|
+
* is left, when do I expire. What an MCP tool needs to describe itself honestly.
|
|
18
|
+
* - GetGrantUsage: admitted calls per service and action over a window — an Admin
|
|
19
|
+
* for any grant, a token for its own (a partner usage view, ledger reconciliation).
|
|
20
|
+
*
|
|
21
|
+
* Names are this repo's PascalCase; semantics mirror NIGHTGATE's agent grants
|
|
22
|
+
* (createAgentGrant / updateAgentGrant / rotateAgentGrantToken / revokeAgentGrant /
|
|
23
|
+
* getGrantUsage), so a gateway drives both products with one code path.
|
|
24
|
+
*
|
|
25
|
+
* A token request never inherits the operator's roles: `@requires: 'Admin'` on the
|
|
26
|
+
* four actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
|
|
27
|
+
* every other Admin surface therefore refuses it by construction. The allow list,
|
|
28
|
+
* wallet pinning and daily budget are enforced by a before('*') hook on all six
|
|
29
|
+
* ODATANO services (srv/utils/agent-grants.ts). The `x-agent-token` header only
|
|
30
|
+
* reaches the services when cds.requires.odatano-core.agentGrants.enabled is set
|
|
31
|
+
* (srv/utils/agent-token-auth.ts).
|
|
32
|
+
*/
|
|
33
|
+
@requires: 'authenticated-user'
|
|
34
|
+
service CardanoAgentService @(impl: './cardano-agent-service') {
|
|
35
|
+
|
|
36
|
+
@readonly
|
|
37
|
+
@title : 'Agent Grants'
|
|
38
|
+
@description: 'Issued grants (token hash excluded). Admins see all, a token sees its own row.'
|
|
39
|
+
@restrict : [
|
|
40
|
+
{ grant: 'READ', to: 'Admin' },
|
|
41
|
+
{ grant: 'READ', to: 'agent-grant', where: 'ID = $user.grantId' }
|
|
42
|
+
]
|
|
43
|
+
entity AgentGrants as projection on db.CardanoAgentGrants excluding { tokenHash };
|
|
44
|
+
|
|
45
|
+
@title : 'Grant Status'
|
|
46
|
+
type GrantStatus {
|
|
47
|
+
grantId : UUID;
|
|
48
|
+
agentLabel : String(100);
|
|
49
|
+
allowedActions : many String;
|
|
50
|
+
walletId : String(50);
|
|
51
|
+
allowedJobKinds : many String;
|
|
52
|
+
maxJobsPerDay : Integer;
|
|
53
|
+
jobsUsedToday : Integer;
|
|
54
|
+
budgetWindow : String(10);
|
|
55
|
+
validUntil : Timestamp;
|
|
56
|
+
isActive : Boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
@title : 'Issued Grant'
|
|
60
|
+
type IssuedGrant {
|
|
61
|
+
grantId : UUID;
|
|
62
|
+
token : String; // shown once, never stored
|
|
63
|
+
allowedActions : many String;
|
|
64
|
+
walletId : String(50);
|
|
65
|
+
allowedJobKinds : many String;
|
|
66
|
+
maxJobsPerDay : Integer;
|
|
67
|
+
validUntil : Timestamp;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
@title : 'Get Grant Status'
|
|
71
|
+
@description: 'The calling token''s own grant: allow list, wallet, remaining daily budget, expiry. 400 without a token — an operator lists AgentGrants instead.'
|
|
72
|
+
function GetGrantStatus() returns GrantStatus;
|
|
73
|
+
|
|
74
|
+
@title : 'Create Agent Grant'
|
|
75
|
+
@description: 'Issue a scoped bearer token for an agent. Admin only. The token is returned once and stored as SHA-256. allowedActions must be a non-empty subset of the grantable set; walletId is required when SubmitWalletJob or CancelJob is allowed.'
|
|
76
|
+
@requires : 'Admin'
|
|
77
|
+
action CreateAgentGrant(
|
|
78
|
+
@title: 'Allowed Actions' allowedActions : many String,
|
|
79
|
+
@title: 'Wallet Id' walletId : String(50),
|
|
80
|
+
@title: 'Allowed Job Kinds' allowedJobKinds : many String,
|
|
81
|
+
@title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
|
|
82
|
+
@title: 'Valid Until' validUntil : Timestamp,
|
|
83
|
+
@title: 'Agent Label' agentLabel : String(100)
|
|
84
|
+
) returns IssuedGrant;
|
|
85
|
+
|
|
86
|
+
@title : 'Revoke Agent Grant'
|
|
87
|
+
@description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
|
|
88
|
+
@requires : 'Admin'
|
|
89
|
+
action RevokeAgentGrant(
|
|
90
|
+
@title: 'Grant Id' grantId : UUID
|
|
91
|
+
) returns Boolean;
|
|
92
|
+
|
|
93
|
+
@title : 'Rotated Grant'
|
|
94
|
+
type RotatedGrant {
|
|
95
|
+
grantId : UUID;
|
|
96
|
+
token : String; // shown once, never stored
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@title : 'Rotate Agent Grant Token'
|
|
100
|
+
@description: 'Replace the grant token; the old token is unknown from the next request. Budget, wallet, allow list and expiry survive. Admin only. 404 when the grant does not exist or is revoked.'
|
|
101
|
+
@requires : 'Admin'
|
|
102
|
+
action RotateAgentGrantToken(
|
|
103
|
+
@title: 'Grant Id' grantId : UUID
|
|
104
|
+
) returns RotatedGrant;
|
|
105
|
+
|
|
106
|
+
@title : 'Updated Grant'
|
|
107
|
+
type UpdatedGrant {
|
|
108
|
+
grantId : UUID;
|
|
109
|
+
updated : many String; // parameter names that were applied
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
@title : 'Update Agent Grant'
|
|
113
|
+
@description: 'Change label, allow list, job kinds, daily budget or expiry of an active grant. An absent parameter stays as it is; an explicit null clears agentLabel, allowedJobKinds, maxJobsPerDay or validUntil. allowedActions cannot be emptied; the wallet binding is immutable (issue a new grant). Admin only. 404 unknown grant, 409 GRANT_REVOKED.'
|
|
114
|
+
@requires : 'Admin'
|
|
115
|
+
action UpdateAgentGrant(
|
|
116
|
+
@title: 'Grant Id' grantId : UUID,
|
|
117
|
+
@title: 'Agent Label' agentLabel : String(100),
|
|
118
|
+
@title: 'Allowed Actions' allowedActions : many String,
|
|
119
|
+
@title: 'Allowed Job Kinds' allowedJobKinds : many String,
|
|
120
|
+
@title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
|
|
121
|
+
@title: 'Valid Until' validUntil : Timestamp
|
|
122
|
+
) returns UpdatedGrant;
|
|
123
|
+
|
|
124
|
+
@title : 'Grant Usage Call'
|
|
125
|
+
type GrantUsageCall {
|
|
126
|
+
service : String(60); // CardanoTransactionService, CardanoSignService, ...
|
|
127
|
+
action : String(100); // BuildSimpleAdaTransaction, SubmitTransaction, ...
|
|
128
|
+
count : Integer; // admitted and kept (budget charged and not refunded)
|
|
129
|
+
refunded : Integer; // admitted, then refunded because the handler refused the input
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
@title : 'Grant Usage'
|
|
133
|
+
type GrantUsage {
|
|
134
|
+
grantId : UUID;
|
|
135
|
+
since : Timestamp;
|
|
136
|
+
until : Timestamp;
|
|
137
|
+
calls : many GrantUsageCall;
|
|
138
|
+
total : Integer;
|
|
139
|
+
jobsUsedToday : Integer;
|
|
140
|
+
maxJobsPerDay : Integer;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
@title : 'Get Grant Usage'
|
|
144
|
+
@description: 'Admitted calls under a grant between since (default until - 30 days) and until (default now), at most 366 days, per UTC day, grouped by service and action. An Admin sees any grant (revoked ones keep their history); a token sees only its own.'
|
|
145
|
+
function GetGrantUsage(
|
|
146
|
+
@title: 'Grant Id' grantId : UUID,
|
|
147
|
+
@title: 'Since' since : Timestamp,
|
|
148
|
+
@title: 'Until' until : Timestamp
|
|
149
|
+
) returns GrantUsage;
|
|
150
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const agent_grants_1 = require("./utils/agent-grants");
|
|
4
|
+
/**
|
|
5
|
+
* CardanoAgentService handlers — grant administration (Admin) and token
|
|
6
|
+
* self-service. Everything lives in srv/utils/agent-grants.ts so the
|
|
7
|
+
* programmatic API (`issueAgentGrant`, used by @odatano/x402 to sell grants) and
|
|
8
|
+
* the OData actions share one code path.
|
|
9
|
+
*
|
|
10
|
+
* The enforcement hook for token requests is attached to all six services from
|
|
11
|
+
* src/plugin.ts (cds.on('serving')), not here.
|
|
12
|
+
*/
|
|
13
|
+
module.exports = (srv) => {
|
|
14
|
+
(0, agent_grants_1.registerAgentGrantHandlers)(srv);
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=cardano-agent-service.js.map
|
|
@@ -61,6 +61,26 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
61
61
|
|
|
62
62
|
function getStatus() returns CrawlerStatus;
|
|
63
63
|
|
|
64
|
+
@title : 'Liveness'
|
|
65
|
+
type Liveness {
|
|
66
|
+
status : String; // 'alive'
|
|
67
|
+
timestamp : Timestamp;
|
|
68
|
+
uptime : Integer; // seconds since process start
|
|
69
|
+
version : String; // @odatano/core version
|
|
70
|
+
network : String; // configured network
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Public override (see VerifyDataSignature in cardano-sign-service.cds): a
|
|
74
|
+
// liveness probe carries no credentials. 200 as long as the process answers —
|
|
75
|
+
// no backend or DB probe, no secrets, no backend names, no API key state. That
|
|
76
|
+
// stays with getStatus and the backend health entities, which remain
|
|
77
|
+
// authenticated. Mirrors NIGHTGATE's `/api/v1/indexer/getLiveness()`, so a
|
|
78
|
+
// gateway probes both products the same way.
|
|
79
|
+
@title : 'Get Liveness'
|
|
80
|
+
@description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
|
|
81
|
+
@requires : 'any'
|
|
82
|
+
function getLiveness() returns Liveness;
|
|
83
|
+
|
|
64
84
|
@title : 'Pause Crawler'
|
|
65
85
|
@description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
|
|
66
86
|
@requires : 'Admin'
|
|
@@ -9,6 +9,7 @@ const errors_1 = require("./utils/errors");
|
|
|
9
9
|
const crawler_1 = require("./blockchain/crawler");
|
|
10
10
|
const sync_state_1 = require("./blockchain/crawler/sync-state");
|
|
11
11
|
const server_1 = require("./server");
|
|
12
|
+
const liveness_1 = require("./utils/liveness");
|
|
12
13
|
const logger = cds_1.default.log('CardanoIndexerService');
|
|
13
14
|
/**
|
|
14
15
|
* CardanoIndexerService handlers — thin control/observability surface over the crawler
|
|
@@ -16,6 +17,8 @@ const logger = cds_1.default.log('CardanoIndexerService');
|
|
|
16
17
|
* cursor and starts/stops the crawler.
|
|
17
18
|
*/
|
|
18
19
|
module.exports = (srv) => {
|
|
20
|
+
// getLiveness — unauthenticated probe (@requires: 'any'); no handleRequest, no app context.
|
|
21
|
+
srv.on('getLiveness', async () => (0, liveness_1.buildLiveness)());
|
|
19
22
|
// getStatus — live run state + sync progress (numeric fields as strings, CAP-10 aligned)
|
|
20
23
|
srv.on('getStatus', async (req) => {
|
|
21
24
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
package/srv/server.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ interface AppContext {
|
|
|
13
13
|
cardanoIndexer: CardanoIndexer;
|
|
14
14
|
cardanoTxBuilder: CardanoTransactionBuilder;
|
|
15
15
|
}
|
|
16
|
+
/** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
|
|
17
|
+
export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
|
|
16
18
|
/**
|
|
17
19
|
* Get the application context (must be called after bootstrap)
|
|
18
20
|
* @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
|
|
@@ -125,5 +127,4 @@ export declare function startWalletWorkerIfConfigured(): Promise<void>;
|
|
|
125
127
|
* Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
|
|
126
128
|
*/
|
|
127
129
|
export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
|
|
128
|
-
export {};
|
|
129
130
|
//# sourceMappingURL=server.d.ts.map
|
package/srv/server.js
CHANGED
|
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
|
|
6
7
|
exports.getAppContext = getAppContext;
|
|
7
8
|
exports.getCardanoIndexer = getCardanoIndexer;
|
|
8
9
|
exports.getCardanoClient = getCardanoClient;
|
|
@@ -28,6 +29,7 @@ const errors_1 = require("./utils/errors");
|
|
|
28
29
|
const network_context_1 = require("./utils/network-context");
|
|
29
30
|
const crawler_1 = require("./blockchain/crawler");
|
|
30
31
|
const wallet_worker_1 = require("./blockchain/wallet-worker");
|
|
32
|
+
const agent_grants_config_1 = require("./utils/agent-grants-config");
|
|
31
33
|
const process_1 = require("process");
|
|
32
34
|
const logger = cds_1.default.log('ODATANO');
|
|
33
35
|
const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
|
|
@@ -91,6 +93,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
|
|
|
91
93
|
cardanoTxBuilder,
|
|
92
94
|
};
|
|
93
95
|
}
|
|
96
|
+
/** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
|
|
97
|
+
var agent_grants_config_2 = require("./utils/agent-grants-config");
|
|
98
|
+
Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
|
|
99
|
+
Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
|
|
100
|
+
// Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
|
|
101
|
+
// cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
|
|
102
|
+
// agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
|
|
103
|
+
// imports this file before cds.server() instantiates the middlewares, so the
|
|
104
|
+
// auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
|
|
105
|
+
(0, agent_grants_config_1.activateAgentGrants)();
|
|
94
106
|
/**
|
|
95
107
|
* Get the application context (must be called after bootstrap)
|
|
96
108
|
* @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-grant feature switch. Read from `cds.requires.odatano-core.agentGrants`
|
|
3
|
+
* first, then from the environment; kept in its own tiny module because
|
|
4
|
+
* src/plugin.ts reads it at plugin load, before any blockchain module may be
|
|
5
|
+
* required.
|
|
6
|
+
*
|
|
7
|
+
* cds: "odatano-core": { "agentGrants": { "enabled": true, "delegate": "mocked", "adminRateLimit": 10 } }
|
|
8
|
+
* env: AGENT_GRANTS_ENABLED=true AGENT_GRANTS_DELEGATE=mocked|basic|jwt|xsuaa|ias|dummy
|
|
9
|
+
* AGENT_GRANT_ADMIN_RATE_LIMIT=10
|
|
10
|
+
*
|
|
11
|
+
* `delegate` names the CAP auth strategy that keeps authenticating every
|
|
12
|
+
* request WITHOUT an `x-agent-token` header (the transport lane only adds the
|
|
13
|
+
* token path next to it). Default: the configured `cds.requires.auth.kind`.
|
|
14
|
+
*
|
|
15
|
+
* `adminRateLimit` is the number of grant-administration calls
|
|
16
|
+
* (CreateAgentGrant, UpdateAgentGrant, RotateAgentGrantToken, RevokeAgentGrant)
|
|
17
|
+
* one principal may make per hour; NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`.
|
|
18
|
+
* A gateway that mints for everybody (ODATANO ACCESS) raises it.
|
|
19
|
+
*/
|
|
20
|
+
export interface AgentGrantsConfig {
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
/** CAP auth kind the transport middleware delegates to for non-token requests. */
|
|
23
|
+
delegate: string;
|
|
24
|
+
/** Grant administration calls per principal per hour (integer >= 1). */
|
|
25
|
+
adminRateLimit: number;
|
|
26
|
+
}
|
|
27
|
+
export declare const AGENT_GRANTS_DELEGATES: readonly string[];
|
|
28
|
+
export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
29
|
+
/**
|
|
30
|
+
* The admin rate limit: `agentGrants.adminRateLimit`, then
|
|
31
|
+
* `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
|
|
32
|
+
* integer, below 1) is logged once and falls back to the default — a typo in
|
|
33
|
+
* this knob must not switch the whole feature off, unlike a wrong delegate.
|
|
34
|
+
*/
|
|
35
|
+
export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
|
|
36
|
+
/** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
|
|
37
|
+
export declare function configuredAuth(): Record<string, unknown>;
|
|
38
|
+
/**
|
|
39
|
+
* A custom `cds.requires.auth.impl` the host configured before us (anything
|
|
40
|
+
* that is not this package's middleware). It keeps authenticating every
|
|
41
|
+
* non-token request: the lane wraps it instead of replacing it.
|
|
42
|
+
*/
|
|
43
|
+
export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
|
|
44
|
+
export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
|
|
45
|
+
/**
|
|
46
|
+
* Switch agent grants on for this process when configured. Called from BOTH
|
|
47
|
+
* entry points, because CAP loads `cds-plugin.js` only from a project's
|
|
48
|
+
* dependencies, never from the project itself:
|
|
49
|
+
* - src/plugin.ts at plugin load (consumer app), and
|
|
50
|
+
* - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
|
|
51
|
+
* bin/serve.js imports the local server.js BEFORE cds.server() builds its
|
|
52
|
+
* middlewares — the last moment `cds.requires.auth.impl` can still change).
|
|
53
|
+
*
|
|
54
|
+
* When enabled:
|
|
55
|
+
* - the transport auth becomes srv/utils/agent-token-auth, which admits the
|
|
56
|
+
* `x-agent-token` header on the six service paths and delegates every other
|
|
57
|
+
* request to the strategy that was configured before (kept as the delegate);
|
|
58
|
+
* - each of the six services gets the enforcement hook once it is served.
|
|
59
|
+
*
|
|
60
|
+
* Never throws: a misconfiguration is logged and the feature stays off, so a
|
|
61
|
+
* host app never fails to start because of it. Returns whether grants are on.
|
|
62
|
+
*/
|
|
63
|
+
export declare function activateAgentGrants(): boolean;
|
|
64
|
+
//# sourceMappingURL=agent-grants-config.d.ts.map
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
|
|
7
|
+
exports.loadGrantAdminRateLimit = loadGrantAdminRateLimit;
|
|
8
|
+
exports.configuredAuth = configuredAuth;
|
|
9
|
+
exports.customAuthImpl = customAuthImpl;
|
|
10
|
+
exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
|
|
11
|
+
exports.activateAgentGrants = activateAgentGrants;
|
|
12
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
13
|
+
const path_1 = __importDefault(require("path"));
|
|
14
|
+
exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
|
|
15
|
+
exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
16
|
+
/**
|
|
17
|
+
* The admin rate limit: `agentGrants.adminRateLimit`, then
|
|
18
|
+
* `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
|
|
19
|
+
* integer, below 1) is logged once and falls back to the default — a typo in
|
|
20
|
+
* this knob must not switch the whole feature off, unlike a wrong delegate.
|
|
21
|
+
*/
|
|
22
|
+
function loadGrantAdminRateLimit(env = process.env) {
|
|
23
|
+
const cfg = envRecord();
|
|
24
|
+
const raw = cfg.adminRateLimit !== undefined ? cfg.adminRateLimit : env.AGENT_GRANT_ADMIN_RATE_LIMIT;
|
|
25
|
+
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
26
|
+
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
27
|
+
const n = Number(raw);
|
|
28
|
+
if (!Number.isInteger(n) || n < 1) {
|
|
29
|
+
cds_1.default.log('ODATANO').warn(`AGENT_GRANT_ADMIN_RATE_LIMIT "${String(raw)}" is not an integer >= 1; using ${exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT}`);
|
|
30
|
+
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
31
|
+
}
|
|
32
|
+
return n;
|
|
33
|
+
}
|
|
34
|
+
function envRecord() {
|
|
35
|
+
const requires = (cds_1.default.env?.requires ?? {});
|
|
36
|
+
const core = (requires['odatano-core'] ?? {});
|
|
37
|
+
return (core.agentGrants ?? {});
|
|
38
|
+
}
|
|
39
|
+
/** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
|
|
40
|
+
function configuredAuth() {
|
|
41
|
+
const auth = cds_1.default.env?.requires?.auth;
|
|
42
|
+
if (typeof auth === 'string')
|
|
43
|
+
return { kind: auth };
|
|
44
|
+
return (auth ?? {});
|
|
45
|
+
}
|
|
46
|
+
/** Our own middleware module, recognisable in `auth.impl` so activation stays idempotent. */
|
|
47
|
+
const OUR_IMPL = 'agent-token-auth';
|
|
48
|
+
/**
|
|
49
|
+
* A custom `cds.requires.auth.impl` the host configured before us (anything
|
|
50
|
+
* that is not this package's middleware). It keeps authenticating every
|
|
51
|
+
* non-token request: the lane wraps it instead of replacing it.
|
|
52
|
+
*/
|
|
53
|
+
function customAuthImpl(auth = configuredAuth()) {
|
|
54
|
+
const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
|
|
55
|
+
if (!impl || impl.includes(OUR_IMPL))
|
|
56
|
+
return null;
|
|
57
|
+
return impl;
|
|
58
|
+
}
|
|
59
|
+
function loadAgentGrantsConfig(env = process.env) {
|
|
60
|
+
const cfg = envRecord();
|
|
61
|
+
const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
|
|
62
|
+
const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
|
|
63
|
+
const auth = configuredAuth();
|
|
64
|
+
const authKind = String(auth.kind ?? 'mocked');
|
|
65
|
+
// A host with its own auth.impl keeps it as the delegate ("custom") unless
|
|
66
|
+
// an explicit delegate says otherwise.
|
|
67
|
+
const fallback = customAuthImpl(auth) ? 'custom' : authKind;
|
|
68
|
+
const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
|
|
69
|
+
// `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
|
|
70
|
+
const delegate = delegateRaw.replace(/-auth$/, '');
|
|
71
|
+
if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
|
|
72
|
+
throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
|
|
73
|
+
}
|
|
74
|
+
if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
|
|
75
|
+
throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
|
|
76
|
+
}
|
|
77
|
+
return { enabled, delegate, adminRateLimit: loadGrantAdminRateLimit(env) };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Marker on the shared `cds` facade: the activation below must run exactly once
|
|
81
|
+
* per process even though this module can be loaded twice (natively by CAP /
|
|
82
|
+
* src/plugin.ts and again through a test runner's transform). A module-level
|
|
83
|
+
* flag would not survive that; the `cds` singleton does.
|
|
84
|
+
*/
|
|
85
|
+
const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
|
|
86
|
+
/**
|
|
87
|
+
* Switch agent grants on for this process when configured. Called from BOTH
|
|
88
|
+
* entry points, because CAP loads `cds-plugin.js` only from a project's
|
|
89
|
+
* dependencies, never from the project itself:
|
|
90
|
+
* - src/plugin.ts at plugin load (consumer app), and
|
|
91
|
+
* - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
|
|
92
|
+
* bin/serve.js imports the local server.js BEFORE cds.server() builds its
|
|
93
|
+
* middlewares — the last moment `cds.requires.auth.impl` can still change).
|
|
94
|
+
*
|
|
95
|
+
* When enabled:
|
|
96
|
+
* - the transport auth becomes srv/utils/agent-token-auth, which admits the
|
|
97
|
+
* `x-agent-token` header on the six service paths and delegates every other
|
|
98
|
+
* request to the strategy that was configured before (kept as the delegate);
|
|
99
|
+
* - each of the six services gets the enforcement hook once it is served.
|
|
100
|
+
*
|
|
101
|
+
* Never throws: a misconfiguration is logged and the feature stays off, so a
|
|
102
|
+
* host app never fails to start because of it. Returns whether grants are on.
|
|
103
|
+
*/
|
|
104
|
+
function activateAgentGrants() {
|
|
105
|
+
const facade = cds_1.default;
|
|
106
|
+
if (facade[ACTIVATED] !== undefined)
|
|
107
|
+
return facade[ACTIVATED] === true;
|
|
108
|
+
const logger = cds_1.default.log('ODATANO');
|
|
109
|
+
try {
|
|
110
|
+
const agentGrants = loadAgentGrantsConfig();
|
|
111
|
+
if (!agentGrants.enabled) {
|
|
112
|
+
facade[ACTIVATED] = false;
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
const auth = configuredAuth();
|
|
116
|
+
const current = typeof auth.impl === 'string' ? auth.impl : '';
|
|
117
|
+
if (!current.includes(OUR_IMPL)) {
|
|
118
|
+
// A host's own auth.impl is preserved as the delegate: the lane only adds
|
|
119
|
+
// the token path in front of it, it never replaces the host's gate.
|
|
120
|
+
const original = customAuthImpl(auth);
|
|
121
|
+
cds_1.default.env.requires.auth = {
|
|
122
|
+
...auth,
|
|
123
|
+
kind: auth.kind ?? agentGrants.delegate,
|
|
124
|
+
impl: path_1.default.join(__dirname, OUR_IMPL),
|
|
125
|
+
agentGrantsDelegate: agentGrants.delegate,
|
|
126
|
+
...(original ? { agentGrantsDelegateImpl: original } : {})
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
cds_1.default.on('serving', (srv) => {
|
|
130
|
+
const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
|
|
131
|
+
if (AGENT_SERVICE_NAMES.includes(srv.name))
|
|
132
|
+
attachAgentGrantEnforcement(srv);
|
|
133
|
+
});
|
|
134
|
+
facade[ACTIVATED] = true;
|
|
135
|
+
logger.info(`Agent grants enabled (transport delegate: ${agentGrants.delegate})`);
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
facade[ACTIVATED] = false;
|
|
140
|
+
logger.error('Agent grants not enabled:', err instanceof Error ? err.message : err);
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=agent-grants-config.js.map
|