CodeSampleX

샘플

aws4 1.13.2: RequestSigner

검증된 샘플 — npm aws4 1.13.2: RequestSigner. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: RequestSigner initializes request options, credentials…

sha256:e04de4efe6a1aacde99b72daea2496307001b0a66db2873f59549468d7923295

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-05

케이스

HOW
목표
verify aws4.RequestSigner in pkg:npm/aws4@1.13.2
패키지
심벌
  • aws4.RequestSigner
생성일
2026-09-05T19:16:02Z

컨트랙트

  1. RequestSigner initializes request options, credentials, and parses URL strings or host headers
  2. RequestSigner extracts service name and region from standard AWS and custom hostnames
  3. RequestSigner computes canonical request string with sorted query parameters and signed headers
  4. RequestSigner constructs stringToSign with AWS4-HMAC-SHA256 algorithm and credential scope
  5. RequestSigner generates valid 64-character hexadecimal HMAC-SHA256 signature and authorization header
  6. RequestSigner respects extraHeadersToInclude and extraHeadersToIgnore during header canonicalization
  7. RequestSigner prepares and signs presigned query requests without adding Authorization header
  8. RequestSigner supports sessionToken for temporary credentials and doNotModifyHeaders flag

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify aws4.RequestSigner in pkg:npm/aws4@1.13.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/aws4@1.13.2
Demonstrate these symbols/APIs:
  - aws4.RequestSigner

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:65dab7df763b137525b5750f51909b65e5cced98baed899d2c1e5f4fce77319a","contract":["RequestSigner initializes request options, credentials, and parses URL strings or host headers","RequestSigner extracts service name and region from standard AWS and custom hostnames","RequestSigner computes canonical request string with sorted query parameters and signed headers","RequestSigner constructs stringToSign with AWS4-HMAC-SHA256 algorithm and credential scope","RequestSigner generates valid 64-character hexadecimal HMAC-SHA256 signature and authorization header","RequestSigner respects extraHeadersToInclude and extraHeadersToIgnore during header canonicalization","RequestSigner prepares and signs presigned query requests without adding Authorization header","RequestSigner supports sessionToken for temporary credentials and doNotModifyHeaders flag"],"goal":"verify aws4.RequestSigner in pkg:npm/aws4@1.13.2","kind":"HOW","packages":["pkg:npm/aws4@1.13.2"],"schemaVersion":1,"symbols":["aws4.RequestSigner"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/aws4@1.13.2"],"schemaVersion":1,"subject":"pkg:npm/aws4@1.13.2","symbols":["aws4.RequestSigner"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-aws4-request-signer",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-aws4-request-signer",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "aws4": "1.13.2"
      }
    },
    "node_modules/aws4": {
      "version": "1.13.2",
      "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
      "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-aws4-request-signer",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of pkg:npm/aws4@1.13.2 aws4.RequestSigner",
  "main": "src/index.js",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "aws4": "1.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify aws4.RequestSigner in pkg:npm/aws4@1.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/aws4@1.13.2"
  ],
  "symbols": [
    "aws4.RequestSigner"
  ]
}
src/index.js
'use strict';

const aws4 = require('aws4');

/**
 * Creates a RequestSigner instance for custom inspection and step-by-step signing.
 *
 * @param {object|string} request - Request options or URL string.
 * @param {object} [credentials] - AWS credentials.
 * @returns {aws4.RequestSigner} RequestSigner instance.
 */
function createRequestSigner(request, credentials) {
  return new aws4.RequestSigner(request, credentials);
}

/**
 * Prepares the request, parsing path, query, and injecting standard headers.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {aws4.RequestSigner} Same RequestSigner instance.
 */
function prepareRequest(signer) {
  signer.prepareRequest();
  return signer;
}

/**
 * Computes canonical request string from a RequestSigner.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {string} The canonical request string.
 */
function getCanonicalString(signer) {
  return signer.canonicalString();
}

/**
 * Computes the string-to-sign for AWS Signature Version 4.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {string} String to sign.
 */
function getStringToSign(signer) {
  return signer.stringToSign();
}

/**
 * Computes the 64-char hexadecimal HMAC-SHA256 signature.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {string} Hexadecimal signature.
 */
function getSignature(signer) {
  return signer.signature();
}

/**
 * Generates the full Authorization header value.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {string} Authorization header string.
 */
function getAuthHeader(signer) {
  return signer.authHeader();
}

