| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import { createHash, createHmac, randomUUID } from 'node:crypto';
- import { readFileSync } from 'node:fs';
- import { request } from 'node:https';
- const config = Object.fromEntries(readFileSync('client.env', 'utf8').trimEnd().split('\n').map(line => line.split('=')));
- const env = name => {
- if (!process.env[name]) throw new Error('Set ' + name);
- return process.env[name];
- };
- const base = new URL(process.env.INGRESS_BASE || config.INGRESS_BASE);
- if (base.protocol !== 'https:' || base.username || base.password || base.pathname !== '/' || base.search || base.hash)
- throw new Error('INGRESS_BASE must be an HTTPS origin');
- const [, , action, value] = process.argv;
- if (!value || !['send', 'status'].includes(action))
- throw new Error('Usage: push.mjs send <file> | status <batchId>');
- const send = action === 'send';
- if (!send && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new Error('Invalid batchId');
- const endpoint = config.DATASET_ENDPOINT + (send ? '' : '/batches/' + value.toLowerCase());
- const method = send ? 'POST' : 'GET';
- const body = send ? readFileSync(value) : Buffer.alloc(0);
- const media = send ? (value.toLowerCase().endsWith('.ndjson') ? 'application/x-ndjson' : 'application/json') : '';
- const idem = send ? env('IDEMPOTENCY_KEY') : '';
- const schema = send ? config.SCHEMA_VERSION : '';
- const factory = media === 'application/json' ? '' : config.FACTORY_ID;
- const accessKey = env('ACCESS_KEY');
- const timestamp = Math.floor(Date.now() / 1000).toString();
- const nonce = randomUUID().replaceAll('-', '');
- const digest = createHash('sha256').update(body).digest('hex');
- const version = 'mdp-ingress-hmac-sha256-v2';
- const wire = [version, method, endpoint, accessKey, timestamp, nonce, digest, idem, media, factory, schema].join('&');
- const signature = createHmac('sha256', Buffer.from(env('SIGNING_KEY_BASE64'), 'base64')).update(wire).digest('base64');
- const headers = { 'X-Access-Key': accessKey, 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Content-SHA256': digest,
- 'X-Signature': signature, 'X-Signature-Version': version };
- if (factory) headers['X-Factory-Id'] = factory;
- if (send) Object.assign(headers, { 'Content-Type': media, 'Content-Length': body.length,
- 'Idempotency-Key': idem, 'X-Schema-Version': schema });
- const ca = process.env.INGRESS_CA_FILE ? readFileSync(process.env.INGRESS_CA_FILE) : undefined;
- const pass = request(new URL(endpoint, base), { method, headers, ca, timeout: 30_000 }, response => {
- console.log('HTTP ' + response.statusCode);
- if (response.headers['retry-after']) console.log('Retry-After: ' + response.headers['retry-after']);
- response.pipe(process.stdout);
- if (response.statusCode >= 300) process.exitCode = 1;
- });
- pass.on('timeout', () => pass.destroy(new Error('Request timed out')));
- pass.end(send ? body : undefined);
|