@x12i/kinedrop-cli 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,58 @@
1
+ import {open,lstat} from 'node:fs/promises';
2
+ import {constants} from 'node:fs';
3
+ import {resolve} from 'node:path';
4
+ import {spawn} from 'node:child_process';
5
+
6
+ export const STORAGE_CREDENTIAL_ENTROPY='KineDrop object-storage credentials v1';
7
+ export const STORAGE_CREDENTIAL_POWERSHELL='C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
8
+ export const STORAGE_CREDENTIAL_PROTECT_COMMAND=`$ErrorActionPreference='Stop';try{Add-Type -AssemblyName System.Security;$s=[Console]::In.ReadToEnd();if($s.Length -gt 87384){throw 'bounded'};$p=[Convert]::FromBase64String($s);if($p.Length -gt 65536){throw 'bounded'};$e=[Text.Encoding]::UTF8.GetBytes('${STORAGE_CREDENTIAL_ENTROPY}');try{$c=[Security.Cryptography.ProtectedData]::Protect($p,$e,[Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Out.Write([Convert]::ToBase64String($c));}finally{if($null -ne $p){[Array]::Clear($p,0,$p.Length)}};exit 0}catch{exit 1}`;
9
+ const failure=()=>Object.assign(new Error('Credential output could not be saved securely. No credential has been printed; inspect the account credential inventory before retrying.'),{code:'STORAGE_CREDENTIAL_OUTPUT_FAILED'});
10
+ const invalid=()=>Object.assign(new Error('Choose a new explicit --credentials-file in an existing local directory. Existing files are never overwritten.'),{code:'INVALID_ARGUMENTS',status:422});
11
+
12
+ /** Fixed child, no credential arguments/environment, bounded private stdin and ciphertext stdout. */
13
+ export async function protectStorageCredentials(bytes,{spawnImpl=spawn,timeoutMs=10000}={}){
14
+ if(!(bytes instanceof Uint8Array)||bytes.length>65536||!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>30000)throw failure();
15
+ const input=Buffer.from(bytes).toString('base64');
16
+ return new Promise((resolveOutput,reject)=>{
17
+ let child,timer,settled=false,size=0,stderrBytes=0;const chunks=[],deadline=performance.now()+timeoutMs;
18
+ const finish=(error,value)=>{if(settled)return;settled=true;clearTimeout(timer);if(error){try{child?.kill();}catch{}reject(failure());}else resolveOutput(value);for(const chunk of chunks)chunk.fill(0);};
19
+ try{child=spawnImpl(STORAGE_CREDENTIAL_POWERSHELL,['-NoLogo','-NoProfile','-NonInteractive','-Command',STORAGE_CREDENTIAL_PROTECT_COMMAND],{windowsHide:true,shell:false,stdio:['pipe','pipe','pipe'],env:{SystemRoot:'C:\\Windows',WINDIR:'C:\\Windows',TEMP:process.env.TEMP??'C:\\Windows\\Temp',TMP:process.env.TMP??'C:\\Windows\\Temp'}});}catch{return finish(true);}
20
+ if(!child?.stdout?.on||!child?.stderr?.on||!child?.stdin?.end||!child?.on)return finish(true);
21
+ timer=setTimeout(()=>finish(true),timeoutMs);
22
+ child.on('error',()=>finish(true));child.stdin.on?.('error',()=>finish(true));
23
+ child.stdout.on('error',()=>finish(true));child.stderr.on('error',()=>finish(true));
24
+ child.stdout.on('data',chunk=>{if(settled)return;size+=chunk.length;if(size>131072)return finish(true);chunks.push(Buffer.from(chunk));});
25
+ child.stderr.on('data',chunk=>{if(settled)return;stderrBytes+=chunk.length;if(stderrBytes>1024)finish(true);});
26
+ child.on('close',code=>{if(settled)return;if(code!==0||stderrBytes||!size||performance.now()>=deadline)return finish(true);const text=Buffer.concat(chunks).toString('ascii');if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)||text.length<32||Buffer.from(text,'base64').toString('base64')!==text)return finish(true);finish(false,text);});
27
+ if(performance.now()>=deadline)return finish(true);try{child.stdin.end(input);}catch{finish(true);}
28
+ });
29
+ }
30
+
31
+ /** Reserve the destination before issue/rotation; output is DPAPI on Windows, verified 0600 on POSIX. */
32
+ export async function reserveCredentialOutput(file,{cwd=process.cwd(),platform=process.platform,protect=protectStorageCredentials}={}){
33
+ if(typeof file!=='string'||!file||file==='-'||/[\r\n\0]/.test(file))throw invalid();
34
+ const path=resolve(cwd,file);let handle,identity,closed=false;
35
+ if(process.platform==='win32'&&(!/^[A-Za-z]:[\\/]/.test(path)||path.slice(2).includes(':')))throw invalid();
36
+ try{handle=await open(path,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|(constants.O_NOFOLLOW??0),0o600);identity=await handle.stat();if(!identity.isFile()||platform!=='win32'&&(identity.mode&0o077)!==0)throw invalid();}catch{try{await handle?.close();}catch{}throw invalid();}
37
+ const same=async()=>{const actual=await lstat(path);return actual.isFile()&&!actual.isSymbolicLink()&&actual.ino===identity.ino&&actual.dev===identity.dev;};
38
+ // Cross-platform filesystems have no compare-and-unlink primitive. Preserve the
39
+ // reservation on failure rather than risk unlinking a concurrent replacement.
40
+ const abort=async()=>{if(!closed){closed=true;try{await handle.close();}catch{}}};
41
+ return {
42
+ async save(value){
43
+ let bytes;
44
+ try{
45
+ if(closed)throw failure();
46
+ bytes=Buffer.from(JSON.stringify(value));if(bytes.length>65536)throw failure();
47
+ const output=platform==='win32'?JSON.stringify({schemaVersion:1,protection:'windows-dpapi-current-user',entropy:STORAGE_CREDENTIAL_ENTROPY,ciphertextBase64:await protect(bytes)}):bytes;
48
+ if(!await same())throw failure();await handle.writeFile(output);await handle.sync();if(!await same())throw failure();await handle.close();closed=true;
49
+ return {saved:true,protection:platform==='win32'?'windows-dpapi-current-user':'posix-0600'};
50
+ }catch{await abort();throw failure();}finally{bytes?.fill(0);}
51
+ },abort,
52
+ };
53
+ }
54
+
55
+ export function storageCredentialMetadata(value){
56
+ const fields=['credentialId','orgId','accountId','protocol','permissions','containers','prefix','policyRevision','createdAt','expiresAt','revoked','revokedAt'];
57
+ return Object.fromEntries(fields.filter(key=>Object.hasOwn(value??{},key)).map(key=>[key,value[key]]));
58
+ }
package/extended.mjs ADDED
@@ -0,0 +1,357 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import {resolve} from 'node:path';
3
+ import {captureAndUploadRepository} from './source.mjs';
4
+ import {reserveCredentialOutput,storageCredentialMetadata} from './credential-output.mjs';
5
+
6
+ export const EXTENDED_HELP=`
7
+ Service operations:
8
+ login -- <kd-command> Authorize and run a command with an in-memory scoped grant
9
+ logout Revoke the current scoped grant
10
+ capabilities | audit | usage Inspect authorized service evidence
11
+ projects list | create <name> Manage organization projects
12
+ nodes list | show <id> Inspect operator-authorized fleet nodes
13
+ nodes rebalance-plan <id> <json-file> Review an operator allocation change
14
+ nodes rebalance <id> <json-file> Apply the reviewed confirmation
15
+ placement capabilities Inspect configured Observe/Propose metadata
16
+ placement observations list <realm> <environment> [query-json-file]
17
+ placement observations record <realm> <environment> <json-file|->
18
+ placement propose <realm> <environment> <json-file|->
19
+ onboarding list <realm> <environment> [query-json-file]
20
+ onboarding show <realm> <environment> <intent>
21
+ onboarding register <realm> <environment> <json-file|->
22
+ onboarding bind|resume <realm> <environment> <intent> <json-file|->
23
+ onboarding reconcile|release <realm> <environment> <intent>
24
+ onboarding expire <realm> <environment>
25
+ tenants list | show <id> | create <json-file>
26
+ tenants rotate|plan-offboard <id> | offboard <id> <json-file>
27
+ tenants access list <tenant>
28
+ tenants access grant <tenant> <json-file>
29
+ tenants access plan-revoke <tenant> <access>
30
+ tenants access revoke <tenant> <access> <json-file>
31
+ kafka topics create <tenant> <topic> [json-file]
32
+ kafka topics list <tenant> | show <tenant> <topic>
33
+ kafka topics plan-delete <tenant> <topic>
34
+ kafka topics delete <tenant> <topic> <json-file>
35
+ protect resource-status <resource>
36
+ protect points list <resource> | show <resource> <point>
37
+ protect backup <resource> [json-file]
38
+ protect restore-plan|restore <resource> <json-file> Human-only review/confirmation
39
+ protect schedule show|set <resource> [json-file] Human-approved backup policy
40
+ protect alerts <resource> Read bounded protection alerts
41
+ operations list | show <id> Inspect shared operations
42
+ resources get|manifest <service> <id> Inspect a resource definition
43
+ api <METHOD> </path> [json-file] Call the configured API; normal guards apply
44
+ cache get|set|delete <id> <key> [json-file]
45
+ storage list <id> | get|put|delete <id> <key> [json-file]
46
+ object-storage capabilities
47
+ object-storage accounts list|show|create [account|json-file]
48
+ object-storage usage <account>
49
+ object-storage containers list <account> [query-json-file]
50
+ object-storage containers show <account> <container> | create <account> <json-file>
51
+ object-storage objects list <account> <container> [query-json-file]
52
+ object-storage credentials list <account>
53
+ object-storage credentials issue <account> <json-file> --credentials-file <new-file>
54
+ object-storage credentials rotate <account> <credential> [json-file] --credentials-file <new-file>
55
+ object-storage credentials revoke <account> <credential>
56
+ messaging capabilities <id>
57
+ messaging peek|deadletters|receive <id> <queue> [json-file]
58
+ messaging send <id> <queue> <json-file>
59
+ messaging settle <id> <queue> <message> <action> <json-file>
60
+ sql query|create-table <id> <json-file>
61
+ mongo query|insert <id> <collection> <json-file>
62
+ search query|create-index|insert <id> <json-file>
63
+ analytics query|create-table|ingest <id> <json-file>
64
+
65
+ Apps (requires a configured Apps service and explicit app/environment):
66
+ apps list | create <name> Register application metadata
67
+ apps retention capabilities|pins|retirements <app>
68
+ apps retention plan|set-pins <app> <json-file>
69
+ apps retention get <app> <plan-id>
70
+ apps retention apply <app> <plan-id> <json-file> Human-reviewed bounded cleanup
71
+ source upload [directory] --app <name> [--upload-id <id>]
72
+ source status|cancel <upload-id> --app <name>
73
+ environments list <app> | create <app> <json-file>
74
+ plan | deploy [directory] --app <name> --env <name>
75
+ source git --app <name> --env <name> [--repository-id <id> --branch <branch>]
76
+ plan --app <name> --env <name> --repository-id <id> --branch <branch> [--answers-file <json>]
77
+ deploy --app <name> --env <name> --plan-id <id> --source-digest <digest> --commit <sha>
78
+ status|wait|explain|cancel|resume <operation>
79
+ answer|approve <operation> <json-file> Continue or review an operation
80
+ app | logs | releases --app <name> --env <name>
81
+ release|promote <release> --app <name> [--env <name>]
82
+ rollback --app <name> --env <name> [--to <release>]
83
+ env ls | set|secret <NAME> <json-file> --app <name> --env <name>
84
+
85
+ Additional options: --engine kafka|rabbitmq|local-sqlite --compatibility native|azure-service-bus
86
+ --app <name> --env <name> --source <source.json> --upload-id <id> --to <release> --project <id>
87
+ --scopes <comma-list> --principal agent|ci|user|operator --login-timeout <seconds>
88
+ JSON inputs may use '-' for stdin. Secret values are read only from files/stdin.
89
+ Object-storage credential delivery never prints keys: Windows uses CurrentUser DPAPI, POSIX verifies mode 0600.
90
+ Use an existing private directory and a new --credentials-file; dry run and replay keys are unsupported.
91
+ Placement realms and environments are explicit and independent of --org. Placement writes are human operator actions.
92
+ Registration replay keys belong in its JSON body; placement does not accept --idempotency-key or --dry-run.
93
+ Service mutations return accepted operation records; inspect operations for completion and provider outcomes.
94
+ Plan/deploy captures regular repository bytes without running hooks. Larger source uses resumable 512 KiB chunks.
95
+ Chunked source admits at most 500 MiB total, 100 MiB/file, and a 1 MiB manifest; MCP byte limits are unchanged.
96
+ Deploy waits for readiness or an actionable outcome; an accepted queued operation is never printed as deployed.
97
+ `;
98
+
99
+ const required=(v,label)=>{if(v===undefined||v===null||v==='')throw Object.assign(new Error(label+' is required.'),{code:'INVALID_ARGUMENTS'});return v;};
100
+ const segment=v=>encodeURIComponent(required(v,'identifier'));
101
+ const result=value=>({handled:true,result:value});
102
+ const outcomes={'deployed':0,'needs-input':10,'awaiting-approval':11,'failed-safe':12,'failed-partial':13,unknown:14,cancelled:15};
103
+ export function appsExit(value){
104
+ const op=value?.operation??value;
105
+ if(op?.status==='awaiting_input')return 10;
106
+ if(op?.status==='awaiting_approval')return 11;
107
+ if(op?.status==='cancelled')return 15;
108
+ if(op?.status==='succeeded')return 0;
109
+ return outcomes[op?.error?.outcome??op?.outcome]??14;
110
+ }
111
+
112
+ export async function runExtended({args,options,client,requestOptions,cwd,stdin,credentialOutput=reserveCredentialOutput}){
113
+ const [command,action,...rest]=args;
114
+ async function jsonFile(path){
115
+ required(path,'JSON file');let text;
116
+ if(path==='-'){const chunks=[];let size=0;try{for await(const chunk of stdin){size+=Buffer.byteLength(chunk);if(size>2*1024*1024)throw Object.assign(new Error('JSON stdin exceeds 2 MiB.'),{code:'INVALID_ARGUMENTS'});chunks.push(chunk);}}catch(error){if(error?.code==='INVALID_ARGUMENTS')throw error;throw Object.assign(new Error('JSON stdin could not be read.'),{code:'INVALID_ARGUMENTS'});}text=Buffer.concat(chunks.map(c=>Buffer.from(c))).toString('utf8');}
117
+ else {let bytes;try{bytes=await readFile(resolve(cwd,path));}catch{throw Object.assign(new Error('Input JSON file could not be read. Check its local path and permissions.'),{code:'INVALID_ARGUMENTS'});}if(bytes.length>2*1024*1024)throw Object.assign(new Error('JSON file exceeds 2 MiB.'),{code:'INVALID_ARGUMENTS'});text=bytes.toString('utf8');}
118
+ try{return JSON.parse(text);}catch{throw Object.assign(new Error('Input must be valid JSON.'),{code:'INVALID_ARGUMENTS'});}
119
+ }
120
+ if(command==='object-storage'){
121
+ if(requestOptions.dryRun||requestOptions.idempotencyKey)throw Object.assign(new Error('Object storage management does not support --dry-run or --idempotency-key.'),{code:'INVALID_ARGUMENTS'});
122
+ const api=client.objectStorage;
123
+ if(action==='capabilities'&&!rest.length)return result(await api.capabilities());
124
+ if(action==='usage'&&rest.length===1)return result(await api.usage(rest[0]));
125
+ const [verb,accountId,selector,file]=rest;
126
+ if(action==='accounts'){
127
+ if(verb==='list'&&rest.length===1)return result(await api.accounts.list());
128
+ if(verb==='show'&&rest.length===2)return result(await api.accounts.get(accountId));
129
+ if(verb==='create'&&rest.length===2)return result(await api.accounts.create(await jsonFile(accountId),requestOptions));
130
+ }
131
+ if(action==='containers'){
132
+ if(verb==='list'&&[2,3].includes(rest.length))return result(await api.containers.list(accountId,selector?await jsonFile(selector):{}));
133
+ if(verb==='show'&&rest.length===3)return result(await api.containers.get(accountId,selector));
134
+ if(verb==='create'&&rest.length===3)return result(await api.containers.create(accountId,await jsonFile(selector),requestOptions));
135
+ }
136
+ if(action==='objects'&&verb==='list'&&[3,4].includes(rest.length))return result(await api.objects.list(accountId,selector,file?await jsonFile(file):{}));
137
+ if(action==='credentials'){
138
+ if(verb==='list'&&rest.length===2){const value=await api.credentials.list(accountId);return result({items:(value.items??[]).map(storageCredentialMetadata)});}
139
+ if(verb==='revoke'&&rest.length===3)return result(await api.credentials.revoke(accountId,selector,requestOptions));
140
+ if(verb==='issue'&&rest.length===3||verb==='rotate'&&[3,4].includes(rest.length)){
141
+ const target=required(options['credentials-file'],'--credentials-file');
142
+ const input=verb==='issue'?await jsonFile(selector):file?await jsonFile(file):{};
143
+ const output=await credentialOutput(target,{cwd});
144
+ try{
145
+ const issued=verb==='issue'?await api.credentials.issue(accountId,input,requestOptions):await api.credentials.rotate(accountId,selector,input,requestOptions);
146
+ const saved=await output.save(issued);return result({...storageCredentialMetadata(issued),...saved});
147
+ }catch(error){await output.abort();throw error;}
148
+ }
149
+ }
150
+ throw Object.assign(new Error('Use object-storage capabilities, accounts, usage, containers, objects, or credentials. Run kd --help for exact arguments.'),{code:'INVALID_ARGUMENTS'});
151
+ }
152
+ if(command==='capabilities'&&!action)return result(await client.capabilities());
153
+ if(command==='audit'&&!action)return result(await client.audit());
154
+ if(command==='usage'&&!action)return result(await client.usage());
155
+ if(command==='projects'){
156
+ if(action==='list'&&!rest.length)return result(await client.projects.list());
157
+ if(action==='create'&&rest.length===1)return result(await client.projects.create({name:rest[0]},requestOptions));
158
+ }
159
+ if(command==='nodes'){
160
+ if(action==='list'&&!rest.length)return result(await client.fleet.nodes.list());
161
+ if(action==='show'&&rest.length===1)return result(await client.fleet.nodes.get(rest[0]));
162
+ if(action==='rebalance-plan'&&rest.length===2)return result(await client.fleet.rebalance.plan(rest[0],await jsonFile(rest[1]),requestOptions));
163
+ if(action==='rebalance'&&rest.length===2)return result(await client.fleet.rebalance.apply(rest[0],await jsonFile(rest[1]),requestOptions));
164
+ }
165
+ if(command==='placement'||command==='onboarding'){
166
+ // Selectors are positional. Private keys and attestations are only accepted
167
+ // through the bounded JSON body reader, never an option or URI parameter.
168
+ const input=async(file,scope)=>{
169
+ const body=file?await jsonFile(file):{};
170
+ if(!body||typeof body!=='object'||Array.isArray(body)||['realmId','environmentId','intentId'].some(name=>Object.hasOwn(body,name)))throw Object.assign(new Error('JSON input must be an object without route selectors.'),{code:'INVALID_ARGUMENTS'});
171
+ return {...body,...scope};
172
+ };
173
+ const invoke=(id,data)=>client.invokePlacement(id,data,requestOptions);
174
+ if(command==='placement'){
175
+ if(action==='capabilities'&&!rest.length)return result(await invoke('placement.capabilities',{}));
176
+ if(action==='observations'){
177
+ const [verb,realmId,environmentId,file]=rest,scope={realmId,environmentId};
178
+ if(verb==='list'&&[3,4].includes(rest.length))return result(await invoke('placement.observations.list',await input(file,scope)));
179
+ if(verb==='record'&&rest.length===4)return result(await invoke('placement.observations.create',await input(file,scope)));
180
+ }
181
+ if(action==='propose'&&rest.length===3)return result(await invoke('placement.proposals.create',await input(rest[2],{realmId:rest[0],environmentId:rest[1]})));
182
+ throw Object.assign(new Error('Use placement capabilities, observations list|record <realm> <environment>, or propose <realm> <environment> <json-file|->.'),{code:'INVALID_ARGUMENTS'});
183
+ }
184
+ const [realmId,environmentId,intentId,file]=rest,scope={realmId,environmentId};
185
+ if(action==='list'&&[2,3].includes(rest.length))return result(await invoke('onboarding.intents.list',await input(intentId,scope)));
186
+ if(action==='show'&&rest.length===3)return result(await invoke('onboarding.intents.get',{...scope,intentId}));
187
+ if(action==='register'&&rest.length===3)return result(await invoke('onboarding.intents.create',await input(intentId,scope)));
188
+ if(['bind','resume'].includes(action)&&rest.length===4)return result(await invoke('onboarding.intents.'+action,await input(file,{...scope,intentId})));
189
+ if(['reconcile','release'].includes(action)&&rest.length===3)return result(await invoke('onboarding.intents.'+action,{...scope,intentId}));
190
+ if(action==='expire'&&rest.length===2)return result(await invoke('onboarding.expire',scope));
191
+ throw Object.assign(new Error('Use onboarding list|show|register|bind|resume|reconcile|release|expire with explicit <realm> <environment> selectors and JSON files/stdin for private inputs.'),{code:'INVALID_ARGUMENTS'});
192
+ }
193
+ if(command==='tenants'){
194
+ if(action==='access'){
195
+ const [verb,tenantId,accessId,file]=rest;
196
+ if(verb==='list'&&rest.length===2)return result(await client.tenants.access.list(tenantId));
197
+ if(verb==='grant'&&rest.length===3)return result(await client.tenants.access.grant(tenantId,await jsonFile(accessId),requestOptions));
198
+ if(verb==='plan-revoke'&&rest.length===3)return result(await client.tenants.access.planRevoke(tenantId,accessId,requestOptions));
199
+ if(verb==='revoke'&&rest.length===4)return result(await client.tenants.access.revoke(tenantId,accessId,await jsonFile(file),requestOptions));
200
+ }
201
+ if(action==='list'&&!rest.length)return result(await client.tenants.list());
202
+ if(action==='show'&&rest.length===1)return result(await client.tenants.get(rest[0]));
203
+ if(action==='create'&&rest.length===1)return result(await client.tenants.create(await jsonFile(rest[0]),requestOptions));
204
+ if(action==='rotate'&&rest.length===1)return result(await client.tenants.rotate(rest[0],requestOptions));
205
+ if(action==='plan-offboard'&&rest.length===1)return result(await client.tenants.planOffboard(rest[0],requestOptions));
206
+ if(action==='offboard'&&rest.length===2)return result(await client.tenants.offboard(rest[0],await jsonFile(rest[1]),requestOptions));
207
+ }
208
+ if(command==='kafka'&&action==='topics'){
209
+ const [verb,tenantId,topic,file]=rest;
210
+ if(verb==='list'&&rest.length===2)return result(await client.tenants.kafka.topics.list(tenantId));
211
+ if(verb==='show'&&rest.length===3)return result(await client.tenants.kafka.topics.get(tenantId,topic));
212
+ if(verb==='create'&&[3,4].includes(rest.length))return result(await client.tenants.kafka.topics.create(tenantId,topic,file?await jsonFile(file):{},requestOptions));
213
+ if(verb==='plan-delete'&&rest.length===3)return result(await client.tenants.kafka.topics.planDelete(tenantId,topic,requestOptions));
214
+ if(verb==='delete'&&rest.length===4)return result(await client.tenants.kafka.topics.delete(tenantId,topic,await jsonFile(file),requestOptions));
215
+ }
216
+ if(command==='protect'){
217
+ if(action==='schedule'&&rest[0]==='show'&&rest.length===2)return result(await client.protect.resources.schedule.get(rest[1]));
218
+ if(action==='schedule'&&rest[0]==='set'&&rest.length===3)return result(await client.protect.resources.schedule.set(rest[1],await jsonFile(rest[2]),requestOptions));
219
+ if(action==='schedule')throw Object.assign(new Error('Use protect schedule show <resource> or protect schedule set <resource> <json-file|->.'),{code:'INVALID_ARGUMENTS'});
220
+ if(action==='alerts'&&rest.length===1)return result(await client.protect.resources.alerts(rest[0]));
221
+ if(action==='alerts')throw Object.assign(new Error('Use protect alerts <resource>.'),{code:'INVALID_ARGUMENTS'});
222
+ if(action==='resource-status'&&rest.length===1)return result(await client.protect.resources.status(rest[0]));
223
+ if(action==='points'&&rest[0]==='list'&&rest.length===2)return result(await client.protect.resources.backups.list(rest[1]));
224
+ if(action==='points'&&rest[0]==='show'&&rest.length===3)return result(await client.protect.resources.backups.get(rest[1],rest[2]));
225
+ if(action==='backup'&&[1,2].includes(rest.length))return result(await client.protect.resources.backups.create(rest[0],rest[1]?await jsonFile(rest[1]):{},requestOptions));
226
+ if(action==='restore-plan'&&rest.length===2)return result(await client.protect.resources.restore.plan(rest[0],await jsonFile(rest[1]),requestOptions));
227
+ if(action==='restore'&&rest.length===2)return result(await client.protect.resources.restore.apply(rest[0],await jsonFile(rest[1]),requestOptions));
228
+ }
229
+ if(command==='operations'){
230
+ if(action==='list'&&!rest.length)return result(await client.operations.list());
231
+ if(action==='show'&&rest.length===1)return result(await client.operations.get(rest[0]));
232
+ }
233
+ if(command==='resources'&&['get','manifest'].includes(action)&&rest.length===2)return result(await client.resources[action](...rest));
234
+ if(command==='api'){
235
+ const method=required(action,'METHOD').toUpperCase(),path=required(rest[0],'API path');
236
+ if(!['GET','HEAD','POST','PUT','PATCH','DELETE'].includes(method))throw Object.assign(new Error('Choose GET, HEAD, POST, PUT, PATCH or DELETE.'),{code:'INVALID_ARGUMENTS'});
237
+ let decoded;try{decoded=decodeURIComponent(new URL('http://127.0.0.1'+path).pathname);}catch{throw Object.assign(new Error('API path contains invalid encoding.'),{code:'INVALID_ARGUMENTS'});}
238
+ if(method==='POST'&&/^\/v1\/orgs\/[^/]+\/object-storage\/accounts\/[^/]+\/credentials(?:\/[^/]+\/rotate)?\/?$/.test(decoded))throw Object.assign(new Error('Use object-storage credentials issue or rotate with --credentials-file for protected one-time delivery.'),{code:'INVALID_ARGUMENTS'});
239
+ if(rest.length>2)throw Object.assign(new Error('Use api <METHOD> </path> [json-file].'),{code:'INVALID_ARGUMENTS'});
240
+ return result(await client.request(method,path,rest[1]?await jsonFile(rest[1]):undefined,requestOptions));
241
+ }
242
+ if(command==='cache'&&['get','set','delete'].includes(action)){
243
+ required(rest[0],'Cache ID');required(rest[1],'Key');
244
+ if(action==='set'&&rest.length===3)return result(await client.cache.set(rest[0],rest[1],await jsonFile(rest[2]),requestOptions));
245
+ if(action!=='set'&&rest.length===2)return result(await client.cache[action](rest[0],rest[1],requestOptions));
246
+ }
247
+ if(command==='storage'){
248
+ if(action==='list'&&rest.length===1)return result(await client.storage.list(rest[0]));
249
+ if(['get','delete'].includes(action)&&rest.length===2)return result(await client.storage[action](...rest,requestOptions));
250
+ if(action==='put'&&rest.length===3)return result(await client.storage.put(rest[0],rest[1],await jsonFile(rest[2]),requestOptions));
251
+ }
252
+ if(command==='messaging'){
253
+ if(action==='capabilities'&&rest.length===1)return result(await client.messaging.capabilities(rest[0]));
254
+ if(['peek','deadletters'].includes(action)&&rest.length===2)return result(await client.messaging[action](...rest));
255
+ if(['send','receive'].includes(action)&&rest.length>=2&&rest.length<=3)return result(await client.messaging[action](rest[0],rest[1],rest[2]?await jsonFile(rest[2]):{},requestOptions));
256
+ if(action==='settle'&&rest.length===5)return result(await client.messaging.settle(rest[0],rest[1],rest[2],rest[3],await jsonFile(rest[4]),requestOptions));
257
+ }
258
+ const families={sql:{query:'query','create-table':'createTable'},search:{query:'query','create-index':'createIndex',insert:'insert'},analytics:{query:'query','create-table':'createTable',ingest:'ingest'}};
259
+ if(families[command]?.[action]&&rest.length===2)return result(await client[command][families[command][action]](rest[0],await jsonFile(rest[1]),requestOptions));
260
+ if(command==='mongo'&&['query','insert'].includes(action)&&rest.length===3)return result(await client.databases[action](rest[0],rest[1],await jsonFile(rest[2]),requestOptions));
261
+ if(command==='apps'){
262
+ if(action==='retention'){
263
+ const [verb,app,idOrFile,file]=rest,api=client.apps.retention;required(app,'Application name');
264
+ if(['capabilities','retirements'].includes(verb)&&rest.length===2)return result(await api[verb]({app},requestOptions));
265
+ if(verb==='pins'&&rest.length===2)return result(await api.pins.get({app},requestOptions));
266
+ if(verb==='plan'&&rest.length===3)return result(await api.plan({...await jsonFile(idOrFile),app},requestOptions));
267
+ if(verb==='set-pins'&&rest.length===3)return result(await api.pins.set({...await jsonFile(idOrFile),app},requestOptions));
268
+ if(verb==='get'&&rest.length===3)return result(await api.get({app,planId:idOrFile},requestOptions));
269
+ if(verb==='apply'&&rest.length===4)return result(await api.apply({...await jsonFile(file),app,planId:idOrFile},requestOptions));
270
+ throw Object.assign(new Error('Use apps retention capabilities|pins|retirements <app>, plan|set-pins <app> <json-file>, get <app> <plan-id>, or apply <app> <plan-id> <json-file>.'),{code:'INVALID_ARGUMENTS'});
271
+ }
272
+ if(action==='list'&&!rest.length)return result(await client.apps.list());
273
+ if(action==='create'&&rest.length===1)return result(await client.apps.create({name:rest[0],...(options.project?{projectId:options.project}:{})},requestOptions));
274
+ }
275
+ if(command==='environments'){
276
+ if(action==='list'&&rest.length===1)return result(await client.apps.environments.list(rest[0]));
277
+ if(action==='create'&&rest.length===2)return result(await client.apps.environments.create(rest[0],await jsonFile(rest[1]),requestOptions));
278
+ }
279
+ if(command==='source'){
280
+ const app=required(options.app,'--app');
281
+ if(action==='git'&&!rest.length){
282
+ const scope={app,env:required(options.env,'--env')};
283
+ if(!options['repository-id']&&!options.branch&&!options.commit)return result(await client.apps.sources.github.list(scope,requestOptions));
284
+ if(requestOptions.dryRun)throw Object.assign(new Error('Git source import stores a snapshot. Omit --dry-run.'),{code:'INVALID_ARGUMENTS'});
285
+ return result(await client.apps.sources.github.import({...scope,repositoryId:required(options['repository-id'],'--repository-id'),branch:required(options.branch,'--branch'),commit:options.commit},requestOptions));
286
+ }
287
+ if(action==='upload'&&rest.length<=1)return result(await captureAndUploadRepository(resolve(cwd,rest[0]??'.'),{client,app,uploadId:options['upload-id'],requestOptions}));
288
+ if(action==='status'&&rest.length===1)return result(await client.apps.sources.uploads.status({app,uploadId:rest[0]},requestOptions));
289
+ if(action==='cancel'&&rest.length===1)return result(await client.apps.sources.uploads.cancel({app,uploadId:rest[0]},requestOptions));
290
+ throw Object.assign(new Error('Use source git, source upload [directory], or source status|cancel <upload-id> with --app <name>.'),{code:'INVALID_ARGUMENTS'});
291
+ }
292
+ const appCommands=new Set(['plan','deploy','status','wait','explain','cancel','resume','answer','approve','app','logs','releases','release','promote','rollback','env']);
293
+ if(!appCommands.has(command)||command==='plan'&&action==='delete')return {handled:false};
294
+ let app=options.app;
295
+ if(!app){try{app=JSON.parse(await readFile(resolve(cwd,command==='deploy'||command==='plan'?action??'.':'.','kinedrop.json'),'utf8')).app;}catch{}}
296
+ const scope=()=>({app:required(app,'--app or kinedrop.json app'),env:required(options.env,'--env')});
297
+ const invoke=(id,input)=>client.apps.invoke(id,input,requestOptions);
298
+ if(command==='plan'||command==='deploy'){
299
+ if(rest.length)throw Object.assign(new Error('Use '+command+' [directory] --app <name> --env <name>.'),{code:'INVALID_ARGUMENTS'});
300
+ const target=scope();
301
+ const repositorySelected=options['repository-id']!==undefined||options.branch!==undefined;
302
+ const storedSource=options.source||options['source-digest'];
303
+ if(requestOptions.dryRun&&!storedSource)throw Object.assign(new Error('Repository capture is an upload. For --dry-run supply an existing verified --source JSON; kd plan performs the non-executing deployment plan.'),{code:'INVALID_DRY_RUN_SOURCE'});
304
+ if([options.source,options['source-digest'],options['upload-id'],repositorySelected].filter(Boolean).length>1||repositorySelected&&action){
305
+ throw Object.assign(new Error('Choose one source: a Git repository, a captured source, or a local directory/upload.'),{code:'INVALID_ARGUMENTS'});
306
+ }
307
+ if(command==='deploy'&&repositorySelected)throw Object.assign(new Error('Run kd plan for the selected repository, then deploy with its plan ID, source digest and commit.'),{code:'INVALID_ARGUMENTS'});
308
+ let source;
309
+ if(repositorySelected){
310
+ const imported=await client.apps.sources.github.import({...target,repositoryId:required(options['repository-id'],'--repository-id'),branch:required(options.branch,'--branch'),commit:options.commit},requestOptions);
311
+ source=imported.source;
312
+ }else if(options.source){
313
+ const stored=await jsonFile(options.source);
314
+ source=stored?.source??stored;
315
+ }else if(options['source-digest']){
316
+ source={kind:'snapshot',digest:options['source-digest'],commit:options.commit};
317
+ }else{
318
+ if(options.commit||options['plan-id'])throw Object.assign(new Error('Use --source or --source-digest with a reviewed plan or pinned commit.'),{code:'INVALID_ARGUMENTS'});
319
+ source=await captureAndUploadRepository(resolve(cwd,action??'.'),{client,app:target.app,uploadId:options['upload-id'],requestOptions});
320
+ }
321
+ const sourceRef={kind:source?.kind,digest:source?.digest,...(source?.commit?{commit:source.commit}:{})};
322
+ const answers=options['answers-file']?await jsonFile(options['answers-file']):undefined;
323
+ let operation=await invoke(command==='plan'?'deploy.plan':'deploy.submit',{
324
+ ...target,source:sourceRef,...(command==='deploy'&&options['plan-id']?{planId:options['plan-id']}:{}),...(answers!==undefined?{answers}:{})
325
+ });
326
+ if(command==='plan')return result(operation);
327
+ let after=0;
328
+ // Leave time for the response to arrive before the SDK request deadline.
329
+ const pollSeconds=Math.min(20,Math.max(1,Math.floor((client.timeoutMs??30_000)/2000)));
330
+ while(['queued','running','cancelling'].includes((operation?.operation??operation)?.status)){
331
+ operation=await invoke('operation.wait',{operationId:(operation.operation??operation).id,after,timeoutSeconds:pollSeconds});
332
+ after=operation.next??operation.events?.at(-1)?.seq??after;
333
+ // Older servers may return only the record. Yield before the next poll so
334
+ // an in-process transport cannot starve the background controller.
335
+ if(!Array.isArray(operation.events))await new Promise(done=>setTimeout(done,25));
336
+ }
337
+ return {handled:true,result:operation,exitCode:appsExit(operation)};
338
+ }
339
+ const operationActions={status:'operation.get',wait:'operation.wait',explain:'operation.explain',cancel:'operation.cancel',resume:'operation.resume',answer:'operation.answer',approve:'operation.approve'};
340
+ if(operationActions[command]){
341
+ const extra=['answer','approve'].includes(command)?await jsonFile(rest[0]):{};
342
+ const value=await invoke(operationActions[command],{operationId:required(action,'Operation ID'),...extra});
343
+ return {handled:true,result:value,...(command==='wait'?{exitCode:appsExit(value)}:{})};
344
+ }
345
+ if(command==='app'||command==='logs'||command==='releases')return result(await invoke({app:'app.status',logs:'app.logs',releases:'release.list'}[command],scope()));
346
+ if(command==='release'||command==='promote')return result(await invoke(command==='release'?'release.get':'release.promote',{app:required(app,'--app'),releaseId:required(action,'Release ID'),...(command==='promote'?{env:required(options.env,'--env')}:{})}));
347
+ if(command==='rollback')return result(await invoke('release.rollback',{...scope(),...(options.to?{toReleaseId:options.to}:{})}));
348
+ if(command==='env'){
349
+ if(action==='ls')return result(await invoke('env.config.list',scope()));
350
+ if(['set','secret'].includes(action)&&rest.length===2){
351
+ const input=await jsonFile(rest[1]);const value=typeof input==='string'?input:input&&typeof input==='object'&&!Array.isArray(input)?input.value:undefined;
352
+ if(typeof value!=='string')throw Object.assign(new Error('Configuration or secret JSON requires a string value.'),{code:'INVALID_ARGUMENTS'});
353
+ return result(await invoke(action==='set'?'env.config.set':'env.secret.set',{...scope(),name:rest[0],value}));
354
+ }
355
+ }
356
+ throw Object.assign(new Error('Invalid arguments. Run kd --help.'),{code:'INVALID_ARGUMENTS'});
357
+ }
package/index.mjs ADDED
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createReadStream } from 'node:fs';
4
+ import { pathToFileURL } from 'node:url';
5
+ import {resolve} from 'node:path';
6
+ import { runExtended, EXTENDED_HELP } from './extended.mjs';
7
+ import {configuredAuthority,deviceLogin,keyroxDeviceLogin} from './login.mjs';
8
+ import {reserveCredentialOutput} from './credential-output.mjs';
9
+ const { KineDropClient, keyroxClientOptionsFromEnv, keyroxIssuer, keyroxRequest } = await import('@x12i/kinedrop').catch(error => {
10
+ if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
11
+ return import('../kinedrop-sdk/index.mjs');
12
+ });
13
+ const invalid=message=>Object.assign(new Error(message),{code:'INVALID_ARGUMENTS',status:422});
14
+
15
+ export const HELP = `KineDrop CLI — local control plane and explicit engine integrations
16
+
17
+ Usage: kd <command> [arguments] [options]
18
+
19
+ version Show the installed CLI package version
20
+ doctor Check control-plane health
21
+ catalog List services and capabilities
22
+ runtime Inspect package and service evidence
23
+ auth authority Inspect the server's account authority
24
+ orgs list | create <name> Manage local organizations
25
+ workspaces plan | apply <enrollment.json> Enroll a customer workspace
26
+ workspaces inspect <operationId> Read one workspace enrollment
27
+ workspaces inventory Inspect targets and service bindings
28
+ resources list List organization resources
29
+ resources create <service> <name> Register resource intent
30
+ cache binding <id> Inspect a registered Valkey binding
31
+ stacks plan <blueprint.json> Validate and plan a dependency graph
32
+ stacks apply <planId> Register the planned stack
33
+ docs ingest <text-or-markdown-file> Ground a local text document
34
+ hybrid query <store> <collection> <json> Query/hydrate native documents
35
+ hybrid insert <store> <collection> <json> Insert a native document from JSON
36
+ hybrid nodes | edges <store> Inspect a native graph
37
+ hybrid walk <store> <startNodeId> Traverse up to three graph levels
38
+ protect backups list | create <name> Snapshot the local control-plane catalog
39
+ resilience status | plan <instanceId> Inspect the single-node backup profile
40
+ resilience initialize | backup | archive <instanceId>
41
+ resilience restore-plan <instanceId> Plan recovery to a fresh managed target
42
+ resilience restore <instanceId> <planId> Confirm recovery with its single-use token
43
+ plan delete <service> <resourceId> Prepare a destructive plan
44
+ confirm delete <planId> Consume a destructive confirmation
45
+
46
+ Options:
47
+ --url <url> API URL (KINEDROP_URL; default http://127.0.0.1:4200)
48
+ --org <id> Organization (KINEDROP_ORG)
49
+ --keyrox-org <id> Keyrox approval tenant for login (KINEDROP_KEYROX_ORG)
50
+ --json Machine-readable output
51
+ --read-only Refuse all mutating requests
52
+ --dry-run Ask API to validate without applying writes
53
+ --idempotency-key <key> Replay-safe mutation key
54
+ --topology <profile> lean, ha, or resilient-single-replica-set (MongoDB only)
55
+ --tenant <id> Bind a caches definition to an owned Valkey tenant
56
+ --confirmation-file <p> JSON file or '-' stdin containing confirmationToken
57
+ --help Show help
58
+ --version Show the installed CLI package version
59
+
60
+ Set KINEDROP_TOKEN to a short-lived Keyrox access token. For automatic renewal,
61
+ inject KINEDROP_KEYROX_CREDENTIAL and set KINEDROP_KEYROX_ISSUER to the trusted issuer.
62
+ Stack apply prepares local intent. Apps deployment requires an explicitly configured runtime.
63
+ ${EXTENDED_HELP}
64
+ `;
65
+
66
+ function parse(argv) {
67
+ const values = new Set(['url', 'org', 'keyrox-org', 'idempotency-key', 'topology', 'confirmation-file','credentials-file','engine','compatibility','app','env','source','upload-id','to','project','scopes','principal','login-timeout','tenant','repository-id','branch','commit','plan-id','source-digest','answers-file']);
68
+ const flags = new Set(['json', 'read-only', 'dry-run', 'help', 'version']);
69
+ const options = {};
70
+ const args = [];
71
+ for (let i = 0; i < argv.length; i++) {
72
+ const value = argv[i];
73
+ if (value === '-h') { options.help = true; continue; }
74
+ if (value === '--') { args.push(...argv.slice(i + 1)); break; }
75
+ if (!value.startsWith('--')) { args.push(value); continue; }
76
+ const eq = value.indexOf('=');
77
+ const key = value.slice(2, eq < 0 ? undefined : eq);
78
+ if (flags.has(key)) {
79
+ if (eq >= 0) throw invalid('--' + key + ' takes no value.');
80
+ options[key] = true;
81
+ } else if (values.has(key)) {
82
+ const supplied = eq >= 0 ? value.slice(eq + 1) : argv[++i];
83
+ if (!supplied || supplied.startsWith('--')) throw invalid('--' + key + ' requires a value.');
84
+ options[key] = supplied;
85
+ } else throw invalid('Unknown option. Run kd --help.');
86
+ }
87
+ return { args, options };
88
+ }
89
+
90
+ function required(value, label) {
91
+ if (!value) throw invalid(label + ' is required. Run kd --help.');
92
+ return value;
93
+ }
94
+
95
+ export async function runCli(argv = process.argv.slice(2), { env = process.env, stdout = process.stdout, stderr = process.stderr, client: suppliedClient, cwd=process.cwd(), stdin=process.stdin,sleep,credentialOutput } = {}) {
96
+ let json = argv.includes('--json');
97
+ try {
98
+ const { args, options } = parse(argv);
99
+ json = !!options.json;
100
+ if (options.version || args[0] === 'version') {
101
+ if (args.length && (args.length !== 1 || args[0] !== 'version')) throw invalid('version takes no arguments and cannot be combined with another command.');
102
+ const manifest = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
103
+ stdout.write((json ? JSON.stringify({ name: manifest.name, version: manifest.version }) : manifest.version) + '\n');
104
+ return 0;
105
+ }
106
+ if (options.help || !args.length) { stdout.write(HELP); return 0; }
107
+ const [command, action, ...rest] = args;
108
+ const client = suppliedClient ?? new KineDropClient({
109
+ baseUrl: options.url ?? env.KINEDROP_URL,
110
+ token: env.KINEDROP_TOKEN,
111
+ keyrox: env.KINEDROP_KEYROX_CREDENTIAL === undefined ? undefined : keyroxClientOptionsFromEnv(env),
112
+ orgId: options.org ?? env.KINEDROP_ORG,
113
+ readOnly: !!options['read-only'],
114
+ });
115
+ if (options['read-only'] && suppliedClient) client.readOnly = true;
116
+ const requestOptions = { idempotencyKey: options['idempotency-key'], dryRun: !!options['dry-run'] };
117
+ const inputBytes=async file=>{try{return await readFile(resolve(cwd,file));}catch{throw invalid('Input file could not be read. Check its local path and permissions.');}};
118
+ const confirmation=async()=>{
119
+ const file=required(options['confirmation-file'],'--confirmation-file');let text;
120
+ if(file==='-'){const chunks=[];let size=0;try{for await(const chunk of stdin){size+=Buffer.byteLength(chunk);if(size>16384)throw invalid('Confirmation input exceeds 16 KiB.');chunks.push(Buffer.from(chunk));}}catch(error){if(error?.code==='INVALID_ARGUMENTS')throw error;throw invalid('Confirmation stdin could not be read.');}text=Buffer.concat(chunks).toString('utf8');}
121
+ else {const bytes=await inputBytes(file);if(bytes.length>16384)throw invalid('Confirmation input exceeds 16 KiB.');text=bytes.toString('utf8');}
122
+ let input;try{input=JSON.parse(text);}catch{throw invalid('Confirmation input must be valid JSON.');}
123
+ if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(key=>key!=='confirmationToken')||typeof input.confirmationToken!=='string'||!input.confirmationToken)throw invalid('Confirmation input requires confirmationToken.');
124
+ return input.confirmationToken;
125
+ };
126
+ const loginTarget = options.app!==undefined||options.env!==undefined ? {app:options.app,env:options.env} : undefined;
127
+ options.app??=env.KINEDROP_APP;options.env??=env.KINEDROP_ENV;
128
+ if(command==='login'){
129
+ const taskReadOnly=client.readOnly;let login;
130
+ const authority=await configuredAuthority(client);
131
+ if(authority.provider!=='local'&&authority.provider!=='keyrox')throw Object.assign(new Error('Supply a short-lived bearer token from the configured KineDrop authority.'),{code:'AUTH_PROVIDER_UNSUPPORTED'});
132
+ try {
133
+ client.readOnly=false;
134
+ const input={client,authority,options,target:loginTarget,stderr,sleep};
135
+ login=authority.provider==='keyrox'?await keyroxDeviceLogin({...input,request:keyroxRequest,issuerOf:keyroxIssuer,pinnedIssuer:env.KINEDROP_KEYROX_ISSUER,keyroxOrg:options['keyrox-org']??env.KINEDROP_KEYROX_ORG}):await deviceLogin(input);
136
+ } finally {client.readOnly=taskReadOnly;}
137
+ const forwarded=Object.entries(options).filter(([key,value])=>value!==undefined&&!['scopes','principal','login-timeout','keyrox-org'].includes(key)).flatMap(([key,value])=>typeof value==='boolean'?(value?['--'+key]:[]):['--'+key,String(value)]);
138
+ if(args.length>1)return runCli([...args.slice(1),...forwarded],{client,env,cwd,stdin,stdout,stderr,sleep,credentialOutput});
139
+ stdout.write(JSON.stringify(login,null,json?0:2)+'\n');return 0;
140
+ }
141
+ if(command==='logout'){
142
+ if(client.readOnly)throw Object.assign(new Error('This client is read-only.'),{code:'READ_ONLY',status:403});
143
+ const authority=await configuredAuthority(client);
144
+ let result;
145
+ if(authority.provider==='keyrox'){
146
+ if(!env.KINEDROP_KEYROX_ISSUER||keyroxIssuer(env.KINEDROP_KEYROX_ISSUER)!==keyroxIssuer(authority.issuer))throw Object.assign(new Error('Set KINEDROP_KEYROX_ISSUER to the trusted issuer reported by kd auth authority.'),{code:'KEYROX_CONFIGURATION_INVALID'});
147
+ const token=env.KINEDROP_KEYROX_CREDENTIAL??client.token;
148
+ if(!token)throw Object.assign(new Error('Supply a Keyrox credential or access token to revoke.'),{code:'AUTH_REQUIRED',status:401});
149
+ if(!/^krx_[A-Za-z0-9_-]+$|^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token))throw invalid('Supply a Keyrox OAuth credential or access token for revocation.');
150
+ const revoked=await keyroxRequest(env.KINEDROP_KEYROX_ISSUER,'/oauth/revoke',new URLSearchParams({token}),{fetchImpl:client.fetch});
151
+ if(!revoked.ok||revoked.data.ok!==true)throw Object.assign(new Error('Keyrox did not confirm revocation.'),{code:'KEYROX_REVOCATION_FAILED',status:revoked.status});
152
+ result={revoked:true,provider:'keyrox'};
153
+ }else result=await client.auth.logout();
154
+ client.token=undefined;stdout.write(JSON.stringify(result)+'\n');return 0;
155
+ }
156
+ const extended=await runExtended({args,options,client,requestOptions,cwd,stdin,credentialOutput});
157
+ let result,exitCode=extended.exitCode??0;
158
+ if(extended.handled)result=extended.result;
159
+ else switch (command) {
160
+ case 'auth':
161
+ if(action!=='authority'||rest.length)throw invalid('Use kd auth authority.');
162
+ result=await configuredAuthority(client);break;
163
+ case 'doctor':
164
+ if (action) throw invalid('doctor takes no arguments.');
165
+ result = await (client.diagnostics?client.diagnostics():client.doctor()); break;
166
+ case 'catalog':
167
+ if (action) throw invalid('catalog takes no arguments.');
168
+ result = await client.catalog(); break;
169
+ case 'runtime':
170
+ if(action)throw invalid('runtime takes no arguments.');
171
+ result=await client.runtime();break;
172
+ case 'orgs':
173
+ if (action === 'list' && !rest.length) result = await client.orgs.list();
174
+ else if (action === 'create' && rest.length === 1) result = await client.orgs.create({ name: required(rest[0], 'Organization name') }, requestOptions);
175
+ else throw invalid('Use orgs list or orgs create <name>.');
176
+ break;
177
+ case 'workspaces': {
178
+ const enrollmentFile = async () => JSON.parse((await inputBytes(required(rest[0], 'Enrollment file'))).toString('utf8'));
179
+ if ((action === 'plan' || action === 'apply') && rest.length === 1) result = await client.workspaces[action](await enrollmentFile(), requestOptions);
180
+ else if (action === 'inspect' && rest.length === 1) result = await client.workspaces.inspect(rest[0], requestOptions);
181
+ else if (action === 'inventory' && !rest.length) result = await client.workspaces.inventory();
182
+ else throw invalid('Use workspaces plan|apply <enrollment.json>, workspaces inspect <operationId>, or workspaces inventory.');
183
+ break;
184
+ }
185
+ case 'resources':
186
+ if (action === 'list' && !rest.length) result = await client.resources.list();
187
+ else if (action === 'create' && rest.length === 2) {
188
+ const topology = options.topology ?? 'lean';
189
+ if (!['lean', 'ha','resilient-single-replica-set'].includes(topology)) throw invalid('--topology must be lean, ha, or resilient-single-replica-set.');
190
+ if(topology==='resilient-single-replica-set'&&rest[0]!=='databases')throw invalid('The resilient single-node profile requires the databases service.');
191
+ if((options.engine||options.compatibility)&&rest[0]!=='streams')throw invalid('--engine and --compatibility apply to streams only.');
192
+ if(options.tenant!==undefined&&rest[0]!=='caches')throw invalid('--tenant applies to caches only.');
193
+ result = await client.resources.create(rest[0], { name: rest[1], topology,...(options.engine?{engine:options.engine}:{}),...(options.compatibility?{compatibility:options.compatibility}:{}),...(options.tenant===undefined?{}:{tenantId:options.tenant}) }, requestOptions);
194
+ } else throw invalid('Use resources list or resources create <service> <name>.');
195
+ break;
196
+ case 'cache':
197
+ if(action!=='binding'||rest.length!==1)throw invalid('Use cache binding <id>.');
198
+ result=await client.cache.binding(rest[0]);break;
199
+ case 'stacks':
200
+ if (action === 'plan' && rest.length === 1) {
201
+ const text = (await inputBytes(rest[0])).toString('utf8');
202
+ if (Buffer.byteLength(text) > 2 * 1024 * 1024) throw invalid('Blueprint exceeds the 2 MiB client limit.');
203
+ let blueprint;
204
+ try { blueprint = JSON.parse(text); } catch { throw invalid('Blueprint must be valid JSON.'); }
205
+ result = await client.stacks.plan(blueprint, requestOptions);
206
+ } else if (action === 'apply' && rest.length === 1) result = await client.stacks.apply(rest[0], requestOptions);
207
+ else throw invalid('Use stacks plan <blueprint.json> or stacks apply <planId>.');
208
+ break;
209
+ case 'docs':
210
+ if (action !== 'ingest' || rest.length !== 1) throw invalid('Use docs ingest <supported-document-file>.');
211
+ {
212
+ const bytes = await inputBytes(rest[0]);
213
+ if (bytes.length > 2 * 1024 * 1024) throw invalid('Document exceeds the 2 MiB client limit.');
214
+ const fileName = rest[0].split(/[\\/]/).pop();
215
+ const needsReader=bytes.includes(0)||bytes.subarray(0,5).toString()==='%PDF-'||/\.(pdf|docx|pptx|xlsx|html?|csv|tsv|jsonl?|xml|odt|ods|odp|epub|eml|rtf)$/i.test(fileName);
216
+ if(needsReader){
217
+ if(bytes.length>1024*1024)throw invalid('Binary document uploads must be at most 1 MiB at this JSON gateway.');
218
+ const capabilities=await client.docs.capabilities();
219
+ if(!capabilities.acquisition)throw Object.assign(new Error('Published document acquisition is not configured on this server.'),{code:'CAPABILITY_UNAVAILABLE',status:503});
220
+ result=await client.docs.ingest({contentBase64:bytes.toString('base64'),fileName,onSecret:'redact'},requestOptions);break;
221
+ }
222
+ let text;
223
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw invalid('Document must contain valid UTF-8 text.'); }
224
+ result = await client.docs.ingest({ text, fileName, onSecret: 'redact' }, requestOptions);
225
+ }
226
+ break;
227
+ case 'hybrid':
228
+ if(['query','insert'].includes(action)&&rest.length===3){
229
+ const bytes=await inputBytes(rest[2]);if(bytes.length>1024*1024)throw invalid('Hybrid request JSON exceeds 1 MiB.');
230
+ let input;try{input=JSON.parse(bytes.toString('utf8'));}catch{throw invalid('Hybrid input must be valid JSON.');}
231
+ result=await client.hybrid[action](rest[0],rest[1],input,requestOptions);
232
+ }else if(['nodes','edges'].includes(action)&&rest.length===1)result=await client.hybrid.graph[action](rest[0]);
233
+ else if(action==='walk'&&rest.length===2)result=await client.hybrid.graph.walk(rest[0],{startNodeId:rest[1],maxDepth:3},requestOptions);
234
+ else throw invalid('Use hybrid query|insert <store> <collection> <json>, hybrid nodes|edges <store>, or hybrid walk <store> <startNodeId>.');
235
+ break;
236
+ case 'protect':
237
+ if (action !== 'backups') throw invalid('Use protect backups list or protect backups create <name>.');
238
+ if (rest[0] === 'list' && rest.length === 1) result = await client.protect.backups.list();
239
+ else if (rest[0] === 'create' && rest.length === 2) result = await client.protect.backups.create({ name: rest[1] }, requestOptions);
240
+ else throw invalid('Use protect backups list or protect backups create <name>.');
241
+ break;
242
+ case 'resilience': {
243
+ const api=client.databases.resilience;
244
+ if(['status','plan','initialize','backup','archive','restore-plan'].includes(action)&&rest.length===1){
245
+ const instanceId=required(rest[0],'Instance ID');
246
+ if(action==='status')result=await api.status(instanceId);
247
+ else if(action==='archive')result=await api.archive(instanceId,{},requestOptions);
248
+ else result=await api[action==='restore-plan'?'planRestore':action](instanceId,requestOptions);
249
+ }else if(action==='restore'&&rest.length===2){
250
+ result=await api.restore(rest[0],rest[1],await confirmation(),requestOptions);
251
+ }else throw invalid('Use resilience status|plan|initialize|backup|archive|restore-plan <instanceId>, or resilience restore <instanceId> <planId> --confirmation-file <json-file|->.');
252
+ break;
253
+ }
254
+ case 'plan':
255
+ if (action !== 'delete' || rest.length !== 2) throw invalid('Use plan delete <service> <resourceId>.');
256
+ result = await client.resources.planDelete(rest[0], rest[1], requestOptions); break;
257
+ case 'confirm':
258
+ if (action !== 'delete' || rest.length !== 1) throw invalid('Use confirm delete <planId> --confirmation-file <json-file|->.');
259
+ if (requestOptions.dryRun) throw invalid('Use plan delete to review a destructive operation. --dry-run cannot consume a confirmation.');
260
+ result = await client.resources.confirmDelete(rest[0], await confirmation(), requestOptions); break;
261
+ default: throw invalid('Unknown command. Run kd --help.');
262
+ }
263
+ stdout.write(JSON.stringify(result ?? null, null, json ? 0 : 2) + '\n');
264
+ return exitCode;
265
+ } catch (error) {
266
+ const localInput=error instanceof SyntaxError||error instanceof TypeError||['ENOENT','EACCES','EPERM','EISDIR','ENOTDIR'].includes(error?.code);
267
+ const message = localInput?(error instanceof SyntaxError?'Input must be valid JSON.':error instanceof TypeError?(String(error.message).startsWith('Remote KineDrop connections require HTTPS.')?'Remote KineDrop connections require HTTPS; HTTP is allowed only for loopback.':'Invalid client input. Run kd --help.'):'Input file or directory could not be read. Check its local path and permissions.'):String(error?.message ?? 'Command failed.');
268
+ const code = localInput?'INVALID_ARGUMENTS':error?.code ?? 'CLI_ERROR';
269
+ stderr.write(json ? JSON.stringify({ error: { code, message, ...(error?.correlationId ? { correlationId: error.correlationId } : {}) } }) + '\n' : 'Error [' + code + ']: ' + message + '\n');
270
+ return error.status===401||error.status===403?3:localInput||error.status===400||error.status===422||/^(?:INVALID_|CONFIG_)/.test(code)?2:1;
271
+ }
272
+ }
273
+
274
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) process.exitCode = await runCli();
package/login.mjs ADDED
@@ -0,0 +1,91 @@
1
+ // Device grants stay in memory. A following kd command can use the scoped grant
2
+ // without writing a plaintext credential or printing it on stdout.
3
+ export async function deviceLogin({client,options,target,stderr,sleep=ms=>new Promise(done=>setTimeout(done,ms))}){
4
+ const timeout=Number(options['login-timeout']??300);
5
+ if(!Number.isFinite(timeout)||timeout<1||timeout>600)throw Object.assign(new Error('--login-timeout must be 1-600 seconds.'),{code:'INVALID_ARGUMENTS'});
6
+ if(target&&(!target.app||!target.env))throw Object.assign(new Error('Use --app and --env together for a scoped sign-in.'),{code:'INVALID_ARGUMENTS'});
7
+ const request=await client.auth.login({...(target??{}),...(options.scopes?{scopes:options.scopes.split(',').filter(Boolean)}:{}),...(options.principal?{principalType:options.principal}:{}),deviceName:'KineDrop CLI'});
8
+ stderr.write('Approve code '+request.userCode+' at '+new URL(request.verificationUri,client.baseUrl).href+'. The CLI never prints or saves the bearer token.\n');
9
+ const deadline=Date.now()+Math.min(timeout,request.expiresIn)*1000;let interval=request.interval??3;
10
+ while(Date.now()<deadline){
11
+ await sleep(Math.max(1,Math.min(30,interval))*1000);
12
+ const grant=await client.auth.poll(request.deviceCode);
13
+ if(grant.accessToken){client.token=grant.accessToken;if(grant.orgId)client.orgId=grant.orgId;return {authenticated:true,orgId:grant.orgId,principalType:grant.principalType,scopes:grant.scopes,expiresIn:grant.expiresIn,...(grant.target?{target:grant.target}:{}),tokenPersisted:false};}
14
+ if(grant.status!=='authorization_pending')throw Object.assign(new Error('Device authorization returned an unsupported state.'),{code:'AUTH_INVALID_RESPONSE'});
15
+ interval=grant.interval??interval;
16
+ }
17
+ throw Object.assign(new Error('Device authorization timed out. Start kd login again.'),{code:'AUTH_DEVICE_TIMEOUT',status:401});
18
+ }
19
+
20
+ const deviceGrant = 'urn:ietf:params:oauth:grant-type:device_code';
21
+ const oauthError = (code, message, status) => Object.assign(new Error(message), { code, status });
22
+
23
+ export async function configuredAuthority(client) {
24
+ if (!client.auth.authority) return {provider:'local'};
25
+ try { return await client.auth.authority(); }
26
+ catch (error) {
27
+ // Releases predating authority discovery route the request through authentication.
28
+ if ([401,404].includes(error.status)) return {provider:'local'};
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ export async function keyroxDeviceLogin({client,authority,options,target,stderr,request,issuerOf,pinnedIssuer,keyroxOrg,sleep=ms=>new Promise(done=>setTimeout(done,ms))}) {
34
+ const timeout = Number(options['login-timeout'] ?? 600);
35
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 600) throw oauthError('INVALID_ARGUMENTS', '--login-timeout must be 1-600 seconds.', 422);
36
+ if (options.principal && options.principal !== 'agent') throw oauthError('INVALID_ARGUMENTS', 'Keyrox device login grants an agent identity. Use --principal agent.', 422);
37
+ const validId = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
38
+ const validAppName = value => typeof value === 'string' && value.length <= 24 && /^[a-z](?:[a-z0-9]|-(?!-))*[a-z0-9]$/.test(value);
39
+ if (!validId(client.orgId)) throw oauthError('INVALID_ARGUMENTS', 'Supply a KineDrop organization with --org or KINEDROP_ORG.', 422);
40
+ if (keyroxOrg !== undefined && !validId(keyroxOrg)) throw oauthError('INVALID_ARGUMENTS', 'Supply a valid Keyrox organization ID.', 422);
41
+ if (target && (!validAppName(target.app) || !validAppName(target.env))) throw oauthError('INVALID_ARGUMENTS', 'Use --app and --env together with valid names.', 422);
42
+ const scopes = [...new Set((options.scopes ?? (target ? 'apps:read' : 'resources:read')).split(',').map(scope => scope.trim()))];
43
+ if (!scopes.length || scopes.some(scope => !/^[a-z][a-z0-9:-]{0,63}$/.test(scope))) throw oauthError('INVALID_ARGUMENTS', '--scopes must contain comma-separated action names.', 422);
44
+ if (!target && scopes.some(scope => ['apps:read','apps:deploy','apps:promote','apps:rollback','apps:config'].includes(scope))) {
45
+ throw oauthError('INVALID_ARGUMENTS', 'Use --app and --env to request an application grant.', 422);
46
+ }
47
+ if (typeof authority.audience !== 'string' || !authority.audience || /\s/.test(authority.audience)) throw oauthError('KEYROX_CONFIGURATION_INVALID', 'The KineDrop server did not publish its Keyrox audience.');
48
+ const issuer = issuerOf(authority.issuer);
49
+ if (pinnedIssuer && issuerOf(pinnedIssuer) !== issuer) throw oauthError('KEYROX_CONFIGURATION_INVALID', 'The Keyrox issuer differs from KINEDROP_KEYROX_ISSUER.');
50
+ const organizationResource = `kinedrop://orgs/${client.orgId}`;
51
+ const resource = target ? `${organizationResource}/apps/${target.app}/environments/${target.env}` : organizationResource;
52
+ if (resource.length > 200) throw oauthError('INVALID_ARGUMENTS', 'The requested Keyrox resource identifier exceeds 200 characters.', 422);
53
+ const send = (path, input) => request(issuer, path, input, {fetchImpl:client.fetch});
54
+ const registration = await send('/oauth/register', {client_name:'KineDrop CLI',redirect_uris:['http://127.0.0.1/callback'],token_endpoint_auth_method:'none'});
55
+ if (!registration.ok || typeof registration.data.client_id !== 'string' || !registration.data.client_id || registration.data.client_id.length > 256) {
56
+ throw oauthError('KEYROX_CLIENT_REGISTRATION_FAILED', 'Keyrox could not register this KineDrop CLI session.', registration.status);
57
+ }
58
+ const clientId = registration.data.client_id;
59
+ const form = new URLSearchParams({client_id:clientId,audience:authority.audience,scope:scopes.join(' ')});
60
+ if (keyroxOrg !== undefined) form.set('org',keyroxOrg);
61
+ form.append('resource', resource);
62
+ const started = await send('/oauth/device', form);
63
+ const device = started.data;
64
+ if (!started.ok) throw oauthError('KEYROX_DEVICE_REJECTED', 'Keyrox rejected the requested KineDrop action or resource scope.', started.status);
65
+ if (typeof device.device_code !== 'string' || !/^[A-Za-z0-9_-]{16,512}$/.test(device.device_code) || typeof device.user_code !== 'string' || !/^[A-Za-z0-9-]{4,64}$/.test(device.user_code) || !Number.isSafeInteger(device.expires_in) || device.expires_in < 1 || device.expires_in > 900) {
66
+ throw oauthError('KEYROX_RESPONSE_INVALID', 'Keyrox returned an invalid device authorization.');
67
+ }
68
+ let verification;
69
+ try { verification = new URL(device.verification_uri); }
70
+ catch { throw oauthError('KEYROX_RESPONSE_INVALID', 'Keyrox did not return a device approval address.'); }
71
+ if (verification.origin !== issuer || verification.username || verification.password || verification.search || verification.hash) throw oauthError('KEYROX_RESPONSE_INVALID', 'Keyrox returned an unsafe device approval address.');
72
+ stderr.write(`Approve code ${device.user_code} at ${verification.href}.\n`);
73
+ const deadline = Date.now() + Math.min(timeout, device.expires_in) * 1000;
74
+ let interval = Math.max(1, Number.isSafeInteger(device.interval) ? device.interval : 5);
75
+ while (Date.now() + interval * 1000 <= deadline) {
76
+ await sleep(interval * 1000);
77
+ if (Date.now() >= deadline) break;
78
+ const result = await send('/oauth/token', new URLSearchParams({grant_type:deviceGrant,device_code:device.device_code,client_id:clientId}));
79
+ const grant = result.data;
80
+ if (result.ok && typeof grant.access_token === 'string' && grant.access_token.length <= 8192 && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(grant.access_token) && typeof grant.token_type === 'string' && grant.token_type.toLowerCase() === 'bearer' && Number.isSafeInteger(grant.expires_in) && grant.expires_in > 0 && grant.expires_in <= 3600) {
81
+ client.token = grant.access_token;
82
+ return {authenticated:true,provider:'keyrox',orgId:client.orgId,principalType:'agent',scopes:typeof grant.scope === 'string' ? grant.scope.split(' ').filter(Boolean) : scopes,expiresIn:grant.expires_in,...(target ? {target} : {}),tokenPersisted:false};
83
+ }
84
+ if (!result.ok && grant.error === 'authorization_pending') continue;
85
+ if (!result.ok && grant.error === 'slow_down') { interval += 5; continue; }
86
+ if (grant.error === 'access_denied') throw oauthError('AUTH_DEVICE_DENIED', 'The Keyrox device request was denied.', 403);
87
+ if (grant.error === 'expired_token') break;
88
+ throw oauthError('KEYROX_RESPONSE_INVALID', 'Keyrox returned an unsupported device authorization response.', result.status);
89
+ }
90
+ throw oauthError('AUTH_DEVICE_TIMEOUT', 'Keyrox device authorization timed out. Start kd login again.', 401);
91
+ }
package/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "@x12i/kinedrop-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "license": "UNLICENSED",
5
+ "repository": { "type": "git", "url": "git+https://github.com/kinedrop/kinedrop.git", "directory": "packages/kinedrop-cli" },
6
+ "publishConfig": { "access": "public" },
7
+ "type": "module",
8
+ "bin": { "kd": "./index.mjs" },
9
+ "engines": { "node": ">=24.0.0" },
10
+ "dependencies": { "@x12i/kinedrop": "0.1.1" },
11
+ "files": ["index.mjs", "extended.mjs", "source.mjs", "login.mjs", "credential-output.mjs"]
12
+ }
package/source.mjs ADDED
@@ -0,0 +1,131 @@
1
+ import { readdir,readFile,lstat,open,realpath } from 'node:fs/promises';
2
+ import {constants} from 'node:fs';
3
+ import { join,resolve,relative,isAbsolute } from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const excluded=new Set(['.git','.hg','.svn','.kinedrop','.aws','.ssh','.codex','.agents','.npmrc','.yarnrc.yml','node_modules','artifacts','.next','.nuxt','dist','build','coverage','secrets']);
7
+ const forbidden=name=>excluded.has(name.toLowerCase())||/^\.env(?:\.|$)/i.test(name)||/\.(?:pem|key|pfx|p12|jks|keystore)$/i.test(name)||/^(?:credentials|auth)\.json$/i.test(name);
8
+ const invalid=message=>Object.assign(new Error(message),{code:'CONFIG_SOURCE_INVALID'});
9
+
10
+ /** Capture bytes, never execute project hooks. The JSON upload profile is bounded to Core's 2 MiB body. */
11
+ export async function captureRepository(directory){
12
+ const root=resolve(directory),files={},manifest=[],seen=new Set();let expanded=0;
13
+ async function walk(relative=''){
14
+ const entries=(await readdir(join(root,relative),{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name));
15
+ for(const entry of entries){
16
+ if(forbidden(entry.name))continue;
17
+ const path=(relative?relative+'/':'')+entry.name;
18
+ if(entry.isSymbolicLink())throw invalid('Source contains a symbolic link: '+path+'. Use regular files in the supported source profile.');
19
+ if(entry.isDirectory()){await walk(path);continue;}
20
+ if(!entry.isFile())throw invalid('Source contains a special file: '+path);
21
+ const folded=path.toLowerCase();if(seen.has(folded))throw invalid('Source paths collide by case: '+path);seen.add(folded);
22
+ const bytes=await readFile(join(root,path));expanded+=bytes.length;
23
+ if(manifest.length>=20000||bytes.length>100*1024*1024||expanded>1024*1024)throw Object.assign(invalid('This JSON source upload profile supports at most 1 MiB of expanded repository content. Use a smaller source or a verified artifact.'),{sourceProfileLimit:true});
24
+ manifest.push({path,digest:'sha256:'+createHash('sha256').update(bytes).digest('hex'),sizeBytes:bytes.length});
25
+ files[path]={contentBase64:bytes.toString('base64')};
26
+ }
27
+ }
28
+ await walk();
29
+ const result={manifest:{files:manifest},files};
30
+ if(Buffer.byteLength(JSON.stringify(result))>1900000)throw Object.assign(invalid('Source manifest and bytes exceed the JSON upload limit.'),{sourceProfileLimit:true});
31
+ return result;
32
+ }
33
+
34
+ export const SOURCE_UPLOAD_PROFILE=Object.freeze({chunkBytes:512*1024,maxManifestBytes:1024*1024,maxFiles:20000,maxFileBytes:100*1024*1024,maxTotalBytes:500*1024*1024});
35
+ const sourceError=(code,message)=>Object.assign(new Error(message),{code});
36
+ const digest=bytes=>'sha256:'+createHash('sha256').update(bytes).digest('hex');
37
+ const stamp=stat=>[stat.dev,stat.ino,stat.size,stat.mtimeNs,stat.ctimeNs].map(String).join(':');
38
+ const contained=(root,path)=>{const part=relative(root,path);return part&&!/^\.\.(?:[\\/]|$)/.test(part)&&!isAbsolute(part);};
39
+ const checkedPath=path=>{
40
+ if(typeof path!=='string'||path.length>500||path.normalize('NFC')!==path||/[\\:<>"|?*\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/.test(path)||path.split('/').some(part=>!part||part==='.'||part==='..'||/[. ]$/.test(part)||['__proto__','constructor','prototype'].includes(part)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)))throw sourceError('CONFIG_SOURCE_INVALID','Source contains a non-portable or unsafe relative path.');
41
+ };
42
+ function interrupted(signal){if(signal?.aborted)throw sourceError('SOURCE_UPLOAD_ABORTED','Source upload was interrupted.');}
43
+ async function unchangedDirectories(prepared){for(const directory of prepared.directories??[]){const current=await lstat(directory.absolute,{bigint:true});if(current.isSymbolicLink()||!current.isDirectory()||stamp(current)!==directory.stamp)throw sourceError('SOURCE_CHANGED','The source directory inventory changed after its manifest was captured.');}}
44
+ async function readVerified(file,{signal,onChunk}={}){
45
+ interrupted(signal);const before=await lstat(file.absolute,{bigint:true});
46
+ if(before.isSymbolicLink()||!before.isFile()||stamp(before)!==file.stamp)throw sourceError('SOURCE_CHANGED','A source file changed after its manifest was captured.');
47
+ const handle=await open(file.absolute,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
48
+ try{
49
+ if(stamp(await handle.stat({bigint:true}))!==file.stamp)throw sourceError('SOURCE_CHANGED','A source file changed before its bytes could be read.');
50
+ const hash=createHash('sha256'),buffer=Buffer.alloc(SOURCE_UPLOAD_PROFILE.chunkBytes);let position=0,index=0;
51
+ while(position<file.sizeBytes){interrupted(signal);const size=Math.min(buffer.length,file.sizeBytes-position);let read=0;
52
+ while(read<size){const result=await handle.read(buffer,read,size-read,position+read);if(!result.bytesRead)throw sourceError('SOURCE_CHANGED','A source file was truncated while being read.');read+=result.bytesRead;}
53
+ const bytes=Buffer.from(buffer.subarray(0,size));hash.update(bytes);if(onChunk)await onChunk(bytes,index);position+=size;index++;
54
+ }
55
+ if(stamp(await handle.stat({bigint:true}))!==file.stamp||stamp(await lstat(file.absolute,{bigint:true}))!==file.stamp)throw sourceError('SOURCE_CHANGED','A source file changed while its bytes were being read.');
56
+ return 'sha256:'+hash.digest('hex');
57
+ }finally{await handle.close();}
58
+ }
59
+
60
+ /** Hash source incrementally; the prepared object retains metadata and paths, never the full repository bytes. */
61
+ export async function prepareRepositorySource(directory,{signal}={}){
62
+ const root=resolve(directory),top=await lstat(root);if(!top.isDirectory()||top.isSymbolicLink())throw sourceError('CONFIG_SOURCE_INVALID','Choose a regular repository directory.');
63
+ const actualRoot=await realpath(root),files=[],directories=[],seen=new Set();let totalBytes=0,manifestBytes=Buffer.byteLength('{"files":[]}');
64
+ async function walk(folder=''){
65
+ interrupted(signal);const absolute=join(root,folder),stat=await lstat(absolute,{bigint:true});if(!stat.isDirectory()||stat.isSymbolicLink())throw sourceError('CONFIG_SOURCE_INVALID','Source contains a symbolic link or special directory.');directories.push({absolute,stamp:stamp(stat)});
66
+ const actual=await realpath(absolute);if(actual!==actualRoot&&!contained(actualRoot,actual))throw sourceError('CONFIG_SOURCE_INVALID','A source directory escaped the selected repository.');
67
+ const entries=(await readdir(absolute,{withFileTypes:true})).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);
68
+ for(const entry of entries){if(forbidden(entry.name))continue;const path=folder?folder+'/'+entry.name:entry.name;checkedPath(path);const target=join(root,path),stat=await lstat(target,{bigint:true});
69
+ if(stat.isSymbolicLink())throw sourceError('CONFIG_SOURCE_INVALID','Source contains a symbolic link.');
70
+ if(stat.isDirectory()){await walk(path);continue;}if(!stat.isFile())throw sourceError('CONFIG_SOURCE_INVALID','Source contains a special file.');
71
+ const folded=path.toLowerCase();if(seen.has(folded))throw sourceError('CONFIG_SOURCE_INVALID','Source paths collide by case.');seen.add(folded);
72
+ const sizeBytes=Number(stat.size);totalBytes+=sizeBytes;
73
+ if(files.length>=SOURCE_UPLOAD_PROFILE.maxFiles||!Number.isSafeInteger(sizeBytes)||sizeBytes>SOURCE_UPLOAD_PROFILE.maxFileBytes||totalBytes>SOURCE_UPLOAD_PROFILE.maxTotalBytes)throw sourceError('CONFIG_SOURCE_INVALID','Repository exceeds the bounded source-upload file or byte profile.');
74
+ const publicFile={path,digest:'sha256:'+'0'.repeat(64),sizeBytes};manifestBytes+=Buffer.byteLength(JSON.stringify(publicFile))+(files.length?1:0);
75
+ if(manifestBytes>SOURCE_UPLOAD_PROFILE.maxManifestBytes)throw sourceError('SOURCE_MANIFEST_TOO_LARGE','Source manifest exceeds the 1 MiB transfer profile.');
76
+ const file={...publicFile,absolute:target,stamp:stamp(stat)};file.digest=await readVerified(file,{signal});files.push(file);
77
+ }
78
+ }
79
+ await walk();await unchangedDirectories({directories});if(!files.length)throw sourceError('CONFIG_SOURCE_INVALID','Repository source is empty.');files.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
80
+ const manifest={files:files.map(({path,digest,sizeBytes})=>({path,digest,sizeBytes}))};
81
+ const sourceDigest=digest('{'+manifest.files.map(file=>JSON.stringify(file.path)+':'+JSON.stringify(file.digest)).join(',')+'}');
82
+ return {manifest,files,directories,totalBytes,sourceDigest};
83
+ }
84
+
85
+ /** SDK/CLI transfer profile: fixed bounded chunks; retries resume an actor-bound server session. */
86
+ export async function uploadPreparedRepository(prepared,{client,app,uploadId,requestOptions={}}={}){
87
+ if(client?.readOnly)throw Object.assign(sourceError('READ_ONLY','This client is read-only.'),{status:403});
88
+ if(requestOptions.dryRun)throw sourceError('INVALID_DRY_RUN_SOURCE','Source upload has no dry-run mode. Supply an already verified source for a dry-run plan.');
89
+ const uploads=client?.apps?.sources?.uploads;if(!uploads)throw sourceError('SOURCE_UPLOAD_UNAVAILABLE','This client has no configured chunked source-upload interface.');
90
+ const options=requestOptions.signal?{signal:requestOptions.signal}:{};let id=uploadId;
91
+ const same=(left,right)=>JSON.stringify(left.map(({path,digest,sizeBytes})=>({path,digest,sizeBytes})).sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0))===JSON.stringify(right);
92
+ try{
93
+ await unchangedDirectories(prepared);
94
+ const session=id?await uploads.status({app,uploadId:id},options):await uploads.create({app,manifest:prepared.manifest},options);id=session.uploadId;
95
+ if(typeof id!=='string'||!/^upl_[a-f0-9-]{36}$/.test(id)||session.chunkBytes!==SOURCE_UPLOAD_PROFILE.chunkBytes||!Array.isArray(session.files)||session.files.some(file=>!file||typeof file.path!=='string'||!/^sha256:[a-f0-9]{64}$/.test(file.digest??'')||!Number.isSafeInteger(file.sizeBytes)||file.sizeBytes<0)||!same(session.files,prepared.manifest.files))throw sourceError('SOURCE_UPLOAD_MISMATCH','Upload session does not match the exact captured repository.');
96
+ if(session.state==='finalized'){
97
+ if(session.source?.kind!=='snapshot'||session.source.digest!==prepared.sourceDigest)throw sourceError('SOURCE_UPLOAD_MISMATCH','Finalized upload does not match the exact captured repository.');
98
+ for(const file of prepared.files)if(await readVerified(file,{signal:requestOptions.signal})!==file.digest)throw sourceError('SOURCE_CHANGED','A source file changed after the upload was finalized.');
99
+ await unchangedDirectories(prepared);return session.source;
100
+ }
101
+ if(session.state!=='uploading')throw sourceError('SOURCE_UPLOAD_PROTOCOL_INVALID','Upload session is not accepting source bytes.');
102
+ for(const file of prepared.files){const observed=session.files.find(item=>item.path===file.path),indices=observed.receivedChunks??[],count=Math.ceil(file.sizeBytes/SOURCE_UPLOAD_PROFILE.chunkBytes);
103
+ if(!Array.isArray(indices))throw sourceError('SOURCE_UPLOAD_PROTOCOL_INVALID','Upload session contains invalid received-chunk metadata.');const received=new Set(indices);
104
+ if(received.size!==indices.length||[...received].some(index=>!Number.isInteger(index)||index<0||index>=count))throw sourceError('SOURCE_UPLOAD_PROTOCOL_INVALID','Upload session contains invalid received-chunk metadata.');
105
+ const actualDigest=await readVerified(file,{signal:requestOptions.signal,onChunk:async(bytes,index)=>{if(received.has(index))return;const input={app,uploadId:id,path:file.path,index,digest:digest(bytes),contentBase64:bytes.toString('base64')},answer=await uploads.chunk(input,options);if(answer?.accepted!==true||answer.uploadId!==id||answer.path!==file.path||answer.index!==index||answer.digest!==input.digest||answer.sizeBytes!==bytes.length)throw sourceError('SOURCE_UPLOAD_PROTOCOL_INVALID','Server did not confirm the exact source chunk.');}});
106
+ if(actualDigest!==file.digest)throw sourceError('SOURCE_CHANGED','A source file changed between manifest hashing and chunk transfer.');
107
+ }
108
+ await unchangedDirectories(prepared);const source=await uploads.finalize({app,uploadId:id},options);if(source?.kind!=='snapshot'||source.digest!==prepared.sourceDigest)throw sourceError('SOURCE_UPLOAD_PROTOCOL_INVALID','Server did not confirm the exact captured source digest.');return source;
109
+ }catch(error){if(id){error.uploadId=id;error.message=`Source upload ${id} did not finish. `+error.message;}throw error;}
110
+ }
111
+
112
+ export async function captureAndUploadRepository(directory,{client,app,uploadId,requestOptions={}}={}){
113
+ if(client?.readOnly)throw Object.assign(sourceError('READ_ONLY','This client is read-only.'),{status:403});
114
+ if(requestOptions.dryRun)throw sourceError('INVALID_DRY_RUN_SOURCE','Source upload has no dry-run mode. Supply an already verified source for a dry-run plan.');
115
+ const prepared=await prepareRepositorySource(directory,{signal:requestOptions.signal});
116
+ if(!uploadId&&prepared.totalBytes<=1024*1024){
117
+ let input;try{input=await capturePreparedSource(prepared,{signal:requestOptions.signal});}catch(error){if(!error.sourceProfileLimit)throw error;return uploadPreparedRepository(prepared,{client,app,uploadId,requestOptions});}
118
+ return client.apps.sources.capture({app,...input},requestOptions);
119
+ }
120
+ return uploadPreparedRepository(prepared,{client,app,uploadId,requestOptions});
121
+ }
122
+
123
+ /** The small JSON path enforces the same captured identities as chunk transfer. */
124
+ export async function capturePreparedSource(prepared,{signal}={}){
125
+ if(prepared.totalBytes>1024*1024)throw sourceError('SOURCE_JSON_PROFILE_TOO_LARGE','Use chunk transfer for this source.');
126
+ await unchangedDirectories(prepared);const files=Object.create(null);
127
+ for(const file of prepared.files){const chunks=[];const actual=await readVerified(file,{signal,onChunk:bytes=>{chunks.push(bytes);}});if(actual!==file.digest)throw sourceError('SOURCE_CHANGED','A source file changed between manifest hashing and JSON capture.');files[file.path]={contentBase64:Buffer.concat(chunks,file.sizeBytes).toString('base64')};}
128
+ await unchangedDirectories(prepared);const input={manifest:prepared.manifest,files};
129
+ if(Buffer.byteLength(JSON.stringify(input))>1900000){const error=sourceError('SOURCE_JSON_PROFILE_TOO_LARGE','Source metadata and bytes exceed the JSON capture profile.');error.sourceProfileLimit=true;throw error;}
130
+ return input;
131
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.