/**
 * Signs the request using the RequestSigner instance.
 *
 * @param {aws4.RequestSigner} signer - RequestSigner instance.
 * @returns {object} Signed request object.
 */
function signWithSigner(signer) {
  return signer.sign();
}

module.exports = {
  aws4,
  RequestSigner: aws4.RequestSigner,
  createRequestSigner,
  prepareRequest,
  getCanonicalString,
  getStringToSign,
  getSignature,
  getAuthHeader,
  signWithSigner,
};
test/contract.mjs
import assert from 'node:assert';
import crypto from 'node:crypto';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const aws4 = require('aws4');
const {
  createRequestSigner,
  prepareRequest,
  getCanonicalString,
  getStringToSign,
  getSignature,
  getAuthHeader,
  signWithSigner,
} = require('../src/index.js');

const dummyCredentials = {
  accessKeyId: 'mock-access-key-id',
  secretAccessKey: 'mock-secret-access-key',
};

async function runContract() {
  // 1. RequestSigner initializes request options, credentials, and parses URL strings or host headers
  const signer1 = createRequestSigner('https://example.com/test-queue', dummyCredentials);
  assert.strictEqual(signer1.request.hostname, 'example.com');
  assert.strictEqual(signer1.request.path, '/test-queue');
  assert.strictEqual(signer1.credentials.accessKeyId, 'mock-access-key-id');
  assert.strictEqual(signer1.credentials.secretAccessKey, 'mock-secret-access-key');

  const signerHost = createRequestSigner({
    host: 'sqs.us-east-2.amazonaws.com',
    path: '/test-queue',
  }, dummyCredentials);
  assert.strictEqual(signerHost.service, 'sqs');
  assert.strictEqual(signerHost.region, 'us-east-2');

  const signerCustom = createRequestSigner({
    host: 'example.com',
    service: 'custom-service',
    region: 'eu-west-1',
  }, dummyCredentials);
  assert.strictEqual(signerCustom.service, 'custom-service');
  assert.strictEqual(signerCustom.region, 'eu-west-1');

  // 2. RequestSigner extracts service name and region from standard AWS and custom hostnames
  const match1 = signer1.matchHost('dynamodb.us-west-2.amazonaws.com');
  assert.strictEqual(match1[0], 'dynamodb');
  assert.strictEqual(match1[1], 'us-west-2');

  const match2 = signer1.matchHost('s3-us-west-2.amazonaws.com');
  assert.strictEqual(match2[0], 's3');
  assert.strictEqual(match2[1], 'us-west-2');

  const match3 = signer1.matchHost('search-cluster.us-east-1.es.amazonaws.com');
  assert.strictEqual(match3[0], 'es');
  assert.strictEqual(match3[1], 'us-east-1');

  const signerSes = createRequestSigner({
    host: 'email.us-east-1.amazonaws.com',
  }, dummyCredentials);
  assert.strictEqual(signerSes.service, 'ses');

  // 3. RequestSigner computes canonical request string with sorted query parameters and signed headers
  const signer3 = createRequestSigner({
    host: 'sqs.us-east-1.amazonaws.com',
    path: '/items?z=last&a=first&m=middle',
    method: 'GET',
    headers: {
      'Date': 'Mon, 09 Sep 2024 00:00:00 GMT',
      'X-Custom-Header': 'custom-value',
      'Accept': 'application/json',
    },
  }, dummyCredentials);
  const canonical = getCanonicalString(signer3);
  const canonicalLines = canonical.split('\n');
  assert.strictEqual(canonicalLines[0], 'GET');
  assert.strictEqual(canonicalLines[1], '/items');
  assert.strictEqual(canonicalLines[2], 'a=first&m=middle&z=last');
  assert.ok(canonical.includes('accept:application/json'));
  assert.ok(canonical.includes('x-custom-header:custom-value'));
  assert.strictEqual(signer3.signedHeaders(), 'accept;date;host;x-amz-date;x-custom-header');
  assert.strictEqual(canonicalLines[canonicalLines.length - 1], 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');

  // 4. RequestSigner constructs stringToSign with AWS4-HMAC-SHA256 algorithm and credential scope
  const sts = getStringToSign(signer3);
  const stsLines = sts.split('\n');
  assert.strictEqual(stsLines[0], 'AWS4-HMAC-SHA256');
  assert.strictEqual(stsLines[1], '20240909T000000Z');
  assert.strictEqual(stsLines[2], '20240909/us-east-1/sqs/aws4_request');
  const expectedHash = crypto.createHash('sha256').update(canonical, 'utf8').digest('hex');
  assert.strictEqual(stsLines[3], expectedHash);

  // 5. RequestSigner generates valid 64-character hexadecimal HMAC-SHA256 signature and authorization header
  const signatureHex = getSignature(signer3);
  assert.match(signatureHex, /^[a-f0-9]{64}$/);
  const authHeader = getAuthHeader(signer3);
  assert.ok(authHeader.startsWith('AWS4-HMAC-SHA256 Credential=mock-access-key-id/20240909/us-east-1/sqs/aws4_request'));
  assert.ok(authHeader.includes('SignedHeaders=accept;date;host;x-amz-date;x-custom-header'));
  assert.ok(authHeader.includes(`Signature=${signatureHex}`));
  const signedReq = signWithSigner(signer3);
  assert.strictEqual(signedReq.headers.Authorization, authHeader);

  // 6. RequestSigner respects extraHeadersToInclude and extraHeadersToIgnore during header canonicalization
  const signer6 = createRequestSigner({
    host: 'example.com',
    service: 'execute-api',
    region: 'us-east-1',
    headers: {
      'User-Agent': 'CustomTestAgent/1.0',
      'X-Excluded': 'skip-me',
      'X-Included': 'keep-me',
    },
    extraHeadersToInclude: { 'user-agent': true },
    extraHeadersToIgnore: { 'x-excluded': true },
  }, dummyCredentials);
  const signedH = signer6.signedHeaders();
  assert.ok(signedH.includes('user-agent'), 'user-agent should be included via extraHeadersToInclude');
  assert.ok(signedH.includes('x-included'), 'x-included should be retained');
  assert.ok(!signedH.includes('x-excluded'), 'x-excluded should be omitted via extraHeadersToIgnore');

  // 7. RequestSigner prepares and signs presigned query requests without adding Authorization header
  const signer7 = createRequestSigner({
    host: 's3.us-east-1.amazonaws.com',
    path: '/my-bucket/test-file.txt',
    service: 's3',
    region: 'us-east-1',
    signQuery: true,
    headers: {
      'Date': 'Mon, 09 Sep 2024 00:00:00 GMT',
    },
  }, dummyCredentials);
  const expectedSig = getSignature(signer7);
  const presigned = signWithSigner(signer7);
  assert.strictEqual(presigned.headers.Authorization, undefined, 'Authorization header must not be set on presigned query');
  assert.ok(presigned.path.includes('X-Amz-Algorithm=AWS4-HMAC-SHA256'));
  assert.ok(presigned.path.includes('X-Amz-Credential=mock-access-key-id%2F20240909%2Fus-east-1%2Fs3%2Faws4_request'));
  assert.ok(presigned.path.includes('X-Amz-Date=20240909T000000Z'));
  assert.ok(presigned.path.includes('X-Amz-SignedHeaders=date%3Bhost'));
  assert.ok(presigned.path.includes(`X-Amz-Signature=${expectedSig}`));

  // 8. RequestSigner supports sessionToken for temporary credentials and doNotModifyHeaders flag
  const signer8 = createRequestSigner({
    host: 'sqs.us-east-1.amazonaws.com',
    path: '/',
    method: 'POST',
    body: '{"Action":"ListQueues"}',
  }, {
    ...dummyCredentials,
    sessionToken: 'mock-session-token',
  });
  prepareRequest(signer8);
  assert.strictEqual(signer8.request.headers['X-Amz-Security-Token'], 'mock-session-token');
  assert.ok(signer8.signedHeaders().includes('x-amz-security-token'));
  assert.strictEqual(signer8.request.headers['Content-Type'], 'application/x-www-form-urlencoded; charset=utf-8');
  assert.strictEqual(signer8.request.headers['Content-Length'], 23);

  const signerNoModify = createRequestSigner({
    host: 'sqs.us-east-1.amazonaws.com',
    path: '/',
    method: 'POST',
    body: '{"Action":"ListQueues"}',
    doNotModifyHeaders: true,
  }, dummyCredentials);
  prepareRequest(signerNoModify);
  assert.strictEqual(signerNoModify.request.headers['Content-Type'], undefined);
  assert.strictEqual(signerNoModify.request.headers['Content-Length'], undefined);

  console.log('Contract tests passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

오리진 시더

익명