@x12i/kinedrop 0.0.0-stage → 0.2.0
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/apps-operations.mjs +1867 -0
- package/index.d.ts +369 -0
- package/index.mjs +429 -0
- package/keyrox.mjs +106 -0
- package/object-storage.mjs +37 -0
- package/package.json +9 -4
- package/placement-operations.mjs +1772 -0
- package/service-operations.mjs +2610 -0
- package/validate.mjs +46 -0
- package/README.md +0 -3
package/index.mjs
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/** Portable, dependency-free client. Credentials stay in memory and never enter URLs. */
|
|
2
|
+
import { APPS_OPERATIONS, APPS_MCP_TOOLS } from './apps-operations.mjs';
|
|
3
|
+
import {SERVICE_OPERATIONS,SERVICE_MCP_TOOLS} from './service-operations.mjs';
|
|
4
|
+
import {PLACEMENT_OPERATIONS,PLACEMENT_MCP_TOOLS} from './placement-operations.mjs';
|
|
5
|
+
import {validateInput} from './validate.mjs';
|
|
6
|
+
import {objectStorageApi} from './object-storage.mjs';
|
|
7
|
+
import {createKeyroxTokenProvider} from './keyrox.mjs';
|
|
8
|
+
export {createKeyroxTokenProvider, keyroxClientOptionsFromEnv, keyroxIssuer, keyroxRequest} from './keyrox.mjs';
|
|
9
|
+
export { APPS_OPERATIONS, APPS_MCP_TOOLS,SERVICE_OPERATIONS,SERVICE_MCP_TOOLS,PLACEMENT_OPERATIONS,PLACEMENT_MCP_TOOLS };
|
|
10
|
+
export {validateInput as validateServiceInput} from './validate.mjs';
|
|
11
|
+
export class KineDropError extends Error {
|
|
12
|
+
constructor(message, { status = 0, code = 'REQUEST_FAILED', details, correlationId } = {}) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'KineDropError';
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.details = details;
|
|
18
|
+
this.correlationId = correlationId;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const RESPONSE_LIMIT_ERROR=Symbol('kinedrop-response-limit');
|
|
23
|
+
const discardResponse=response=>{try{Promise.resolve(response?.body?.cancel?.()).catch(()=>{});}catch{}};
|
|
24
|
+
async function boundedResponseText(response,{maxBytes,signal,assertActive}){
|
|
25
|
+
let reader;
|
|
26
|
+
const cancel=()=>{try{Promise.resolve(reader?reader.cancel():response.body?.cancel?.()).catch(()=>{});}catch{}};
|
|
27
|
+
const limit=()=>Object.assign(new KineDropError('KineDrop response exceeds the configured response size limit.',{status:response.status,code:'RESPONSE_TOO_LARGE'}),{[RESPONSE_LIMIT_ERROR]:true});
|
|
28
|
+
signal.addEventListener('abort',cancel,{once:true});
|
|
29
|
+
try{
|
|
30
|
+
assertActive();const declared=response.headers?.get?.('content-length'),encoding=response.headers?.get?.('content-encoding');
|
|
31
|
+
if(response.body!==null&&(!encoding||encoding.toLowerCase()==='identity')&&typeof declared==='string'&&/^\d+$/.test(declared)&&Number(declared)>maxBytes)throw limit();
|
|
32
|
+
if(response.body?.getReader){
|
|
33
|
+
reader=response.body.getReader();const decoder=new TextDecoder(),parts=[];let bytes=0;
|
|
34
|
+
for(;;){assertActive();const part=await reader.read();assertActive();if(part.done)break;if(!(part.value instanceof Uint8Array))throw new Error();bytes+=part.value.byteLength;if(bytes>maxBytes)throw limit();parts.push(decoder.decode(part.value,{stream:true}));}
|
|
35
|
+
parts.push(decoder.decode());assertActive();return parts.join('');
|
|
36
|
+
}
|
|
37
|
+
// Custom Fetch ports without a ReadableStream can only be checked after their text method completes.
|
|
38
|
+
const text=await response.text();assertActive();if(typeof text!=='string')throw new Error();if(new TextEncoder().encode(text).byteLength>maxBytes)throw limit();return text;
|
|
39
|
+
}catch(error){cancel();throw error;}
|
|
40
|
+
finally{signal.removeEventListener('abort',cancel);try{reader?.releaseLock();}catch{}}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const segment = value => {
|
|
44
|
+
if (typeof value !== 'string' || !value || value.length > 512 || value === '.' || value === '..') {
|
|
45
|
+
throw new TypeError('A non-empty identifier is required.');
|
|
46
|
+
}
|
|
47
|
+
return encodeURIComponent(value);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
function validateBaseUrl(baseUrl) {
|
|
51
|
+
const url = new URL(baseUrl);
|
|
52
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
53
|
+
throw new TypeError('baseUrl must be an HTTP(S) URL without credentials, a query, or a fragment.');
|
|
54
|
+
}
|
|
55
|
+
const literalLoopback = url.hostname === 'localhost' || url.hostname === '[::1]' || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(url.hostname);
|
|
56
|
+
if (url.protocol !== 'https:' && !literalLoopback) {
|
|
57
|
+
throw new TypeError('Remote KineDrop connections require HTTPS. HTTP is allowed only for localhost, 127.x.x.x, or [::1].');
|
|
58
|
+
}
|
|
59
|
+
return url;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Exact semantic-read endpoints; neighboring mutation routes remain write-only. */
|
|
63
|
+
export function isReadOnlyRequest(method, path) {
|
|
64
|
+
method = String(method).toUpperCase();
|
|
65
|
+
return ['GET', 'HEAD'].includes(method) || method === 'POST' && (
|
|
66
|
+
/^\/v1\/orgs\/[^/]+\/documents\/(?:[^/]+\/)?bundles\/[^/]+\/(?:spans|extract)$/.test(path) ||
|
|
67
|
+
/^\/v1\/orgs\/[^/]+\/hybrid\/[^/]+\/(?:collections\/[^/]+\/query|graph\/walk)$/.test(path) ||
|
|
68
|
+
/^\/v1\/orgs\/[^/]+\/(?:sql|search|analytics)\/[^/]+\/query$/.test(path) ||
|
|
69
|
+
/^\/v1\/orgs\/[^/]+\/databases\/[^/]+\/collections\/[^/]+\/query$/.test(path) ||
|
|
70
|
+
/^\/v1\/orgs\/[^/]+\/apps\/[^/]+\/environments\/[^/]+\/plans$/.test(path) ||
|
|
71
|
+
/^\/v1\/orgs\/[^/]+\/projects\/[^/]+\/environments\/[^/]+\/countex\/sample-query$/.test(path) ||
|
|
72
|
+
/^\/v1\/orgs\/[^/]+\/database-bridge\/(?:compile|query|rehearsal|migration-review)$/.test(path) ||
|
|
73
|
+
/^\/v1\/countex\/rollups\/[^/]+\/query$/.test(path)
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class KineDropClient {
|
|
78
|
+
constructor({ baseUrl = 'http://127.0.0.1:4200', token, keyrox, orgId, timeoutMs = 30_000, maxResponseBytes = 64 * 1024 * 1024, fetch: fetchOption, fetchImpl = fetchOption ?? globalThis.fetch, readOnly = false } = {}) {
|
|
79
|
+
const url = validateBaseUrl(baseUrl);
|
|
80
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('A Fetch API implementation is required.');
|
|
81
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) throw new TypeError('timeoutMs must be between 1 and 300000.');
|
|
82
|
+
if(!Number.isSafeInteger(maxResponseBytes)||maxResponseBytes<1024||maxResponseBytes>1024*1024*1024)throw new TypeError('maxResponseBytes must be an integer between 1024 and 1073741824.');
|
|
83
|
+
if (token != null && (typeof token !== 'string' || /[\r\n]/.test(token))) throw new TypeError('Invalid bearer token.');
|
|
84
|
+
if (token?.startsWith('krx_')) throw new TypeError('Supply Keyrox long-lived credentials through the keyrox client option.');
|
|
85
|
+
if (token != null && keyrox) throw new TypeError('Supply either a bearer token or Keyrox credential configuration.');
|
|
86
|
+
Object.defineProperty(this, 'baseUrl', { value: url.href.replace(/\/$/, ''), enumerable: true });
|
|
87
|
+
Object.defineProperty(this, 'token', { value: token, writable: true, enumerable: false });
|
|
88
|
+
if (keyrox) Object.defineProperty(this, 'tokenProvider', { value: createKeyroxTokenProvider({ ...keyrox, fetchImpl, authority: () => this.auth.authority() }) });
|
|
89
|
+
Object.defineProperty(this,'maxResponseBytes',{value:maxResponseBytes,enumerable:true});
|
|
90
|
+
this.orgId = orgId;
|
|
91
|
+
this.timeoutMs = timeoutMs;
|
|
92
|
+
this.fetch = fetchImpl;
|
|
93
|
+
this.readOnly = readOnly;
|
|
94
|
+
|
|
95
|
+
this.orgs = {
|
|
96
|
+
list: () => this.request('GET', '/v1/orgs'),
|
|
97
|
+
create: (data, options) => this.request('POST', '/v1/orgs', typeof data === 'string' ? { name: data } : data, options),
|
|
98
|
+
};
|
|
99
|
+
this.workspaces = {
|
|
100
|
+
list: () => this.request('GET', '/v1/workspace-enrollments'),
|
|
101
|
+
plan: (input, options) => this.request('POST', '/v1/workspace-enrollments', input, options),
|
|
102
|
+
apply: (id, options) => this.request('POST', '/v1/workspace-enrollments/' + segment(id) + '/apply', {}, options),
|
|
103
|
+
inspect: id => this.request('GET', '/v1/workspace-enrollments/' + segment(id)),
|
|
104
|
+
inventory: () => this.request('GET', this.orgPath('/workspace-inventory')),
|
|
105
|
+
};
|
|
106
|
+
this.resources = {
|
|
107
|
+
list: () => this.request('GET', this.orgPath('/resources')),
|
|
108
|
+
create: (service, data, options) => this.request('POST', this.orgPath('/' + segment(service)), data, options),
|
|
109
|
+
get: (service, id) => this.request('GET', this.orgPath('/' + segment(service) + '/' + segment(id))),
|
|
110
|
+
manifest: (service, id) => this.request('GET', this.orgPath('/' + segment(service) + '/' + segment(id) + '/manifest')),
|
|
111
|
+
planDelete: (service, resourceId, options) => this.request('POST', this.orgPath('/plans'), { operation: 'delete', service, resourceId }, options),
|
|
112
|
+
confirmDelete: (planId, confirmationToken, options) => this.request('POST', this.orgPath('/plans/' + segment(planId) + '/confirm'), { confirmationToken }, options),
|
|
113
|
+
};
|
|
114
|
+
this.objectStorage=objectStorageApi(this,segment);
|
|
115
|
+
const queuePath=(id,queue)=>this.orgPath('/streams/'+segment(id)+'/queues/'+segment(queue));
|
|
116
|
+
this.messaging={
|
|
117
|
+
capabilities:id=>this.request('GET',this.orgPath('/streams/'+(id?segment(id)+'/':'')+'capabilities')),
|
|
118
|
+
send:(id,queue,input,options)=>this.request('POST',queuePath(id,queue)+'/messages',input,options),
|
|
119
|
+
receive:(id,queue,input={},options)=>this.request('POST',queuePath(id,queue)+'/receive',input,options),
|
|
120
|
+
settle:(id,queue,messageId,action,input,options)=>this.request('POST',queuePath(id,queue)+'/messages/'+segment(messageId)+'/'+segment(action),input,options),
|
|
121
|
+
peek:(id,queue)=>this.request('GET',queuePath(id,queue)+'/messages'),
|
|
122
|
+
deadletters:(id,queue)=>this.request('GET',queuePath(id,queue)+'/deadletters'),
|
|
123
|
+
};
|
|
124
|
+
this.projects={
|
|
125
|
+
list:()=>this.request('GET',this.orgPath('/projects')),
|
|
126
|
+
create:(input,options)=>this.request('POST',this.orgPath('/projects'),typeof input==='string'?{name:input}:input,options),
|
|
127
|
+
};
|
|
128
|
+
const tenantPath=id=>this.orgPath('/tenants'+(id===undefined?'':'/'+segment(id)));
|
|
129
|
+
this.fleet={nodes:{list:()=>this.request('GET','/v1/fleet/nodes'),get:id=>this.request('GET','/v1/fleet/nodes/'+segment(id))}};
|
|
130
|
+
this.fleet.rebalance={plan:(nodeId,input,options)=>this.invokeService('fleet.rebalance.plan',{...input,nodeId},options),apply:(nodeId,input,options)=>this.invokeService('fleet.rebalance.apply',{...input,nodeId},options)};
|
|
131
|
+
this.placement={
|
|
132
|
+
capabilities:()=>this.invokePlacement('placement.capabilities'),
|
|
133
|
+
observations:{list:input=>this.invokePlacement('placement.observations.list',input),create:(input,options)=>this.invokePlacement('placement.observations.create',input,options)},
|
|
134
|
+
proposals:{create:(input,options)=>this.invokePlacement('placement.proposals.create',input,options)},
|
|
135
|
+
};
|
|
136
|
+
this.onboarding={intents:{
|
|
137
|
+
list:input=>this.invokePlacement('onboarding.intents.list',input),
|
|
138
|
+
create:(input,options)=>this.invokePlacement('onboarding.intents.create',input,options),
|
|
139
|
+
get:input=>this.invokePlacement('onboarding.intents.get',input),
|
|
140
|
+
...Object.fromEntries(['bind','resume','reconcile','release'].map(action=>[action,(input,options)=>this.invokePlacement('onboarding.intents.'+action,input,options)])),
|
|
141
|
+
},expire:(input,options)=>this.invokePlacement('onboarding.expire',input,options)};
|
|
142
|
+
this.tenants={list:()=>this.request('GET',tenantPath()),create:(input,options)=>this.request('POST',tenantPath(),input,options),get:id=>this.request('GET',tenantPath(id)),rotate:(id,options)=>this.request('POST',tenantPath(id)+'/rotations',{},options),planOffboard:(id,options)=>this.request('POST',tenantPath(id)+'/offboarding-plans',{},options),offboard:(id,input,options)=>this.request('POST',tenantPath(id)+'/offboardings',input,options)};
|
|
143
|
+
this.tenants.kafka={topics:{
|
|
144
|
+
list:tenantId=>this.invokeService('tenants.topics.list',{tenantId}),
|
|
145
|
+
get:(tenantId,topic)=>this.invokeService('tenants.topics.get',{tenantId,topic}),
|
|
146
|
+
create:(tenantId,topic,input={},options)=>this.invokeService('tenants.topics.put',{...input,tenantId,topic},options),
|
|
147
|
+
planDelete:(tenantId,topic,options)=>this.invokeService('tenants.topics.delete.plan',{tenantId,topic},options),
|
|
148
|
+
delete:(tenantId,topic,input,options)=>this.invokeService('tenants.topics.delete',{...input,tenantId,topic},options),
|
|
149
|
+
}};
|
|
150
|
+
this.tenants.access={
|
|
151
|
+
list:tenantId=>this.invokeService('tenants.temporaryAccess.list',{tenantId}),
|
|
152
|
+
grant:(tenantId,input,options)=>this.invokeService('tenants.temporaryAccess.create',{...input,tenantId},options),
|
|
153
|
+
planRevoke:(tenantId,accessId,options)=>this.invokeService('tenants.temporaryAccess.revoke.plan',{tenantId,accessId},options),
|
|
154
|
+
revoke:(tenantId,accessId,input,options)=>this.invokeService('tenants.temporaryAccess.revoke',{...input,tenantId,accessId},options),
|
|
155
|
+
};
|
|
156
|
+
this.operations={list:()=>this.request('GET',this.orgPath('/operations')),get:id=>this.request('GET',this.orgPath('/operations/'+segment(id)))};
|
|
157
|
+
const cachePath=(id,key)=>this.orgPath('/caches/'+segment(id)+'/entries/'+segment(key));
|
|
158
|
+
this.cache={binding:id=>this.request('GET',this.orgPath('/caches/'+segment(id)+'/binding')),get:(id,key)=>this.request('GET',cachePath(id,key)),set:(id,key,input,options)=>this.request('PUT',cachePath(id,key),input,options),delete:(id,key,options)=>this.request('DELETE',cachePath(id,key),undefined,options)};
|
|
159
|
+
const objectPath=(id,key)=>this.orgPath('/storage/'+segment(id)+'/objects'+(key===undefined?'':'/'+String(key).split('/').map(segment).join('/')));
|
|
160
|
+
this.storage={
|
|
161
|
+
list:id=>this.request('GET',objectPath(id)),get:(id,key)=>this.request('GET',objectPath(id,key)),
|
|
162
|
+
put:(id,key,input,options)=>this.request('PUT',objectPath(id,key),input,options),delete:(id,key,options)=>this.request('DELETE',objectPath(id,key),undefined,options),
|
|
163
|
+
createBucket:(id,options)=>this.request('PUT',this.orgPath('/storage/'+segment(id)+'/bucket'),{},options),
|
|
164
|
+
};
|
|
165
|
+
const dataPath=(service,id,suffix)=>this.orgPath('/'+service+'/'+segment(id)+suffix);
|
|
166
|
+
const writeService = engine => {
|
|
167
|
+
if (engine === 'mongo') return 'databases';
|
|
168
|
+
if (engine === 'postgres') return 'sql';
|
|
169
|
+
throw new TypeError('Choose mongo or postgres for the managed write engine');
|
|
170
|
+
};
|
|
171
|
+
const writeTarget = (engine, id, target) => dataPath(
|
|
172
|
+
writeService(engine), id, (engine === 'mongo' ? '/collections/' : '/tables/') + segment(target) + '/writes',
|
|
173
|
+
);
|
|
174
|
+
this.writes = {
|
|
175
|
+
mongo: (id, collection, input, options) => this.request('POST', writeTarget('mongo', id, collection), input, options),
|
|
176
|
+
postgres: (id, table, input, options) => this.request('POST', writeTarget('postgres', id, table), input, options),
|
|
177
|
+
policy: (engine, id, target, options) => this.request('GET', target === undefined ? dataPath(writeService(engine), id, '/writes') : writeTarget(engine, id, target), undefined, options),
|
|
178
|
+
status: (engine, id, writeId, options) => this.request('GET', dataPath(writeService(engine), id, '/writes/' + segment(writeId)), undefined, options),
|
|
179
|
+
};
|
|
180
|
+
this.sql = {
|
|
181
|
+
query: (id, input, options) => this.request('POST', dataPath('sql', id, '/query'), input, options),
|
|
182
|
+
createTable: (id, input, options) => this.request('POST', dataPath('sql', id, '/tables'), input, options),
|
|
183
|
+
insert: (id, table, rows, { mode, ...options } = {}) => {
|
|
184
|
+
if (mode !== undefined && !['sync', 'async'].includes(mode)) throw new TypeError('Choose sync or async for the write mode');
|
|
185
|
+
const suffix = '/tables/' + segment(table) + '/rows' + (mode === undefined ? '' : '?mode=' + mode);
|
|
186
|
+
return this.request('POST', dataPath('sql', id, suffix), { rows }, options);
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
this.search={query:(id,input,options)=>this.request('POST',dataPath('search',id,'/query'),input,options),createIndex:(id,input,options)=>this.request('PUT',dataPath('search',id,'/index'),input,options),insert:(id,input,options)=>this.request('POST',dataPath('search',id,'/documents'),input,options)};
|
|
190
|
+
this.analytics={query:(id,input,options)=>this.request('POST',dataPath('analytics',id,'/query'),input,options),createTable:(id,input,options)=>this.request('POST',dataPath('analytics',id,'/tables'),input,options),ingest:(id,input,options)=>this.request('POST',dataPath('analytics',id,'/ingest'),input,options)};
|
|
191
|
+
this.stacks = {
|
|
192
|
+
list: () => this.request('GET', this.orgPath('/stacks')),
|
|
193
|
+
plan: (blueprint, options) => this.request('POST', this.orgPath('/stacks/plan'), blueprint, options),
|
|
194
|
+
apply: (planId, options) => this.request('POST', this.orgPath('/stacks/apply'), { planId }, options),
|
|
195
|
+
};
|
|
196
|
+
this.docs = {
|
|
197
|
+
capabilities:()=>this.request('GET',this.orgPath('/documents/capabilities')),
|
|
198
|
+
ingest: (input, options) => this.request('POST', this.orgPath('/documents/ingest'), typeof input === 'string' ? { text: input, onSecret: 'redact' } : input, options),
|
|
199
|
+
bundles: {
|
|
200
|
+
list: () => this.request('GET', this.orgPath('/documents/bundles')),
|
|
201
|
+
get: documentId => this.request('GET', this.orgPath('/documents/bundles/' + segment(documentId))),
|
|
202
|
+
},
|
|
203
|
+
resolveSpan: (documentId, range, options) => this.request('POST', this.orgPath('/documents/bundles/' + segment(documentId) + '/spans'), range, options),
|
|
204
|
+
extract: (documentId, input = {}, options) => this.request('POST', this.orgPath('/documents/bundles/' + segment(documentId) + '/extract'), input, options),
|
|
205
|
+
};
|
|
206
|
+
const hybridPath=(storeId,suffix)=>this.orgPath('/hybrid/'+segment(storeId)+suffix);
|
|
207
|
+
this.hybrid={
|
|
208
|
+
query:(storeId,collection,input={},options)=>this.request('POST',hybridPath(storeId,'/collections/'+segment(collection)+'/query'),input,options),
|
|
209
|
+
insert:(storeId,collection,document,options)=>this.request('POST',hybridPath(storeId,'/collections/'+segment(collection)+'/documents'),document,options),
|
|
210
|
+
list:(storeId,collection)=>this.request('GET',hybridPath(storeId,'/collections/'+segment(collection)+'/documents')),
|
|
211
|
+
get:(storeId,collection,id)=>this.request('GET',hybridPath(storeId,'/collections/'+segment(collection)+'/documents/'+segment(id))),
|
|
212
|
+
update:(storeId,collection,id,input,options)=>this.request('PATCH',hybridPath(storeId,'/collections/'+segment(collection)+'/documents/'+segment(id)),input,options),
|
|
213
|
+
delete:(storeId,collection,id,options)=>this.request('DELETE',hybridPath(storeId,'/collections/'+segment(collection)+'/documents/'+segment(id)),undefined,options),
|
|
214
|
+
graph:{
|
|
215
|
+
nodes:storeId=>this.request('GET',hybridPath(storeId,'/graph/nodes')),
|
|
216
|
+
edges:storeId=>this.request('GET',hybridPath(storeId,'/graph/edges')),
|
|
217
|
+
addNode:(storeId,node,options)=>this.request('POST',hybridPath(storeId,'/graph/nodes'),node,options),
|
|
218
|
+
link:(storeId,edge,options)=>this.request('POST',hybridPath(storeId,'/graph/edges'),edge,options),
|
|
219
|
+
walk:(storeId,input,options)=>this.request('POST',hybridPath(storeId,'/graph/walk'),input,options),
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
this.protect = {
|
|
223
|
+
backups: {
|
|
224
|
+
list: () => this.request('GET', this.orgPath('/protect/backups')),
|
|
225
|
+
create: (data, options) => this.request('POST', this.orgPath('/protect/backups'), typeof data === 'string' ? { name: data } : data, options),
|
|
226
|
+
get: backupId => this.request('GET', this.orgPath('/protect/backups/' + segment(backupId))),
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
this.protect.resources={
|
|
230
|
+
status:resourceId=>this.invokeService('protection.status',{resourceId}),
|
|
231
|
+
schedule:{get:resourceId=>this.invokeService('protection.schedule.get',{resourceId}),set:(resourceId,input,options)=>this.invokeService('protection.schedule.set',{...input,resourceId},options)},
|
|
232
|
+
alerts:resourceId=>this.invokeService('protection.alerts.list',{resourceId}),
|
|
233
|
+
backups:{
|
|
234
|
+
list:resourceId=>this.invokeService('protection.backups.list',{resourceId}),
|
|
235
|
+
get:(resourceId,pointId)=>this.invokeService('protection.backups.get',{resourceId,pointId}),
|
|
236
|
+
create:(resourceId,input={},options)=>this.invokeService('protection.backups.create',{...input,resourceId},options),
|
|
237
|
+
},
|
|
238
|
+
restore:{
|
|
239
|
+
plan:(resourceId,input,options)=>this.invokeService('protection.restore.plan',{...input,resourceId},options),
|
|
240
|
+
apply:(resourceId,input,options)=>this.invokeService('protection.restore.apply',{...input,resourceId},options),
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
const resilientPath=(id,operation)=>this.orgPath('/databases/'+segment(id)+'/resilience/'+operation);
|
|
244
|
+
this.databases={resilience:{
|
|
245
|
+
status:id=>this.request('GET',resilientPath(id,'status')),
|
|
246
|
+
plan:(id,options)=>this.request('POST',resilientPath(id,'plan'),{},options),
|
|
247
|
+
initialize:(id,options)=>this.request('POST',resilientPath(id,'initialize'),{},options),
|
|
248
|
+
backup:(id,options)=>this.request('POST',resilientPath(id,'backup'),{},options),
|
|
249
|
+
archive:(id,input={},options)=>this.request('POST',resilientPath(id,'archive'),input,options),
|
|
250
|
+
planRestore:(id,options)=>this.request('POST',resilientPath(id,'restore/plan'),{},options),
|
|
251
|
+
restore:(id,planId,confirmationToken,options)=>this.request('POST',resilientPath(id,'restore/apply'),{planId,confirmationToken},options),
|
|
252
|
+
}};
|
|
253
|
+
const collectionPath=(id,collection,suffix)=>dataPath('databases',id,'/collections/'+segment(collection)+suffix);
|
|
254
|
+
Object.assign(this.databases,{
|
|
255
|
+
query:(id,collection,input={},options)=>this.request('POST',collectionPath(id,collection,'/query'),input,options),
|
|
256
|
+
list:(id,collection)=>this.request('GET',collectionPath(id,collection,'/documents')),
|
|
257
|
+
get:(id,collection,documentId)=>this.request('GET',collectionPath(id,collection,'/documents/'+segment(documentId))),
|
|
258
|
+
insert:(id,collection,input,options)=>this.request('POST',collectionPath(id,collection,'/documents'),input,options),
|
|
259
|
+
});
|
|
260
|
+
this.auth={
|
|
261
|
+
authority:(options)=>this.request('GET','/v1/auth/authority',undefined,{...options,authenticated:false,noStore:true}),
|
|
262
|
+
login:(input={},options)=>this.request('POST','/v1/auth/device',{orgId:this.orgId,...input},options),
|
|
263
|
+
poll:(deviceCode,options)=>this.request('POST','/v1/auth/device/token',{deviceCode},options),
|
|
264
|
+
approve:(input,options)=>this.request('POST','/v1/auth/device/approve',input,options),
|
|
265
|
+
logout:(options)=>this.request('POST','/v1/auth/logout',{},options),
|
|
266
|
+
};
|
|
267
|
+
this.apps={invoke:(action,input={},options)=>this.invokeApps(action,input,options),list:()=>this.request('GET',this.orgPath('/applications')),create:(input,options)=>this.request('POST',this.orgPath('/applications'),input,options),environments:{list:app=>this.request('GET',this.orgPath('/apps/'+segment(app)+'/environments')),create:(app,input,options)=>this.request('POST',this.orgPath('/apps/'+segment(app)+'/environments'),input,options)}};
|
|
268
|
+
// Real named methods are generated from the registry, not merely advertised descriptors.
|
|
269
|
+
for(const operation of APPS_OPERATIONS.filter(op=>op.availability.sdk&&op.sdk.startsWith('apps.'))){
|
|
270
|
+
const names=operation.sdk.split('.').slice(1);let target=this.apps;
|
|
271
|
+
for(const name of names.slice(0,-1))target=target[name]??=( {} );
|
|
272
|
+
target[names.at(-1)]=(input={},options)=>this.invokeApps(operation.id,input,options);
|
|
273
|
+
}
|
|
274
|
+
this.apps.sources??={};
|
|
275
|
+
const gitSourcePath=({orgId=this.orgId,app,env})=>'/v1/orgs/'+segment(orgId)+'/apps/'+segment(app)+'/environments/'+segment(env)+'/git-source';
|
|
276
|
+
this.apps.sources.github={
|
|
277
|
+
list:(scope,options)=>this.request('GET',gitSourcePath(scope),undefined,options),
|
|
278
|
+
import:({repositoryId,branch,commit,...scope},options)=>this.request('POST',gitSourcePath(scope),{repositoryId,branch,...(commit?{commit}:{})},{timeoutMs:100_000,...options})
|
|
279
|
+
};
|
|
280
|
+
this.apps.sources.uploads=Object.fromEntries(['create','status','chunk','finalize','cancel'].map(action=>[action,(input={},options)=>this.invokeService('source.uploads.'+action,input,options)]));
|
|
281
|
+
this.apps.retention={
|
|
282
|
+
capabilities:(input,options)=>this.invokeService('retention.capabilities',input,options),
|
|
283
|
+
plan:(input,options)=>this.invokeService('retention.plan',input,options),
|
|
284
|
+
get:(input,options)=>this.invokeService('retention.get',input,options),
|
|
285
|
+
apply:(input,options)=>this.invokeService('retention.apply',input,options),
|
|
286
|
+
pins:{get:(input,options)=>this.invokeService('retention.pins.get',input,options),set:(input,options)=>this.invokeService('retention.pins.set',input,options)},
|
|
287
|
+
retirements:(input,options)=>this.invokeService('retention.retirements',input,options),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async invokeApps(action, input={}, options={}) {
|
|
292
|
+
const operation=APPS_OPERATIONS.find(op=>op.id===action);
|
|
293
|
+
if(!operation?.availability.sdk)throw new KineDropError('Unknown Apps action.',{code:'UNKNOWN_ACTION'});
|
|
294
|
+
const data={...(operation.input.properties.orgId?{orgId:this.orgId}:{}),...input};
|
|
295
|
+
for(const name of operation.input.required??[])if(data[name]===undefined||data[name]===null||data[name]==='')throw new KineDropError(name+' is required.',{code:'INVALID_ARGUMENTS',status:400});
|
|
296
|
+
const pathNames=[...operation.http.path.matchAll(/\{([^}]+)\}/g)].map(m=>m[1]);
|
|
297
|
+
let path=operation.http.path.replace(/\{([^}]+)\}/g,(_,name)=>segment(data[name]));
|
|
298
|
+
const payload=Object.fromEntries(Object.entries(data).filter(([name])=>!pathNames.includes(name)));
|
|
299
|
+
if(operation.http.method==='GET'){
|
|
300
|
+
const query=new URLSearchParams();for(const [name,value]of Object.entries(payload))if(value!==undefined)query.set(name,String(value));
|
|
301
|
+
if(query.size)path+='?'+query;
|
|
302
|
+
return this.request('GET',path,undefined,options);
|
|
303
|
+
}
|
|
304
|
+
return this.request(operation.http.method,path,payload,{...(data.idempotencyKey?{idempotencyKey:data.idempotencyKey}:{}),...options});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async invokeService(action,input={},options={}){
|
|
308
|
+
const operation=SERVICE_OPERATIONS.find(op=>op.id===action);
|
|
309
|
+
if(!operation?.availability.sdk)throw new KineDropError('Unknown service action.',{code:'UNKNOWN_ACTION',status:404});
|
|
310
|
+
if(options.dryRun)throw new KineDropError('This service action has no dry-run contract. Use its explicit review action where available.',{code:'DRY_RUN_UNSUPPORTED',status:422});
|
|
311
|
+
if(options.idempotencyKey!==undefined&&!operation.idempotency)throw new KineDropError('This service action does not accept HTTP idempotency keys.',{code:'IDEMPOTENCY_UNSUPPORTED',status:400});
|
|
312
|
+
const data=Object.fromEntries(Object.entries({...(operation.input.properties.orgId?{orgId:this.orgId}:{}),...input}).filter(([,value])=>value!==undefined));
|
|
313
|
+
try{validateInput(data,operation.input);}catch(error){throw new KineDropError(error.message,{code:error.code??'INVALID_ARGUMENTS',status:422});}
|
|
314
|
+
const pathNames=[...operation.http.path.matchAll(/\{([^}]+)\}/g)].map(m=>m[1]);
|
|
315
|
+
let path=operation.http.path.replace(/\{([^}]+)\}/g,(_,name)=>segment(data[name]));
|
|
316
|
+
const payload=Object.fromEntries(Object.entries(data).filter(([name])=>!pathNames.includes(name)));
|
|
317
|
+
if(operation.http.method==='GET'){
|
|
318
|
+
const query=new URLSearchParams();for(const [name,value]of Object.entries(payload))query.set(name,String(value));
|
|
319
|
+
if(query.size)path+='?'+query;
|
|
320
|
+
return this.request('GET',path,undefined,options);
|
|
321
|
+
}
|
|
322
|
+
return this.request(operation.http.method,path,payload,options);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async invokePlacement(action,input={},options={}){
|
|
326
|
+
const operation=PLACEMENT_OPERATIONS.find(op=>op.id===action);
|
|
327
|
+
if(!operation?.availability.sdk)throw new KineDropError('Unknown placement action.',{code:'UNKNOWN_ACTION',status:404});
|
|
328
|
+
if(options.dryRun)throw new KineDropError('Placement actions require their explicit observe/propose or reviewed operator contract.',{code:'DRY_RUN_UNSUPPORTED',status:422});
|
|
329
|
+
if(options.idempotencyKey!==undefined)throw new KineDropError('Placement actions do not accept HTTP replay keys; registration uses its JSON body idempotencyKey.',{code:'IDEMPOTENCY_UNSUPPORTED',status:400});
|
|
330
|
+
// A realm is not an organization. Never infer either selector from orgId.
|
|
331
|
+
if(!input||typeof input!=='object'||Array.isArray(input))throw new KineDropError('Placement input must be an object.',{code:'INVALID_ARGUMENTS',status:422});
|
|
332
|
+
const data=Object.fromEntries(Object.entries(input).filter(([,value])=>value!==undefined));
|
|
333
|
+
try{validateInput(data,operation.input);}catch(error){throw new KineDropError(error.message,{code:error.code??'INVALID_ARGUMENTS',status:422});}
|
|
334
|
+
const pathNames=[...operation.http.path.matchAll(/\{([^}]+)\}/g)].map(match=>match[1]);
|
|
335
|
+
let path=operation.http.path.replace(/\{([^}]+)\}/g,(_,name)=>segment(data[name]));
|
|
336
|
+
const payload=Object.fromEntries(Object.entries(data).filter(([name])=>!pathNames.includes(name)));
|
|
337
|
+
if(operation.http.method==='GET'){
|
|
338
|
+
const query=new URLSearchParams();for(const [name,value]of Object.entries(payload))query.set(name,String(value));
|
|
339
|
+
if(query.size)path+='?'+query;
|
|
340
|
+
return this.request('GET',path,undefined,{...options,noStore:true});
|
|
341
|
+
}
|
|
342
|
+
return this.request(operation.http.method,path,payload,{...options,noStore:true});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
orgPath(suffix = '') {
|
|
346
|
+
if (!this.orgId) throw new KineDropError('Select an organization with orgId or KINEDROP_ORG.', { code: 'ORG_REQUIRED' });
|
|
347
|
+
return '/v1/orgs/' + segment(this.orgId) + suffix;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
catalog() { return this.request('GET', '/v1/catalog'); }
|
|
351
|
+
doctor() { return this.request('GET', '/health', undefined, {authenticated:false}); }
|
|
352
|
+
runtime() { return this.request('GET', '/v1/runtime'); }
|
|
353
|
+
capabilities() { return this.request('GET',this.orgPath('/capabilities')); }
|
|
354
|
+
audit({limit=100}={}) { return this.request('GET',this.orgPath('/audit')+'?limit='+encodeURIComponent(limit)); }
|
|
355
|
+
usage() { return this.request('GET',this.orgPath('/usage')); }
|
|
356
|
+
async diagnostics() {
|
|
357
|
+
if(this.orgId){try{
|
|
358
|
+
const result=await this.request('GET',this.orgPath('/diagnostics'));
|
|
359
|
+
if(!result||result.scope!==this.orgId||!result.checks||typeof result.checks!=='object'||Array.isArray(result.checks)||!Object.keys(result.checks).length||Object.values(result.checks).some(check=>!check||typeof check.ok!=='boolean'))throw new KineDropError('Server returned invalid scoped diagnostics.',{code:'INVALID_RESPONSE',status:502});
|
|
360
|
+
return result;
|
|
361
|
+
}catch(error){if(error.status!==404)throw error;}}
|
|
362
|
+
const checks={health:()=>this.doctor(),runtime:()=>this.runtime(),...(this.orgId?{capabilities:()=>this.capabilities()}: {})};
|
|
363
|
+
return {scope:this.orgId??null,checks:Object.fromEntries(await Promise.all(Object.entries(checks).map(async([name,run])=>{try{return[name,{ok:true,result:await run()}];}catch(error){return[name,{ok:false,error:{code:error.code??'CHECK_FAILED',message:error.message}}];}})))};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async request(method, path, body, { idempotencyKey, dryRun = false, signal, surface, noStore = false, authenticated = true, timeoutMs = this.timeoutMs } = {}) {
|
|
367
|
+
method = String(method).toUpperCase();
|
|
368
|
+
if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) throw new TypeError('Unsupported HTTP method.');
|
|
369
|
+
if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//') || path.includes('\\') || /[\r\n#]/.test(path)) {
|
|
370
|
+
throw new TypeError('Use an absolute API path on the configured KineDrop server.');
|
|
371
|
+
}
|
|
372
|
+
const url = new URL(this.baseUrl + path);
|
|
373
|
+
if (url.origin !== new URL(this.baseUrl).origin) throw new TypeError('Cross-origin API requests are forbidden.');
|
|
374
|
+
const mutating = !isReadOnlyRequest(method, url.pathname);
|
|
375
|
+
if (this.readOnly && mutating) throw new KineDropError('This client is read-only.', { code: 'READ_ONLY', status: 403 });
|
|
376
|
+
if ((method === 'GET' || method === 'HEAD') && body !== undefined) throw new TypeError('GET/HEAD requests cannot contain a body.');
|
|
377
|
+
if (dryRun) url.searchParams.set('dryRun', 'true');
|
|
378
|
+
const headers = { Accept: 'application/json' };
|
|
379
|
+
if(surface==='mcp')headers['X-KineDrop-Surface']='mcp';
|
|
380
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
381
|
+
if (idempotencyKey !== undefined) {
|
|
382
|
+
if (typeof idempotencyKey !== 'string' || !/^[A-Za-z0-9_.-]{8,128}$/.test(idempotencyKey)) throw new TypeError('Idempotency-Key must contain 8-128 letters, digits, dots, underscores or hyphens.');
|
|
383
|
+
headers['Idempotency-Key'] = idempotencyKey;
|
|
384
|
+
}
|
|
385
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) throw new TypeError('timeoutMs must be a whole number between 1 and 300000.');
|
|
386
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
387
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
388
|
+
const deadline=performance.now()+timeoutMs;
|
|
389
|
+
const transportError=()=>{const timedOut=timeout.aborted||performance.now()>=deadline;return new KineDropError(timedOut?'KineDrop request timed out.':signal?.aborted?'KineDrop request was cancelled.':'Unable to reach the KineDrop API.',{code:timedOut?'TIMEOUT':signal?.aborted?'CANCELLED':'NETWORK_ERROR'});};
|
|
390
|
+
const assertActive=()=>{if(combinedSignal.aborted||performance.now()>=deadline)throw transportError();};
|
|
391
|
+
let response,text,onAbort;
|
|
392
|
+
try {
|
|
393
|
+
// Redirects could forward a bearer credential; API redirects are never followed.
|
|
394
|
+
const stopped=new Promise((_,reject)=>{onAbort=()=>reject(transportError());combinedSignal.addEventListener('abort',onAbort,{once:true});if(combinedSignal.aborted)onAbort();});
|
|
395
|
+
text=await Promise.race([Promise.resolve().then(async()=>{
|
|
396
|
+
if (authenticated) {
|
|
397
|
+
const token = this.token || await this.tokenProvider?.();
|
|
398
|
+
if (token?.startsWith('krx_')) throw Object.assign(new Error('A long-lived Keyrox credential cannot be sent to KineDrop.'), {code:'KEYROX_CREDENTIAL_INVALID'});
|
|
399
|
+
if (token) headers.Authorization = 'Bearer ' + token;
|
|
400
|
+
}
|
|
401
|
+
assertActive();response=await this.fetch(url,{method,headers,body:body===undefined?undefined:JSON.stringify(body),signal:combinedSignal,redirect:'error',...(noStore?{cache:'no-store'}:{})});try{assertActive();}catch(error){discardResponse(response);throw error;}
|
|
402
|
+
return boundedResponseText(response,{maxBytes:this.maxResponseBytes,signal:combinedSignal,assertActive});
|
|
403
|
+
}),stopped]);assertActive();
|
|
404
|
+
} catch (error) {
|
|
405
|
+
if(error?.[RESPONSE_LIMIT_ERROR])throw error;
|
|
406
|
+
if(typeof error?.code==='string'&&error.code.startsWith('KEYROX_'))throw error;
|
|
407
|
+
throw transportError();
|
|
408
|
+
}finally{if(onAbort)combinedSignal.removeEventListener('abort',onAbort);}
|
|
409
|
+
let data;
|
|
410
|
+
try { data = text ? JSON.parse(text) : undefined; }
|
|
411
|
+
catch {
|
|
412
|
+
throw new KineDropError('KineDrop returned a non-JSON response.', { status: response.status, code: 'INVALID_RESPONSE', correlationId: response.headers.get('x-correlation-id') });
|
|
413
|
+
}
|
|
414
|
+
assertActive();
|
|
415
|
+
if (!response.ok) {
|
|
416
|
+
const error = data?.error ?? data;
|
|
417
|
+
throw new KineDropError(typeof error?.message === 'string' ? error.message : 'KineDrop request failed.', {
|
|
418
|
+
status: response.status,
|
|
419
|
+
code: typeof error?.code === 'string' ? error.code : 'HTTP_' + response.status,
|
|
420
|
+
details: error?.details,
|
|
421
|
+
correlationId: data?.correlationId ?? response.headers.get('x-correlation-id'),
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
return data;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export const createClient = options => new KineDropClient(options);
|
|
429
|
+
export default KineDropClient;
|
package/keyrox.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const exchangeGrant = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
|
2
|
+
const longLivedToken = 'urn:x12i:keyrox:params:oauth:token-type:long-lived';
|
|
3
|
+
const tokenPattern = /^[A-Za-z0-9._~+/=-]{16,8192}$/;
|
|
4
|
+
const fail = (code, message, status = 0) => Object.assign(new Error(message), { code, status });
|
|
5
|
+
|
|
6
|
+
export function keyroxIssuer(value) {
|
|
7
|
+
let url;
|
|
8
|
+
try { url = new URL(value); }
|
|
9
|
+
catch { throw fail('KEYROX_CONFIGURATION_INVALID', 'A valid Keyrox issuer is required.'); }
|
|
10
|
+
const loopback = url.hostname === 'localhost' || url.hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(url.hostname);
|
|
11
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
|
12
|
+
throw fail('KEYROX_CONFIGURATION_INVALID', 'Use the HTTPS origin of Keyrox, or an HTTP loopback origin.');
|
|
13
|
+
}
|
|
14
|
+
return url.origin;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function keyroxRequest(issuer, path, body, { fetchImpl = globalThis.fetch, signal, timeoutMs = 15000 } = {}) {
|
|
18
|
+
if (!['/oauth/register', '/oauth/device', '/oauth/token', '/oauth/revoke'].includes(path)) throw fail('KEYROX_CONFIGURATION_INVALID', 'Unsupported Keyrox OAuth path.');
|
|
19
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 60000) throw fail('KEYROX_CONFIGURATION_INVALID', 'Keyrox request timeout must be 100 to 60000 milliseconds.');
|
|
20
|
+
const url = new URL(path, keyroxIssuer(issuer));
|
|
21
|
+
const requestSignal = AbortSignal.timeout(timeoutMs);
|
|
22
|
+
const combinedSignal = signal ? AbortSignal.any([signal, requestSignal]) : requestSignal;
|
|
23
|
+
const form = body instanceof URLSearchParams;
|
|
24
|
+
let result;
|
|
25
|
+
let response;
|
|
26
|
+
try {
|
|
27
|
+
response = await fetchImpl(url, {
|
|
28
|
+
method: 'POST', redirect: 'error', cache: 'no-store', credentials: 'omit', signal: combinedSignal,
|
|
29
|
+
headers: { accept: 'application/json', 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json' },
|
|
30
|
+
body: form ? body : JSON.stringify(body),
|
|
31
|
+
});
|
|
32
|
+
const reader = response.body?.getReader();
|
|
33
|
+
if (!reader) throw new Error();
|
|
34
|
+
try {
|
|
35
|
+
const decoder = new TextDecoder();
|
|
36
|
+
const chunks = [];
|
|
37
|
+
let size = 0;
|
|
38
|
+
for (;;) {
|
|
39
|
+
const { done, value } = await reader.read();
|
|
40
|
+
if (done) break;
|
|
41
|
+
size += value.byteLength;
|
|
42
|
+
if (size > 65536) throw new Error();
|
|
43
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
44
|
+
}
|
|
45
|
+
chunks.push(decoder.decode());
|
|
46
|
+
result = JSON.parse(chunks.join(''));
|
|
47
|
+
} catch {
|
|
48
|
+
void reader.cancel().catch(() => {});
|
|
49
|
+
throw fail('KEYROX_RESPONSE_INVALID', 'Keyrox returned an invalid OAuth response.', response.status);
|
|
50
|
+
} finally { reader.releaseLock(); }
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (typeof error?.code === 'string' && error.code.startsWith('KEYROX_')) throw error;
|
|
53
|
+
throw fail('KEYROX_UNAVAILABLE', 'Could not reach the configured Keyrox issuer.');
|
|
54
|
+
}
|
|
55
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)) {
|
|
56
|
+
throw fail('KEYROX_RESPONSE_INVALID', 'Keyrox returned an invalid OAuth response.', response.status);
|
|
57
|
+
}
|
|
58
|
+
return { status: response.status, ok: response.ok, data: result };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function createKeyroxTokenProvider({ issuer, audience, credential, authority, executionId, fetchImpl, timeoutMs } = {}) {
|
|
62
|
+
if (typeof credential !== 'function' && (typeof credential !== 'string' || !credential.startsWith('krx_') || !tokenPattern.test(credential))) {
|
|
63
|
+
throw fail('KEYROX_CREDENTIAL_INVALID', 'A Keyrox long-lived credential or credential supplier is required.');
|
|
64
|
+
}
|
|
65
|
+
const pinnedIssuer = keyroxIssuer(issuer);
|
|
66
|
+
if (!audience && typeof authority !== 'function') throw fail('KEYROX_CONFIGURATION_INVALID', 'Provide the KineDrop audience or an authority discovery function.');
|
|
67
|
+
if (audience !== undefined && (typeof audience !== 'string' || !audience || /\s/.test(audience))) throw fail('KEYROX_CONFIGURATION_INVALID', 'Provide the audience registered for KineDrop.');
|
|
68
|
+
if (executionId !== undefined && (typeof executionId !== 'string' || !executionId || executionId.length > 256)) throw fail('KEYROX_CONFIGURATION_INVALID', 'Keyrox execution ID must be a non-empty string of at most 256 characters.');
|
|
69
|
+
let cached;
|
|
70
|
+
let pending;
|
|
71
|
+
async function exchange() {
|
|
72
|
+
const current = await authority?.();
|
|
73
|
+
if (current && current.provider !== 'keyrox') throw fail('KEYROX_NOT_CONFIGURED', 'The KineDrop server has not configured Keyrox.');
|
|
74
|
+
const serverIssuer = current?.issuer === undefined ? undefined : keyroxIssuer(current.issuer);
|
|
75
|
+
if (serverIssuer && pinnedIssuer !== serverIssuer) throw fail('KEYROX_CONFIGURATION_INVALID', 'The Keyrox issuer differs from the configured KineDrop server.');
|
|
76
|
+
if (audience && current?.audience && audience !== current.audience) throw fail('KEYROX_CONFIGURATION_INVALID', 'The Keyrox audience differs from the configured KineDrop server.');
|
|
77
|
+
const effectiveAudience = audience ?? current?.audience;
|
|
78
|
+
if (typeof effectiveAudience !== 'string' || !effectiveAudience || /\s/.test(effectiveAudience)) throw fail('KEYROX_CONFIGURATION_INVALID', 'The KineDrop audience is missing.');
|
|
79
|
+
let subject;
|
|
80
|
+
try { subject = typeof credential === 'function' ? await credential() : credential; }
|
|
81
|
+
catch { throw fail('KEYROX_CREDENTIAL_UNAVAILABLE', 'The Keyrox credential supplier could not provide a credential.'); }
|
|
82
|
+
if (typeof subject !== 'string' || !subject.startsWith('krx_') || !tokenPattern.test(subject)) throw fail('KEYROX_CREDENTIAL_INVALID', 'The Keyrox credential supplier returned an invalid credential.');
|
|
83
|
+
const form = new URLSearchParams({ grant_type: exchangeGrant, subject_token: subject, subject_token_type: longLivedToken, audience: effectiveAudience });
|
|
84
|
+
if (executionId !== undefined) form.set('execution_id', executionId);
|
|
85
|
+
const { ok, status, data } = await keyroxRequest(pinnedIssuer, '/oauth/token', form, { fetchImpl, timeoutMs });
|
|
86
|
+
if (!ok) throw fail('KEYROX_EXCHANGE_REJECTED', 'Keyrox rejected the KineDrop credential exchange.', status);
|
|
87
|
+
if (typeof data.access_token !== 'string' || data.access_token.length > 8192 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(data.access_token) || typeof data.token_type !== 'string' || data.token_type.toLowerCase() !== 'bearer' || !Number.isSafeInteger(data.expires_in) || data.expires_in < 1 || data.expires_in > 3600) {
|
|
88
|
+
throw fail('KEYROX_RESPONSE_INVALID', 'Keyrox did not return a short-lived KineDrop access token.');
|
|
89
|
+
}
|
|
90
|
+
cached = { token: data.access_token, refreshAt: Date.now() + data.expires_in * 1000 - Math.min(30000, data.expires_in * 250) };
|
|
91
|
+
return cached.token;
|
|
92
|
+
}
|
|
93
|
+
return async function provideToken() {
|
|
94
|
+
if (cached?.refreshAt > Date.now()) return cached.token;
|
|
95
|
+
if (!pending) pending = exchange().finally(() => { pending = undefined; });
|
|
96
|
+
return pending;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function keyroxClientOptionsFromEnv(env) {
|
|
101
|
+
const credential = env.KINEDROP_KEYROX_CREDENTIAL;
|
|
102
|
+
if (credential === undefined) return undefined;
|
|
103
|
+
if (!env.KINEDROP_KEYROX_ISSUER) throw fail('KEYROX_CONFIGURATION_INVALID', 'Set KINEDROP_KEYROX_ISSUER to the trusted Keyrox HTTPS origin.');
|
|
104
|
+
if (env.KINEDROP_TOKEN !== undefined) throw fail('KEYROX_CONFIGURATION_INVALID', 'Supply one of KINEDROP_TOKEN or KINEDROP_KEYROX_CREDENTIAL.');
|
|
105
|
+
return { credential, issuer: env.KINEDROP_KEYROX_ISSUER, audience: env.KINEDROP_KEYROX_AUDIENCE, executionId: env.KINEDROP_KEYROX_EXECUTION_ID };
|
|
106
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {validateInput} from './validate.mjs';
|
|
2
|
+
|
|
3
|
+
const object=(properties,required=[])=>({type:'object',properties,required,additionalProperties:false});
|
|
4
|
+
const text={type:'string',minLength:1,maxLength:1024};
|
|
5
|
+
const metadata={type:'object',additionalProperties:{type:'string'}};
|
|
6
|
+
const lifetime={type:'integer',minimum:60,maximum:86400};
|
|
7
|
+
const issue=object({protocol:{enum:['s3','blob']},permissions:{type:'array',minItems:1,maxItems:5,uniqueItems:true,items:{enum:['read','write','delete','list','containers']}},containers:{type:'array',minItems:1,maxItems:30,items:text},prefix:text,ttlSeconds:lifetime},['protocol','permissions']);
|
|
8
|
+
const page=object({prefix:{type:'string',maxLength:1024},cursor:{type:'string',minLength:1,maxLength:4096},limit:{type:'integer',minimum:1,maximum:5000}});
|
|
9
|
+
const selectors=object({...page.properties,delimiter:{type:'string',minLength:1,maxLength:64}});
|
|
10
|
+
|
|
11
|
+
/** Explicit management routes. Legacy resource storage data methods remain separate. */
|
|
12
|
+
export function objectStorageApi(client,segment){
|
|
13
|
+
const root='/object-storage',account=id=>root+'/accounts/'+segment(id),container=(id,name)=>account(id)+'/containers/'+segment(name);
|
|
14
|
+
const send=(method,path,input,options,schema)=>{if(schema)validateInput(input,schema);if(options?.dryRun||options?.idempotencyKey)throw Object.assign(new Error('Object storage management does not support dry run or response replay keys.'),{code:'INVALID_ARGUMENTS',status:422});return client.request(method,client.orgPath(path),input,{...options,noStore:true});};
|
|
15
|
+
const listing=(path,input,options,schema)=>{validateInput(input,schema);const query=new URLSearchParams();for(const [key,value]of Object.entries(input))query.set(key,String(value));return send('GET',path+(query.size?'?'+query:''),undefined,options);};
|
|
16
|
+
return {
|
|
17
|
+
capabilities:options=>send('GET',root+'/capabilities',undefined,options),
|
|
18
|
+
accounts:{
|
|
19
|
+
list:options=>send('GET',root+'/accounts',undefined,options),
|
|
20
|
+
create:(input,options)=>send('POST',root+'/accounts',input,options,object({alias:{type:'string',pattern:'^[a-z0-9]{3,24}$'},quota:{type:'object',additionalProperties:true}},['alias'])),
|
|
21
|
+
get:(id,options)=>send('GET',account(id),undefined,options),
|
|
22
|
+
},
|
|
23
|
+
usage:(id,options)=>send('GET',account(id)+'/usage',undefined,options),
|
|
24
|
+
containers:{
|
|
25
|
+
list:(id,input={},options)=>listing(account(id)+'/containers',input,options,page),
|
|
26
|
+
create:(id,input,options)=>send('POST',account(id)+'/containers',input,options,object({container:text,metadata},['container'])),
|
|
27
|
+
get:(id,name,options)=>send('GET',container(id,name),undefined,options),
|
|
28
|
+
},
|
|
29
|
+
objects:{list:(id,name,input={},options)=>listing(container(id,name)+'/objects',input,options,selectors)},
|
|
30
|
+
credentials:{
|
|
31
|
+
list:(id,options)=>send('GET',account(id)+'/credentials',undefined,options),
|
|
32
|
+
issue:(id,input,options)=>send('POST',account(id)+'/credentials',input,options,issue),
|
|
33
|
+
rotate:(id,credentialId,input={},options)=>send('POST',account(id)+'/credentials/'+segment(credentialId)+'/rotate',input,options,object({ttlSeconds:lifetime,overlapSeconds:{type:'integer',minimum:0,maximum:3600}})),
|
|
34
|
+
revoke:(id,credentialId,options)=>send('DELETE',account(id)+'/credentials/'+segment(credentialId),undefined,options),
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x12i/kinedrop",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "KineDrop control-plane client for Node.js 24 and modern browsers",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": { "types": "./index.d.ts", "import": "./index.mjs" }
|
|
8
|
+
},
|
|
9
|
+
"engines": { "node": ">=24.0.0" },
|
|
10
|
+
"files": ["index.mjs", "index.d.ts", "apps-operations.mjs", "service-operations.mjs", "placement-operations.mjs", "object-storage.mjs", "validate.mjs", "keyrox.mjs"]
|
|
11
|
+
}
|