@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
110 lines • 5.31 kB
JavaScript
import { createHash, createHmac } from 'node:crypto';
/**
* RFC 3986 percent-encoding as SigV4 defines it: everything except unreserved characters
* (`A–Z a–z 0–9 - _ . ~`) is encoded, with uppercase hex. `encodeURIComponent` is close but leaves
* `!'()*` bare, and any of those in an object key would make the canonical request disagree with
* what S3 reconstructs server-side — a signature mismatch that only bites on the one file whose
* name contains them.
*/
function uriEncode(value) {
return encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
}
/** Encode a path for the canonical URI: each segment percent-encoded, `/` separators preserved. */
function encodePath(path) {
return path.split('/').map(uriEncode).join('/');
}
/** `YYYYMMDD'T'HHMMSS'Z'` — the `X-Amz-Date` format. */
function toAmzDate(date) {
return date
.toISOString()
.replace(/[-:]/g, '')
.replace(/\.\d{3}Z$/, 'Z');
}
function hmac(key, data) {
return createHmac('sha256', key).update(data, 'utf8').digest();
}
function sha256Hex(data) {
return createHash('sha256').update(data, 'utf8').digest('hex');
}
/** Bound on {@link signingKeys}: a handful of (credential, day, region, service) scopes are live at once. */
const SIGNING_KEY_CACHE_SIZE = 16;
/**
* Derived SigV4 signing keys, most recently used last. A key depends only on the secret and the
* scope (day, region, service), so every URL signed in the same scope reuses one derivation instead
* of chaining four HMACs per URL.
*/
const signingKeys = new Map();
function deriveSigningKey(secret, dateStamp, region, service) {
const cacheKey = `${secret}\n${dateStamp}\n${region}\n${service}`;
const cached = signingKeys.get(cacheKey);
if (cached) {
signingKeys.delete(cacheKey);
signingKeys.set(cacheKey, cached);
return cached;
}
const key = hmac(hmac(hmac(hmac(`AWS4${secret}`, dateStamp), region), service), 'aws4_request');
signingKeys.set(cacheKey, key);
if (signingKeys.size > SIGNING_KEY_CACHE_SIZE) {
signingKeys.delete(signingKeys.keys().next().value);
}
return key;
}
/**
* Presign an S3 request with AWS Signature Version 4 **query-string authentication** — the
* credential, timestamp, TTL and signature all travel as `X-Amz-*` query parameters, so the URL is
* self-contained and anyone holding it (a browser `PUT`ting a multipart part, a `<video>` tag
* streaming a segment) can perform exactly this one request until it expires.
*
* Hand-rolled on `node:crypto` — ~60 lines of HMAC chaining — instead of pulling in
* `@aws-sdk/s3-request-presigner`: presigning is pure computation (no round-trip to S3), and owning
* it lets the signature target ANY host. That is what makes a split internal/public endpoint
* trivial: SigV4 signs the `Host` header, so a URL signed for the internal endpoint is invalid on
* the public one — with the SDK that means constructing a second client per endpoint, here it is
* just a different `host` argument.
*
* The payload is declared `UNSIGNED-PAYLOAD`, the standard for presigned S3 URLs: the body cannot
* be known at signing time (the client hasn't produced it yet), and S3 accepts the literal in the
* canonical request for query-auth.
*
* Verified against AWS's published SigV4 test vector (the documented `examplebucket` presigned GET)
* in `test/sigv4.spec.ts`.
*/
export function presignS3Url(input) {
const service = input.service ?? 's3';
const now = input.now ?? new Date();
const amzDate = toAmzDate(now);
const dateStamp = amzDate.slice(0, 8);
const scope = `${dateStamp}/${input.region}/${service}/aws4_request`;
const query = {
...input.query,
'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
'X-Amz-Credential': `${input.credentials.accessKeyId}/${scope}`,
'X-Amz-Date': amzDate,
'X-Amz-Expires': String(Math.max(1, Math.round(input.expiresInSeconds))),
'X-Amz-SignedHeaders': 'host',
...(input.credentials.sessionToken !== undefined
? { 'X-Amz-Security-Token': input.credentials.sessionToken }
: {}),
};
// Canonical query string: pairs encoded first, then sorted BY THE ENCODED bytes — the order S3
// reconstructs on its side.
const canonicalQuery = Object.entries(query)
.map(([name, value]) => [uriEncode(name), uriEncode(value)])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([name, value]) => `${name}=${value}`)
.join('&');
const canonicalPath = encodePath(input.path);
const canonicalRequest = [
input.method.toUpperCase(),
canonicalPath,
canonicalQuery,
`host:${input.host}\n`,
'host',
'UNSIGNED-PAYLOAD',
].join('\n');
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n');
const signingKey = deriveSigningKey(input.credentials.secretAccessKey, dateStamp, input.region, service);
const signature = createHmac('sha256', signingKey).update(stringToSign, 'utf8').digest('hex');
return `${input.protocol}//${input.host}${canonicalPath}?${canonicalQuery}&X-Amz-Signature=${signature}`;
}
//# sourceMappingURL=sigv4.js.map