Skip to content

Commit

Permalink
build
Browse files Browse the repository at this point in the history
  • Loading branch information
tamaina committed Mar 8, 2024
1 parent 4f1aad4 commit 0d08a83
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 47 deletions.
1 change: 1 addition & 0 deletions dist/const.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const textEncoder: TextEncoder;
4 changes: 2 additions & 2 deletions dist/digest/digest-rfc3230.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DigestSource } from './utils';
import { DigestHashAlgorithm, IncomingRequest } from '../types';
import { DigestSource } from './utils.js';
import { DigestHashAlgorithm, IncomingRequest } from '../types.js';
export declare function genRFC3230DigestHeader(body: DigestSource, hashAlgorithm: DigestHashAlgorithm): Promise<string>;
export declare const digestHeaderRegEx: RegExp;
export declare function verifyRFC3230DigestHeader(request: IncomingRequest, rawBody: DigestSource, failOnNoDigest?: boolean, errorLogger?: ((message: any) => any)): Promise<boolean>;
4 changes: 2 additions & 2 deletions dist/digest/digest.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { IncomingRequest } from "../types";
import { DigestSource } from "./utils";
import { IncomingRequest } from "../types.js";
import { DigestSource } from "./utils.js";
export declare function verifyDigestHeader(request: IncomingRequest, rawBody: DigestSource, failOnNoDigest?: boolean, errorLogger?: ((message: any) => any)): Promise<boolean>;
2 changes: 1 addition & 1 deletion dist/digest/utils.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { DigestHashAlgorithm } from '../types';
import { DigestHashAlgorithm } from '../types.js';
export type DigestSource = BufferSource | string;
export declare function createBase64Digest(body: DigestSource, hash?: DigestHashAlgorithm): Promise<ArrayBuffer>;
4 changes: 2 additions & 2 deletions dist/draft/verify.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ParsedDraftSignature } from "../types";
import { parseSignInfo } from "../shared/verify";
import { ParsedDraftSignature } from "../types.js";
import { parseSignInfo } from "../shared/verify.js";
/**
* @deprecated Use `parseSignInfo`
*/
Expand Down
53 changes: 36 additions & 17 deletions dist/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ __export(src_exports, {
decodePem: () => decodePem,
defaultSignInfoDefaults: () => defaultSignInfoDefaults,
digestHeaderRegEx: () => digestHeaderRegEx,
encodeArrayBufferToBase64NonRFC4648: () => encodeArrayBufferToBase64NonRFC4648,
encodeArrayBufferToBase64: () => encodeArrayBufferToBase64,
exportPrivateKeyPem: () => exportPrivateKeyPem,
exportPublicKeyPem: () => exportPublicKeyPem,
genASN1Length: () => genASN1Length,
Expand Down Expand Up @@ -973,6 +973,7 @@ async function parseAndImportPublicKey(source, keyUsages = ["verify"], providedA
}

// src/utils.ts
var import_rfc4648 = require("rfc4648");
async function getWebcrypto() {
return globalThis.crypto ?? (await import("node:crypto")).webcrypto;
}
Expand Down Expand Up @@ -1091,15 +1092,18 @@ function genASN1Length(length) {
const lengthUint8Array = numberToUint8Array(length);
return new Uint8Array([128 + lengthUint8Array.length, ...lengthUint8Array]);
}
function encodeArrayBufferToBase64NonRFC4648(buffer) {
function encodeArrayBufferToBase64(buffer) {
const uint8Array = new Uint8Array(buffer);
const binary = String.fromCharCode(...uint8Array);
return btoa(binary);
return import_rfc4648.base64.stringify(uint8Array);
}
function compareUint8Array(a, b) {
if (a.length !== b.length)
return false;
return a.every((v, i) => v === b[i]);
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
var KeyValidationError = class extends Error {
constructor(message) {
Expand Down Expand Up @@ -1193,6 +1197,9 @@ async function importPrivateKey(key, keyUsages = ["sign"], defaults = defaultSig
return await (await getWebcrypto()).subtle.importKey("pkcs8", parsedPrivateKey.der, importParams, extractable, keyUsages);
}

// src/const.ts
var textEncoder = new TextEncoder();

// src/draft/sign.ts
function getDraftAlgoString(keyAlgorithm, hashAlgorithm) {
const verifyHash = () => {
Expand Down Expand Up @@ -1254,8 +1261,8 @@ function genDraftSigningString(source, includeHeaders, additional) {
return results.join("\n");
}
async function genDraftSignature(privateKey, signingString, defaults = defaultSignInfoDefaults) {
const signatureAB = await (await getWebcrypto()).subtle.sign(genAlgorithmForSignAndVerify(privateKey.algorithm, defaults.hash), privateKey, new TextEncoder().encode(signingString));
return encodeArrayBufferToBase64NonRFC4648(signatureAB);
const signatureAB = await (await getWebcrypto()).subtle.sign(genAlgorithmForSignAndVerify(privateKey.algorithm, defaults.hash), privateKey, textEncoder.encode(signingString));
return encodeArrayBufferToBase64(signatureAB);
}
function genDraftSignatureHeader(includeHeaders, keyId, signature, algorithm) {
return `keyId="${keyId}",algorithm="${algorithm}",headers="${includeHeaders.join(" ")}",signature="${signature}"`;
Expand Down Expand Up @@ -1519,11 +1526,11 @@ function parseRequestSignature(request, options) {
// src/keypair.ts
async function exportPublicKeyPem(key) {
const ab = await (await getWebcrypto()).subtle.exportKey("spki", key);
return "-----BEGIN PUBLIC KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64NonRFC4648(ab)).join("\n") + "\n-----END PUBLIC KEY-----\n";
return "-----BEGIN PUBLIC KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64(ab)).join("\n") + "\n-----END PUBLIC KEY-----\n";
}
async function exportPrivateKeyPem(key) {
const ab = await (await getWebcrypto()).subtle.exportKey("pkcs8", key);
return "-----BEGIN PRIVATE KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64NonRFC4648(ab)).join("\n") + "\n-----END PRIVATE KEY-----\n";
return "-----BEGIN PRIVATE KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64(ab)).join("\n") + "\n-----END PRIVATE KEY-----\n";
}
async function genRsaKeyPair(modulusLength = 4096, keyUsage = ["sign", "verify"]) {
const keyPair = await (await getWebcrypto()).subtle.generateKey(
Expand Down Expand Up @@ -1588,15 +1595,15 @@ async function createBase64Digest(body, hash = "SHA-256") {
hash = "SHA-1";
}
if (typeof body === "string") {
body = new TextEncoder().encode(body);
body = textEncoder.encode(body);
}
return await (await getWebcrypto()).subtle.digest(hash, body);
}

// src/digest/digest-rfc3230.ts
var import_rfc4648 = require("rfc4648");
var import_rfc46482 = require("rfc4648");
async function genRFC3230DigestHeader(body, hashAlgorithm) {
return `${hashAlgorithm}=${await createBase64Digest(body, hashAlgorithm).then(encodeArrayBufferToBase64NonRFC4648)}`;
return `${hashAlgorithm}=${await createBase64Digest(body, hashAlgorithm).then(encodeArrayBufferToBase64)}`;
}
var digestHeaderRegEx = /^([a-zA-Z0-9\-]+)=([^\,]+)/;
async function verifyRFC3230DigestHeader(request, rawBody, failOnNoDigest = true, errorLogger) {
Expand All @@ -1620,7 +1627,7 @@ async function verifyRFC3230DigestHeader(request, rawBody, failOnNoDigest = true
errorLogger("Invalid Digest header format");
return false;
}
const value = import_rfc4648.base64.parse(match[2]);
const value = import_rfc46482.base64.parse(match[2]);
const algo = match[1];
if (!algo) {
if (errorLogger)
Expand Down Expand Up @@ -1663,12 +1670,12 @@ async function verifyDigestHeader(request, rawBody, failOnNoDigest = true, error
}

// src/draft/verify.ts
var import_rfc46482 = require("rfc4648");
var import_rfc46483 = require("rfc4648");
var genSignInfoDraft = parseSignInfo;
async function verifyDraftSignature(parsed, key, errorLogger) {
try {
const { publicKey, algorithm } = await parseAndImportPublicKey(key, ["verify"], parsed.algorithm);
const verify = await (await getWebcrypto()).subtle.verify(algorithm, publicKey, import_rfc46482.base64.parse(parsed.params.signature), new TextEncoder().encode(parsed.signingString));
const verify = await (await getWebcrypto()).subtle.verify(algorithm, publicKey, import_rfc46483.base64.parse(parsed.params.signature), textEncoder.encode(parsed.signingString));
if (verify !== true)
throw new Error(`verification simply failed, result: ${verify}`);
return verify;
Expand Down Expand Up @@ -1910,7 +1917,19 @@ var RFC9421SignatureBaseFactory = class _RFC9421SignatureBaseFactory {
}
}
if (isBs) {
const sequences = (Array.isArray(rawValue) ? rawValue : [rawValue]).map((x) => canonicalizeHeaderValue(x)).map((x) => new TextEncoder().encode(x)).map((x) => encodeArrayBufferToBase64NonRFC4648(x.buffer)).map((x) => new sh.ByteSequence(x)).map((x) => [x, /* @__PURE__ */ new Map()]);
const sequences = (Array.isArray(rawValue) ? rawValue : [rawValue]).map((x) => {
if (typeof x !== "string") {
throw new Error(`Invalid header value type: ${typeof x}`);
}
return [
new sh.ByteSequence(
encodeArrayBufferToBase64(
textEncoder.encode(canonicalizeHeaderValue(x)).buffer
)
),
/* @__PURE__ */ new Map()
];
});
return sh.serializeList(sequences);
}
return canonicalizeHeaderValue(rawValue);
Expand Down Expand Up @@ -1971,7 +1990,7 @@ var RFC9421SignatureBaseFactory = class _RFC9421SignatureBaseFactory {
decodePem,
defaultSignInfoDefaults,
digestHeaderRegEx,
encodeArrayBufferToBase64NonRFC4648,
encodeArrayBufferToBase64,
exportPrivateKeyPem,
exportPublicKeyPem,
genASN1Length,
Expand Down
51 changes: 35 additions & 16 deletions dist/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,7 @@ async function parseAndImportPublicKey(source, keyUsages = ["verify"], providedA
}

// src/utils.ts
import { base64 } from "rfc4648";
async function getWebcrypto() {
return globalThis.crypto ?? (await import("node:crypto")).webcrypto;
}
Expand Down Expand Up @@ -998,15 +999,18 @@ function genASN1Length(length) {
const lengthUint8Array = numberToUint8Array(length);
return new Uint8Array([128 + lengthUint8Array.length, ...lengthUint8Array]);
}
function encodeArrayBufferToBase64NonRFC4648(buffer) {
function encodeArrayBufferToBase64(buffer) {
const uint8Array = new Uint8Array(buffer);
const binary = String.fromCharCode(...uint8Array);
return btoa(binary);
return base64.stringify(uint8Array);
}
function compareUint8Array(a, b) {
if (a.length !== b.length)
return false;
return a.every((v, i) => v === b[i]);
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
var KeyValidationError = class extends Error {
constructor(message) {
Expand Down Expand Up @@ -1100,6 +1104,9 @@ async function importPrivateKey(key, keyUsages = ["sign"], defaults = defaultSig
return await (await getWebcrypto()).subtle.importKey("pkcs8", parsedPrivateKey.der, importParams, extractable, keyUsages);
}

// src/const.ts
var textEncoder = new TextEncoder();

// src/draft/sign.ts
function getDraftAlgoString(keyAlgorithm, hashAlgorithm) {
const verifyHash = () => {
Expand Down Expand Up @@ -1161,8 +1168,8 @@ function genDraftSigningString(source, includeHeaders, additional) {
return results.join("\n");
}
async function genDraftSignature(privateKey, signingString, defaults = defaultSignInfoDefaults) {
const signatureAB = await (await getWebcrypto()).subtle.sign(genAlgorithmForSignAndVerify(privateKey.algorithm, defaults.hash), privateKey, new TextEncoder().encode(signingString));
return encodeArrayBufferToBase64NonRFC4648(signatureAB);
const signatureAB = await (await getWebcrypto()).subtle.sign(genAlgorithmForSignAndVerify(privateKey.algorithm, defaults.hash), privateKey, textEncoder.encode(signingString));
return encodeArrayBufferToBase64(signatureAB);
}
function genDraftSignatureHeader(includeHeaders, keyId, signature, algorithm) {
return `keyId="${keyId}",algorithm="${algorithm}",headers="${includeHeaders.join(" ")}",signature="${signature}"`;
Expand Down Expand Up @@ -1426,11 +1433,11 @@ function parseRequestSignature(request, options) {
// src/keypair.ts
async function exportPublicKeyPem(key) {
const ab = await (await getWebcrypto()).subtle.exportKey("spki", key);
return "-----BEGIN PUBLIC KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64NonRFC4648(ab)).join("\n") + "\n-----END PUBLIC KEY-----\n";
return "-----BEGIN PUBLIC KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64(ab)).join("\n") + "\n-----END PUBLIC KEY-----\n";
}
async function exportPrivateKeyPem(key) {
const ab = await (await getWebcrypto()).subtle.exportKey("pkcs8", key);
return "-----BEGIN PRIVATE KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64NonRFC4648(ab)).join("\n") + "\n-----END PRIVATE KEY-----\n";
return "-----BEGIN PRIVATE KEY-----\n" + splitPer64Chars(encodeArrayBufferToBase64(ab)).join("\n") + "\n-----END PRIVATE KEY-----\n";
}
async function genRsaKeyPair(modulusLength = 4096, keyUsage = ["sign", "verify"]) {
const keyPair = await (await getWebcrypto()).subtle.generateKey(
Expand Down Expand Up @@ -1495,15 +1502,15 @@ async function createBase64Digest(body, hash = "SHA-256") {
hash = "SHA-1";
}
if (typeof body === "string") {
body = new TextEncoder().encode(body);
body = textEncoder.encode(body);
}
return await (await getWebcrypto()).subtle.digest(hash, body);
}

// src/digest/digest-rfc3230.ts
import { base64 } from "rfc4648";
import { base64 as base642 } from "rfc4648";
async function genRFC3230DigestHeader(body, hashAlgorithm) {
return `${hashAlgorithm}=${await createBase64Digest(body, hashAlgorithm).then(encodeArrayBufferToBase64NonRFC4648)}`;
return `${hashAlgorithm}=${await createBase64Digest(body, hashAlgorithm).then(encodeArrayBufferToBase64)}`;
}
var digestHeaderRegEx = /^([a-zA-Z0-9\-]+)=([^\,]+)/;
async function verifyRFC3230DigestHeader(request, rawBody, failOnNoDigest = true, errorLogger) {
Expand All @@ -1527,7 +1534,7 @@ async function verifyRFC3230DigestHeader(request, rawBody, failOnNoDigest = true
errorLogger("Invalid Digest header format");
return false;
}
const value = base64.parse(match[2]);
const value = base642.parse(match[2]);
const algo = match[1];
if (!algo) {
if (errorLogger)
Expand Down Expand Up @@ -1570,12 +1577,12 @@ async function verifyDigestHeader(request, rawBody, failOnNoDigest = true, error
}

// src/draft/verify.ts
import { base64 as base642 } from "rfc4648";
import { base64 as base643 } from "rfc4648";
var genSignInfoDraft = parseSignInfo;
async function verifyDraftSignature(parsed, key, errorLogger) {
try {
const { publicKey, algorithm } = await parseAndImportPublicKey(key, ["verify"], parsed.algorithm);
const verify = await (await getWebcrypto()).subtle.verify(algorithm, publicKey, base642.parse(parsed.params.signature), new TextEncoder().encode(parsed.signingString));
const verify = await (await getWebcrypto()).subtle.verify(algorithm, publicKey, base643.parse(parsed.params.signature), textEncoder.encode(parsed.signingString));
if (verify !== true)
throw new Error(`verification simply failed, result: ${verify}`);
return verify;
Expand Down Expand Up @@ -1817,7 +1824,19 @@ var RFC9421SignatureBaseFactory = class _RFC9421SignatureBaseFactory {
}
}
if (isBs) {
const sequences = (Array.isArray(rawValue) ? rawValue : [rawValue]).map((x) => canonicalizeHeaderValue(x)).map((x) => new TextEncoder().encode(x)).map((x) => encodeArrayBufferToBase64NonRFC4648(x.buffer)).map((x) => new sh.ByteSequence(x)).map((x) => [x, /* @__PURE__ */ new Map()]);
const sequences = (Array.isArray(rawValue) ? rawValue : [rawValue]).map((x) => {
if (typeof x !== "string") {
throw new Error(`Invalid header value type: ${typeof x}`);
}
return [
new sh.ByteSequence(
encodeArrayBufferToBase64(
textEncoder.encode(canonicalizeHeaderValue(x)).buffer
)
),
/* @__PURE__ */ new Map()
];
});
return sh.serializeList(sequences);
}
return canonicalizeHeaderValue(rawValue);
Expand Down Expand Up @@ -1877,7 +1896,7 @@ export {
decodePem,
defaultSignInfoDefaults,
digestHeaderRegEx,
encodeArrayBufferToBase64NonRFC4648,
encodeArrayBufferToBase64,
exportPrivateKeyPem,
exportPublicKeyPem,
genASN1Length,
Expand Down
2 changes: 1 addition & 1 deletion dist/keypair.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ECNamedCurve } from './types';
import type { ECNamedCurve } from './types.js';
export declare function exportPublicKeyPem(key: CryptoKey): Promise<string>;
export declare function exportPrivateKeyPem(key: CryptoKey): Promise<string>;
export declare function genRsaKeyPair(modulusLength?: number, keyUsage?: KeyUsage[]): Promise<{
Expand Down
6 changes: 3 additions & 3 deletions dist/pem/spki.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ASN1 from '@lapo/asn1js';
import { ECNamedCurve, KeyAlgorithmName } from '../types';
import { SignInfoDefaults } from '../utils';
import { ECNamedCurve, KeyAlgorithmName } from '../types.js';
import { SignInfoDefaults } from '../utils.js';
export declare class SpkiParseError extends Error {
constructor(message: string);
}
Expand Down Expand Up @@ -112,6 +112,6 @@ export declare function parseAndImportPublicKey(source: ASN1.StreamOrBinary | Cr
publicKey: CryptoKey;
algorithm: {
name: string;
hash: import("../types").SignatureHashAlgorithmUpperSnake;
hash: import("../types.js").SignatureHashAlgorithmUpperSnake;
};
}>;
4 changes: 2 additions & 2 deletions dist/rfc9421/sign.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { IncomingRequest, MapLikeObj, OutgoingResponse, SFVSignatureInputDictionary, SFVSignatureInputDictionaryForInput, HeadersLike } from "../types";
import { SFVHeaderTypeDictionary } from "./const";
import type { IncomingRequest, MapLikeObj, OutgoingResponse, SFVSignatureInputDictionary, SFVSignatureInputDictionaryForInput, HeadersLike } from "../types.js";
import { SFVHeaderTypeDictionary } from "./const.js";
export declare const requestTargetDerivedComponents: string[];
export declare const responseTargetDerivedComponents: string[];
export type Kot<T> = keyof T extends 'req' ? T : null;
Expand Down
2 changes: 1 addition & 1 deletion dist/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export declare function genASN1Length(length: number | bigint): Uint8Array;
/**
* ArrayBuffer to base64
*/
export declare function encodeArrayBufferToBase64NonRFC4648(buffer: ArrayBuffer): string;
export declare function encodeArrayBufferToBase64(buffer: ArrayBuffer): string;
export declare function compareUint8Array(a: Uint8Array, b: Uint8Array): boolean;
export declare class KeyValidationError extends Error {
constructor(message: string);
Expand Down

0 comments on commit 0d08a83

Please sign in to comment.