@vouchington/server-utils 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +56 -2
  3. package/dist/api-errors.d.mts +29 -0
  4. package/dist/api-errors.mjs +95 -0
  5. package/dist/child-process-error.d.mts +13 -0
  6. package/dist/child-process-error.mjs +19 -0
  7. package/dist/child-process-process.d.mts +30 -0
  8. package/dist/child-process-process.mjs +135 -0
  9. package/dist/child-process-run.d.mts +18 -0
  10. package/dist/child-process-run.mjs +132 -0
  11. package/dist/child-process.d.mts +2 -0
  12. package/dist/child-process.mjs +1 -0
  13. package/dist/error-tree.d.mts +8 -0
  14. package/dist/error-tree.mjs +94 -0
  15. package/dist/graceful-shutdown-one-off.d.mts +15 -0
  16. package/dist/graceful-shutdown-one-off.mjs +20 -0
  17. package/dist/graceful-shutdown-registry.d.mts +27 -0
  18. package/dist/graceful-shutdown-registry.mjs +29 -0
  19. package/dist/graceful-shutdown-run.d.mts +32 -0
  20. package/dist/graceful-shutdown-run.mjs +61 -0
  21. package/dist/graceful-shutdown.d.mts +3 -0
  22. package/dist/graceful-shutdown.mjs +3 -0
  23. package/dist/http-signatures-digest.d.mts +3 -0
  24. package/dist/http-signatures-digest.mjs +20 -0
  25. package/dist/http-signatures-keys.d.mts +7 -0
  26. package/dist/http-signatures-keys.mjs +27 -0
  27. package/dist/http-signatures-sign.d.mts +17 -0
  28. package/dist/http-signatures-sign.mjs +35 -0
  29. package/dist/http-signatures-string.d.mts +12 -0
  30. package/dist/http-signatures-string.mjs +40 -0
  31. package/dist/http-signatures-verify.d.mts +21 -0
  32. package/dist/http-signatures-verify.mjs +88 -0
  33. package/dist/http-signatures.d.mts +4 -0
  34. package/dist/http-signatures.mjs +4 -0
  35. package/dist/jsonl-partition-writer.d.mts +20 -0
  36. package/dist/jsonl-partition-writer.mjs +86 -0
  37. package/dist/token-secrets.d.mts +14 -0
  38. package/dist/token-secrets.mjs +102 -0
  39. package/dist/url-signing-hosts.d.mts +18 -0
  40. package/dist/url-signing-hosts.mjs +61 -0
  41. package/dist/url-signing-keys.d.mts +23 -0
  42. package/dist/url-signing-keys.mjs +66 -0
  43. package/dist/url-signing-proxy.d.mts +19 -0
  44. package/dist/url-signing-proxy.mjs +36 -0
  45. package/dist/url-signing.d.mts +3 -0
  46. package/dist/url-signing.mjs +3 -0
  47. package/dist/web-push-vapid.d.mts +26 -0
  48. package/dist/web-push-vapid.mjs +107 -0
  49. package/package.json +72 -3
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Closes resources for a short-lived command. A timer force-exits with code 1 if the close never
3
+ * settles; once it settles the timer is unref'd, so only a leaked handle can still trigger it.
4
+ * Throws an `AggregateError` when any close failed.
5
+ */
6
+ export async function shutdownForOneOffCommand(options) {
7
+ const proc = options.process ?? process;
8
+ const forceExitTimer = setTimeout(() => {
9
+ options.logError?.('One-off shutdown: process did not terminate in time, forcing exit...');
10
+ proc.exit(1);
11
+ }, options.gracePeriodMs);
12
+ try {
13
+ const errors = await options.close();
14
+ if (errors.length > 0)
15
+ throw new AggregateError(errors, 'One-off shutdown failed');
16
+ }
17
+ finally {
18
+ forceExitTimer.unref();
19
+ }
20
+ }
@@ -0,0 +1,27 @@
1
+ export type ResourceShutdown = () => Promise<void>;
2
+ export interface ShutdownRegistryOptions {
3
+ /** Receives one success line per resource that closed. */
4
+ log?: (...args: unknown[]) => void;
5
+ /** Builds the success line for a resource name. */
6
+ successMessage?: (name: string) => string;
7
+ }
8
+ export interface CloseOverrides {
9
+ /** Per-call replacements keyed by resource name; registered owners are left unchanged. */
10
+ shutdowns?: Readonly<Record<string, ResourceShutdown>>;
11
+ /** Replaces the registry logger for this call. */
12
+ log?: (...args: unknown[]) => void;
13
+ }
14
+ export interface ShutdownRegistry {
15
+ /** Registers the shutdown for `name`; the latest registration wins. */
16
+ register: (name: string, shutdown: ResourceShutdown) => void;
17
+ /**
18
+ * Runs every registered shutdown (plus overrides) concurrently, so one failure never skips the
19
+ * others. Returns the failures instead of throwing.
20
+ */
21
+ close: (overrides?: CloseOverrides) => Promise<Error[]>;
22
+ }
23
+ /**
24
+ * A late-binding registry for resources (connections, pools) whose owners register a shutdown at
25
+ * module load, so the shutdown coordinator needs no import of them and creates no dependency cycle.
26
+ */
27
+ export declare function createShutdownRegistry(options?: ShutdownRegistryOptions): ShutdownRegistry;
@@ -0,0 +1,29 @@
1
+ const toError = (reason) => reason instanceof Error ? reason : new Error(String(reason));
2
+ /**
3
+ * A late-binding registry for resources (connections, pools) whose owners register a shutdown at
4
+ * module load, so the shutdown coordinator needs no import of them and creates no dependency cycle.
5
+ */
6
+ export function createShutdownRegistry(options = {}) {
7
+ const registered = new Map();
8
+ const successMessage = options.successMessage ?? ((name) => `Graceful Shutdown: ${name} closed.`);
9
+ return {
10
+ register(name, shutdown) {
11
+ registered.set(name, shutdown);
12
+ },
13
+ async close(overrides = {}) {
14
+ const log = overrides.log ?? options.log;
15
+ const shutdowns = new Map([...registered, ...Object.entries(overrides.shutdowns ?? {})]);
16
+ const names = [...shutdowns.keys()];
17
+ // Promise.resolve().then also turns a synchronous throw into a rejection.
18
+ const results = await Promise.allSettled(names.map((name) => Promise.resolve().then(shutdowns.get(name))));
19
+ const errors = [];
20
+ results.forEach((result, index) => {
21
+ if (result.status === 'rejected')
22
+ errors.push(toError(result.reason));
23
+ else
24
+ log?.(successMessage(names[index]));
25
+ });
26
+ return errors;
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,32 @@
1
+ export interface GracefulShutdownProcess {
2
+ on: (signal: NodeJS.Signals, listener: () => void) => unknown;
3
+ exit: (code?: number) => unknown;
4
+ }
5
+ export interface GracefulShutdownOptions {
6
+ /** Grace period before the force-exit fallback fires. */
7
+ gracePeriodMs: number;
8
+ /** Receives callback failures; one failing callback never skips the others. */
9
+ onError: (error: Error) => void;
10
+ /** Final phase after callbacks and drain callbacks, e.g. closing shared connections. */
11
+ closeResources?: () => Promise<unknown>;
12
+ /** Runs after `closeResources`, e.g. flushing buffered error reports. */
13
+ flush?: () => Promise<unknown>;
14
+ log?: (...args: unknown[]) => void;
15
+ /** Called with the failure text when the fallback fires before shutdown finished. */
16
+ logError?: (...args: unknown[]) => void;
17
+ /** Defaults to the global `process`. */
18
+ process?: GracefulShutdownProcess;
19
+ /** Set false (for example under test) to skip the force-exit timer. Defaults to true. */
20
+ forceExit?: boolean;
21
+ }
22
+ export interface GracefulShutdown {
23
+ /** Registers a callback for the first phase; returns the callback count. */
24
+ addCallback: (callback: () => Promise<void>) => number;
25
+ /** Registers a callback for the second phase, after every first-phase callback settled. */
26
+ addDrainCallback: (callback: () => Promise<void>) => number;
27
+ /** Runs once: callbacks, drain callbacks, `closeResources`, then `flush`. Later calls no-op. */
28
+ shutdown: (signal: string) => Promise<void>;
29
+ /** Installs `shutdown` as the listener for each signal (default SIGTERM and SIGINT). */
30
+ installSignalHandlers: (signals?: readonly NodeJS.Signals[]) => void;
31
+ }
32
+ export declare function createGracefulShutdown(options: GracefulShutdownOptions): GracefulShutdown;
@@ -0,0 +1,61 @@
1
+ export function createGracefulShutdown(options) {
2
+ const callbacks = [];
3
+ const drainCallbacks = [];
4
+ const proc = options.process ?? process;
5
+ let shuttingDown = false;
6
+ const runAll = (list) => Promise.all(list.map((callback) =>
7
+ // The then-wrapper routes a synchronous throw from `callback` into the catch handler.
8
+ // oxlint-disable-next-line promise/no-callback-in-promise
9
+ Promise.resolve()
10
+ .then(callback)
11
+ .catch((error) => {
12
+ options.onError(error instanceof Error ? error : new Error(String(error)));
13
+ })));
14
+ async function shutdown(signal) {
15
+ if (shuttingDown)
16
+ return;
17
+ shuttingDown = true;
18
+ options.log?.(`Graceful Shutdown: received ${signal} signal, shutting down...`);
19
+ let succeeded = false;
20
+ // Fallback for handles that keep the loop alive after cleanup. Unref'd so a natural exit
21
+ // wins; exit code 0 when shutdown succeeded, 1 when the grace period ran out.
22
+ if (options.forceExit !== false) {
23
+ setTimeout(() => {
24
+ if (!succeeded)
25
+ options.logError?.('Graceful Shutdown: could not close in time, forcing exit...');
26
+ proc.exit(succeeded ? 0 : 1);
27
+ }, options.gracePeriodMs).unref();
28
+ }
29
+ await runAll(callbacks);
30
+ options.log?.('Graceful Shutdown: all callbacks completed.');
31
+ await runAll(drainCallbacks);
32
+ options.log?.('Graceful Shutdown: drain phase completed.');
33
+ // A failing close is reported and must not skip the final flush.
34
+ const closed = await attempt(options.closeResources);
35
+ const flushed = await attempt(options.flush);
36
+ if (!closed || !flushed)
37
+ return;
38
+ options.log?.('Graceful Shutdown: all connections closed.');
39
+ succeeded = true;
40
+ }
41
+ async function attempt(step) {
42
+ try {
43
+ await step?.();
44
+ return true;
45
+ }
46
+ catch (error) {
47
+ options.onError(error instanceof Error ? error : new Error(String(error)));
48
+ return false;
49
+ }
50
+ }
51
+ return {
52
+ addCallback: (callback) => callbacks.push(callback),
53
+ addDrainCallback: (callback) => drainCallbacks.push(callback),
54
+ shutdown,
55
+ installSignalHandlers(signals = ['SIGTERM', 'SIGINT']) {
56
+ // `shutdown` reports its own step failures through `onError`, so it does not reject.
57
+ for (const signal of signals)
58
+ proc.on(signal, () => void shutdown(signal));
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,3 @@
1
+ export { createGracefulShutdown, type GracefulShutdown, type GracefulShutdownOptions, type GracefulShutdownProcess, } from './graceful-shutdown-run.mts';
2
+ export { shutdownForOneOffCommand, type OneOffShutdownOptions, } from './graceful-shutdown-one-off.mts';
3
+ export { createShutdownRegistry, type CloseOverrides, type ResourceShutdown, type ShutdownRegistry, type ShutdownRegistryOptions, } from './graceful-shutdown-registry.mts';
@@ -0,0 +1,3 @@
1
+ export { createGracefulShutdown, } from './graceful-shutdown-run.mjs';
2
+ export { shutdownForOneOffCommand, } from './graceful-shutdown-one-off.mjs';
3
+ export { createShutdownRegistry, } from './graceful-shutdown-registry.mjs';
@@ -0,0 +1,3 @@
1
+ export declare function computeDigest(body: string | Buffer): string;
2
+ export declare function extractDigestHash(digestHeader: string): string;
3
+ export declare function verifyDigest(body: string | Buffer, expectedDigestHeader: string): boolean;
@@ -0,0 +1,20 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ const DIGEST_HEADER_PATTERN = /^SHA-256=(.+)$/;
3
+ export function computeDigest(body) {
4
+ const bodyBuffer = typeof body === 'string' ? Buffer.from(body, 'utf-8') : body;
5
+ const hash = createHash('sha256').update(bodyBuffer).digest('base64');
6
+ return `SHA-256=${hash}`;
7
+ }
8
+ export function extractDigestHash(digestHeader) {
9
+ const match = DIGEST_HEADER_PATTERN.exec(digestHeader);
10
+ if (!match?.[1])
11
+ throw new Error('Invalid Digest header format');
12
+ return match[1];
13
+ }
14
+ export function verifyDigest(body, expectedDigestHeader) {
15
+ const computed = Buffer.from(computeDigest(body));
16
+ const expected = Buffer.from(expectedDigestHeader);
17
+ if (computed.length !== expected.length)
18
+ return false;
19
+ return timingSafeEqual(computed, expected);
20
+ }
@@ -0,0 +1,7 @@
1
+ export type RsaSha256KeyPair = {
2
+ publicKeyPem: string;
3
+ privateKeyPem: string;
4
+ };
5
+ export declare function generateRsaSha256KeyPair(): RsaSha256KeyPair;
6
+ export declare function assertPublicKeyPem(pem: string): void;
7
+ export declare function assertPrivateKeyPem(pem: string): void;
@@ -0,0 +1,27 @@
1
+ import { createPrivateKey, createPublicKey, generateKeyPairSync } from 'node:crypto';
2
+ export function generateRsaSha256KeyPair() {
3
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
4
+ modulusLength: 2048,
5
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
6
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
7
+ });
8
+ return { publicKeyPem: publicKey, privateKeyPem: privateKey };
9
+ }
10
+ export function assertPublicKeyPem(pem) {
11
+ if (pem.includes('PRIVATE'))
12
+ throw new Error('Invalid public key PEM format');
13
+ try {
14
+ createPublicKey(pem);
15
+ }
16
+ catch {
17
+ throw new Error('Invalid public key PEM format');
18
+ }
19
+ }
20
+ export function assertPrivateKeyPem(pem) {
21
+ try {
22
+ createPrivateKey(pem);
23
+ }
24
+ catch {
25
+ throw new Error('Invalid private key PEM format');
26
+ }
27
+ }
@@ -0,0 +1,17 @@
1
+ export type SignatureHeaders = {
2
+ digest: string;
3
+ signature: string;
4
+ date: string;
5
+ };
6
+ export type BuildSignatureHeadersOptions = {
7
+ method: string;
8
+ url: string;
9
+ body: string | Buffer;
10
+ keyId: string;
11
+ privateKeyPem: string;
12
+ signedHeaders: readonly string[];
13
+ algorithm: string;
14
+ now?: Date;
15
+ additionalHeaders?: Record<string, string>;
16
+ };
17
+ export declare function buildSignatureHeaders(options: BuildSignatureHeadersOptions): SignatureHeaders;
@@ -0,0 +1,35 @@
1
+ import { createPrivateKey, sign } from 'node:crypto';
2
+ import { computeDigest } from './http-signatures-digest.mjs';
3
+ import { assertPrivateKeyPem } from './http-signatures-keys.mjs';
4
+ import { buildSigningString, isSha256SignatureAlgorithm } from './http-signatures-string.mjs';
5
+ export function buildSignatureHeaders(options) {
6
+ if (options.signedHeaders.length === 0)
7
+ throw new Error('signedHeaders must not be empty');
8
+ if (!isSha256SignatureAlgorithm(options.algorithm)) {
9
+ throw new Error(`Unsupported signature algorithm: ${options.algorithm}`);
10
+ }
11
+ assertPrivateKeyPem(options.privateKeyPem);
12
+ const digest = computeDigest(options.body);
13
+ const date = (options.now ?? new Date()).toUTCString();
14
+ const url = new URL(options.url);
15
+ const host = url.host;
16
+ const path = url.pathname + url.search;
17
+ const signingString = buildSigningString(options.signedHeaders, {
18
+ method: options.method,
19
+ path,
20
+ host,
21
+ date,
22
+ digest,
23
+ additionalHeaders: options.additionalHeaders,
24
+ });
25
+ if (typeof signingString !== 'string')
26
+ throw new Error(signingString.error);
27
+ const signature = sign('sha256', Buffer.from(signingString), createPrivateKey(options.privateKeyPem)).toString('base64');
28
+ const signatureHeaderValue = [
29
+ `keyId="${options.keyId}"`,
30
+ `algorithm="${options.algorithm}"`,
31
+ `headers="${options.signedHeaders.map((name) => name.toLowerCase()).join(' ')}"`,
32
+ `signature="${signature}"`,
33
+ ].join(',');
34
+ return { digest, signature: signatureHeaderValue, date };
35
+ }
@@ -0,0 +1,12 @@
1
+ export type SigningHeaderValues = {
2
+ method: string;
3
+ path: string;
4
+ host: string;
5
+ date: string;
6
+ digest: string;
7
+ additionalHeaders?: Record<string, string> | undefined;
8
+ };
9
+ export declare function isSha256SignatureAlgorithm(algorithm: string): boolean;
10
+ export declare function buildSigningString(headerNames: readonly string[], values: SigningHeaderValues): string | {
11
+ error: string;
12
+ };
@@ -0,0 +1,40 @@
1
+ const SHA256_ALGORITHMS = new Set(['rsa-sha256', 'hs2019']);
2
+ export function isSha256SignatureAlgorithm(algorithm) {
3
+ return SHA256_ALGORITHMS.has(algorithm);
4
+ }
5
+ function additionalHeaderValue(headers, name) {
6
+ if (!headers)
7
+ return undefined;
8
+ if (Object.hasOwn(headers, name))
9
+ return headers[name];
10
+ const lower = name.toLowerCase();
11
+ for (const [key, value] of Object.entries(headers)) {
12
+ if (key.toLowerCase() === lower)
13
+ return value;
14
+ }
15
+ return undefined;
16
+ }
17
+ function signingLineForHeader(name, values) {
18
+ const lower = name.toLowerCase();
19
+ if (lower === '(request-target)') {
20
+ return `(request-target): ${values.method.toLowerCase()} ${values.path}`;
21
+ }
22
+ if (lower === 'host')
23
+ return `host: ${values.host}`;
24
+ if (lower === 'date')
25
+ return `date: ${values.date}`;
26
+ if (lower === 'digest')
27
+ return `digest: ${values.digest}`;
28
+ const extra = additionalHeaderValue(values.additionalHeaders, name);
29
+ return extra === undefined ? undefined : `${lower}: ${extra}`;
30
+ }
31
+ export function buildSigningString(headerNames, values) {
32
+ const lines = [];
33
+ for (const name of headerNames) {
34
+ const line = signingLineForHeader(name, values);
35
+ if (line === undefined)
36
+ return { error: `Unknown signed header: ${name}` };
37
+ lines.push(line);
38
+ }
39
+ return lines.join('\n');
40
+ }
@@ -0,0 +1,21 @@
1
+ export type VerifySignatureOptions = {
2
+ method: string;
3
+ path: string;
4
+ host: string;
5
+ body: string | Buffer;
6
+ signatureHeader: string;
7
+ digestHeader: string;
8
+ dateHeader: string;
9
+ publicKeyPem: string;
10
+ requiredHeaders: readonly string[];
11
+ allowedAlgorithms: readonly string[];
12
+ maxAgeSeconds: number;
13
+ additionalHeaders?: Record<string, string>;
14
+ referenceTime?: Date;
15
+ };
16
+ export type SignatureVerificationResult = {
17
+ valid: boolean;
18
+ error?: string;
19
+ };
20
+ export declare function extractSignatureKeyId(signatureHeader: string): string | undefined;
21
+ export declare function verifySignature(options: VerifySignatureOptions): SignatureVerificationResult;
@@ -0,0 +1,88 @@
1
+ import { verify } from 'node:crypto';
2
+ import { verifyDigest } from './http-signatures-digest.mjs';
3
+ import { assertPublicKeyPem } from './http-signatures-keys.mjs';
4
+ import { buildSigningString, isSha256SignatureAlgorithm } from './http-signatures-string.mjs';
5
+ const SIGNATURE_VALUE_PATTERN = /signature="([^"]+)"/;
6
+ const HEADERS_VALUE_PATTERN = /headers="([^"]+)"/;
7
+ const ALGORITHM_VALUE_PATTERN = /algorithm="([^"]+)"/;
8
+ const KEY_ID_VALUE_PATTERN = /keyId="([^"]+)"/;
9
+ export function extractSignatureKeyId(signatureHeader) {
10
+ return KEY_ID_VALUE_PATTERN.exec(signatureHeader)?.[1];
11
+ }
12
+ function parseSignatureHeader(header) {
13
+ const signatureMatch = SIGNATURE_VALUE_PATTERN.exec(header);
14
+ const headersMatch = HEADERS_VALUE_PATTERN.exec(header);
15
+ if (!signatureMatch?.[1] || !headersMatch?.[1])
16
+ return null;
17
+ return {
18
+ signature: signatureMatch[1],
19
+ headers: headersMatch[1].split(' ').map((name) => name.toLowerCase()),
20
+ algorithm: ALGORITHM_VALUE_PATTERN.exec(header)?.[1] ?? null,
21
+ };
22
+ }
23
+ export function verifySignature(options) {
24
+ try {
25
+ return verifySignatureBody(options);
26
+ }
27
+ catch (err) {
28
+ return {
29
+ valid: false,
30
+ error: `Signature verification exception: ${err.message}`,
31
+ };
32
+ }
33
+ }
34
+ function verifySignatureBody(options) {
35
+ assertPublicKeyPem(options.publicKeyPem);
36
+ const requestDate = new Date(options.dateHeader);
37
+ if (Number.isNaN(requestDate.getTime()))
38
+ return { valid: false, error: 'Invalid date header' };
39
+ const ageSeconds = ((options.referenceTime?.getTime() ?? Date.now()) - requestDate.getTime()) / 1000;
40
+ if (!Number.isFinite(options.maxAgeSeconds) || options.maxAgeSeconds < 0) {
41
+ return { valid: false, error: 'maxAgeSeconds must be a finite non-negative number' };
42
+ }
43
+ if (Math.abs(ageSeconds) > options.maxAgeSeconds) {
44
+ return {
45
+ valid: false,
46
+ error: `Date header too old: ${ageSeconds}s > ${options.maxAgeSeconds}s`,
47
+ };
48
+ }
49
+ if (!verifyDigest(options.body, options.digestHeader)) {
50
+ return { valid: false, error: 'Digest verification failed' };
51
+ }
52
+ const sigParts = parseSignatureHeader(options.signatureHeader);
53
+ if (!sigParts)
54
+ return { valid: false, error: 'Invalid signature header format' };
55
+ const { signature, headers, algorithm } = sigParts;
56
+ if (algorithm === null ||
57
+ !options.allowedAlgorithms.includes(algorithm) ||
58
+ !isSha256SignatureAlgorithm(algorithm)) {
59
+ return {
60
+ valid: false,
61
+ error: algorithm === null
62
+ ? 'Signature algorithm is required'
63
+ : `Unsupported signature algorithm: ${algorithm}`,
64
+ };
65
+ }
66
+ const covered = new Set(headers);
67
+ const missingRequired = options.requiredHeaders
68
+ .map((name) => name.toLowerCase())
69
+ .filter((name) => !covered.has(name));
70
+ if (missingRequired.length > 0) {
71
+ return {
72
+ valid: false,
73
+ error: `Signature must cover ${options.requiredHeaders.join(', ')} (missing: ${missingRequired.join(', ')})`,
74
+ };
75
+ }
76
+ const signingString = buildSigningString(headers, {
77
+ method: options.method,
78
+ path: options.path,
79
+ host: options.host,
80
+ date: options.dateHeader,
81
+ digest: options.digestHeader,
82
+ additionalHeaders: options.additionalHeaders,
83
+ });
84
+ if (typeof signingString !== 'string')
85
+ return { valid: false, error: signingString.error };
86
+ const isValid = verify('sha256', Buffer.from(signingString), options.publicKeyPem, Buffer.from(signature, 'base64'));
87
+ return isValid ? { valid: true } : { valid: false, error: 'Signature verification failed' };
88
+ }
@@ -0,0 +1,4 @@
1
+ export { computeDigest, extractDigestHash, verifyDigest } from './http-signatures-digest.mts';
2
+ export { assertPrivateKeyPem, assertPublicKeyPem, generateRsaSha256KeyPair, type RsaSha256KeyPair, } from './http-signatures-keys.mts';
3
+ export { buildSignatureHeaders, type BuildSignatureHeadersOptions, type SignatureHeaders, } from './http-signatures-sign.mts';
4
+ export { extractSignatureKeyId, verifySignature, type SignatureVerificationResult, type VerifySignatureOptions, } from './http-signatures-verify.mts';
@@ -0,0 +1,4 @@
1
+ export { computeDigest, extractDigestHash, verifyDigest } from './http-signatures-digest.mjs';
2
+ export { assertPrivateKeyPem, assertPublicKeyPem, generateRsaSha256KeyPair, } from './http-signatures-keys.mjs';
3
+ export { buildSignatureHeaders, } from './http-signatures-sign.mjs';
4
+ export { extractSignatureKeyId, verifySignature, } from './http-signatures-verify.mjs';
@@ -0,0 +1,20 @@
1
+ export interface JsonlPartitionWriterOptions<T> {
2
+ /** Root directory; every partition file lives beneath it. */
3
+ directory: string;
4
+ /** Relative file path for a record, for example `events/2025-01-31.jsonl`. Must stay inside `directory`. */
5
+ partition: (record: T) => string;
6
+ /** Receives background flush failures. Explicit `flush()` calls reject instead. */
7
+ onError: (error: unknown) => void;
8
+ /** Flush after this many buffered records. Defaults to 500. */
9
+ maxRecords?: number;
10
+ /** Flush after this many buffered bytes. Defaults to 4 MiB. */
11
+ maxBytes?: number;
12
+ /** Delay before buffered records are flushed. Defaults to 1000. */
13
+ flushIntervalMs?: number;
14
+ }
15
+ export interface JsonlPartitionWriter<T> {
16
+ write: (record: T) => void;
17
+ /** Appends everything buffered, including records written meanwhile; rejects with the first failure. */
18
+ flush: () => Promise<void>;
19
+ }
20
+ export declare function createJsonlPartitionWriter<T>(options: JsonlPartitionWriterOptions<T>): JsonlPartitionWriter<T>;
@@ -0,0 +1,86 @@
1
+ import { appendFile, mkdir } from 'node:fs/promises';
2
+ import { dirname, join, relative } from 'node:path';
3
+ // Buffers records and appends them to per-partition JSON Lines files on count, size, or time.
4
+ export function createJsonlPartitionWriter(options) {
5
+ const { directory, partition, onError } = options;
6
+ const maxRecords = options.maxRecords ?? 500;
7
+ const maxBytes = options.maxBytes ?? 4 * 1024 * 1024;
8
+ const flushIntervalMs = options.flushIntervalMs ?? 1000;
9
+ let buffer = [];
10
+ let bufferedBytes = 0;
11
+ let timer;
12
+ let active;
13
+ function clearTimer() {
14
+ if (timer !== undefined)
15
+ clearTimeout(timer);
16
+ timer = undefined;
17
+ }
18
+ function resolvePath(name) {
19
+ const path = join(directory, name);
20
+ const rel = relative(directory, path);
21
+ if (rel === '' || rel.startsWith('..')) {
22
+ throw new RangeError(`Partition path escapes the directory: ${name}`);
23
+ }
24
+ return path;
25
+ }
26
+ async function appendBatch() {
27
+ const records = buffer;
28
+ buffer = [];
29
+ bufferedBytes = 0;
30
+ const groups = Map.groupBy(records, (record) => record.file);
31
+ const results = await Promise.allSettled([...groups].map(async ([file, items]) => {
32
+ await mkdir(dirname(file), { recursive: true });
33
+ await appendFile(file, `${items.map((item) => item.line).join('\n')}\n`, 'utf8');
34
+ }));
35
+ const failure = results.find((result) => result.status === 'rejected');
36
+ if (failure)
37
+ throw failure.reason;
38
+ }
39
+ async function drain() {
40
+ let failure;
41
+ while (buffer.length > 0) {
42
+ try {
43
+ await appendBatch();
44
+ }
45
+ catch (error) {
46
+ failure ??= { reason: error };
47
+ }
48
+ }
49
+ active = undefined;
50
+ if (failure)
51
+ throw failure.reason;
52
+ }
53
+ function flush() {
54
+ clearTimer();
55
+ if (active)
56
+ return active;
57
+ if (buffer.length === 0)
58
+ return Promise.resolve();
59
+ active = drain();
60
+ return active;
61
+ }
62
+ function flushInBackground() {
63
+ flush().catch(onError);
64
+ }
65
+ function write(record) {
66
+ const line = JSON.stringify(record);
67
+ if (line === undefined)
68
+ throw new TypeError('Record is not JSON serializable');
69
+ buffer.push({ file: resolvePath(partition(record)), line });
70
+ bufferedBytes += Buffer.byteLength(line) + 1;
71
+ if (buffer.length >= maxRecords || bufferedBytes >= maxBytes) {
72
+ // A running drain keeps going until the buffer is empty, so it also takes this record.
73
+ if (!active)
74
+ flushInBackground();
75
+ return;
76
+ }
77
+ if (timer !== undefined)
78
+ return;
79
+ timer = setTimeout(() => {
80
+ timer = undefined;
81
+ flushInBackground();
82
+ }, flushIntervalMs);
83
+ timer.unref();
84
+ }
85
+ return { write, flush };
86
+ }
@@ -0,0 +1,14 @@
1
+ export type EncryptionKey = {
2
+ id: string;
3
+ key: Buffer;
4
+ };
5
+ export type TokenSecrets = {
6
+ hashToken(purpose: string, token: string): string;
7
+ encryptSecret(plaintext: string, purpose: string): string;
8
+ decryptSecret(ciphertext: string, purpose: string): string;
9
+ };
10
+ export declare function parseEncryptionKeys(value: string): EncryptionKey[];
11
+ export declare function createTokenSecrets(options: {
12
+ hashSecret: string;
13
+ encryptionKeys: readonly EncryptionKey[];
14
+ }): TokenSecrets;