CodeSampleX

Exemple

aws4 1.13.2: RequestSigner

Échantillon vérifié pour npm aws4 1.13.2: RequestSigner. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:e04de4efe6a1aacde99b72daea2496307001b0a66db2873f59549468d7923295

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify aws4.RequestSigner in pkg:npm/aws4@1.13.2
Paquets
Symboles
  • aws4.RequestSigner
Créé
2026-09-05T19:16:02Z

Contrat

  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

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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);
});

Seeder d'origine

anonyme