@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,102 @@
1
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'node:crypto';
2
+ const KEY_FORMAT = 'v1';
3
+ export function parseEncryptionKeys(value) {
4
+ return value
5
+ .split(',')
6
+ .map((part) => part.trim())
7
+ .map(parseEncryptionKey);
8
+ }
9
+ export function createTokenSecrets(options) {
10
+ if (!options.hashSecret.trim())
11
+ throw new Error('Hash secret must not be empty');
12
+ const hashSecret = options.hashSecret;
13
+ if (options.encryptionKeys.length === 0)
14
+ throw new Error('Encryption keys must contain at least one key');
15
+ for (const key of options.encryptionKeys) {
16
+ if (!/^[A-Za-z0-9_-]+$/.test(key.id) || key.key.length !== 32)
17
+ throw new Error('Encryption keys must have a non-empty id and 32 bytes');
18
+ }
19
+ const copiedKeys = options.encryptionKeys.map((key) => ({
20
+ id: key.id,
21
+ key: Buffer.from(key.key),
22
+ }));
23
+ const keys = new Map(copiedKeys.map((key) => [key.id, key]));
24
+ if (keys.size !== options.encryptionKeys.length)
25
+ throw new Error('Encryption key ids must be unique');
26
+ const primary = copiedKeys[0];
27
+ return {
28
+ hashToken: (purpose, token) => createHmac('sha256', hashSecret)
29
+ .update(purpose)
30
+ .update('\0')
31
+ .update(token)
32
+ .digest('hex')
33
+ .toUpperCase(),
34
+ encryptSecret: (plaintext, purpose) => encrypt(plaintext, purpose, primary),
35
+ decryptSecret: (ciphertext, purpose) => decrypt(ciphertext, purpose, keys),
36
+ };
37
+ }
38
+ function parseEncryptionKey(part) {
39
+ const separator = part.indexOf(':');
40
+ const id = separator < 0 ? '' : part.slice(0, separator).trim();
41
+ if (!/^[A-Za-z0-9_-]+$/.test(id))
42
+ throw new Error('Encryption key entries must use a non-empty safe key id');
43
+ const raw = part.slice(separator + 1).trim();
44
+ const value = raw.startsWith('raw32:')
45
+ ? raw.slice(6).trim()
46
+ : raw.startsWith('base64url:')
47
+ ? raw.slice(10).trim()
48
+ : raw;
49
+ if (!value)
50
+ throw new Error('Encryption key entries must contain key material');
51
+ if (!raw.startsWith('raw32:') &&
52
+ (!/^[A-Za-z0-9_-]+$/.test(value) ||
53
+ Buffer.from(value, 'base64url').toString('base64url') !== value))
54
+ throw new Error('Encryption key material must be canonical base64url');
55
+ const key = raw.startsWith('raw32:') ? Buffer.from(value) : Buffer.from(value, 'base64url');
56
+ if (key.length !== 32)
57
+ throw new Error(`Encryption key ${id} must be 32 bytes`);
58
+ return { id, key };
59
+ }
60
+ function encrypt(plaintext, purpose, key) {
61
+ const iv = randomBytes(12);
62
+ const cipher = createCipheriv('aes-256-gcm', key.key, iv);
63
+ cipher.setAAD(Buffer.from(purpose));
64
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
65
+ return [
66
+ KEY_FORMAT,
67
+ key.id,
68
+ iv.toString('base64url'),
69
+ cipher.getAuthTag().toString('base64url'),
70
+ ciphertext.toString('base64url'),
71
+ ].join(':');
72
+ }
73
+ function decrypt(value, purpose, keys) {
74
+ const [format, id, iv, tag, ciphertext, extra] = value.split(':');
75
+ if (format !== KEY_FORMAT ||
76
+ !id ||
77
+ !iv ||
78
+ !tag ||
79
+ ciphertext === undefined ||
80
+ extra !== undefined)
81
+ throw new Error('Invalid encrypted secret format');
82
+ const key = keys.get(id);
83
+ if (!key)
84
+ throw new Error(`Encryption key ${id} is not configured`);
85
+ const ivBytes = decodeCanonicalBase64Url(iv);
86
+ const tagBytes = decodeCanonicalBase64Url(tag);
87
+ const ciphertextBytes = decodeCanonicalBase64Url(ciphertext);
88
+ if (ivBytes.length !== 12 || tagBytes.length !== 16)
89
+ throw new Error('Invalid encrypted secret format');
90
+ const decipher = createDecipheriv('aes-256-gcm', key.key, ivBytes);
91
+ decipher.setAAD(Buffer.from(purpose));
92
+ decipher.setAuthTag(tagBytes);
93
+ return Buffer.concat([decipher.update(ciphertextBytes), decipher.final()]).toString();
94
+ }
95
+ function decodeCanonicalBase64Url(value) {
96
+ if (!/^[A-Za-z0-9_-]*$/.test(value))
97
+ throw new Error('Invalid encrypted secret format');
98
+ const decoded = Buffer.from(value, 'base64url');
99
+ if (decoded.toString('base64url') !== value)
100
+ throw new Error('Invalid encrypted secret format');
101
+ return decoded;
102
+ }
@@ -0,0 +1,18 @@
1
+ export declare function normalizeHostname(hostname: string): string;
2
+ /** Hostname of a URL string or a bare host. Returns undefined when empty or unparsable. */
3
+ export declare function hostnameOf(value: string): string | undefined;
4
+ /** Route matcher: `<prefix><one non-empty segment>`. Returns the segment, or undefined. */
5
+ export declare function matchRouteSegment(pathname: string, prefix: string): string | undefined;
6
+ export type ProtectedHostPolicy = {
7
+ hosts: () => string[];
8
+ isProtected: (url: URL, extraHosts?: readonly string[]) => boolean;
9
+ blockedHosts: () => {
10
+ exact: string[];
11
+ suffixes: string[];
12
+ };
13
+ };
14
+ /**
15
+ * Protected-host policy. Each entry (URL or bare host) protects the host and all subdomains.
16
+ * The caller supplies the host list; nothing is read from the environment.
17
+ */
18
+ export declare function createProtectedHostPolicy(entries: readonly string[]): ProtectedHostPolicy;
@@ -0,0 +1,61 @@
1
+ export function normalizeHostname(hostname) {
2
+ return hostname.replace(/\.$/, '').toLowerCase();
3
+ }
4
+ /** Hostname of a URL string or a bare host. Returns undefined when empty or unparsable. */
5
+ export function hostnameOf(value) {
6
+ if (value.includes('://')) {
7
+ try {
8
+ return normalizeHostname(new URL(value).hostname);
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
14
+ const host = value.trim();
15
+ if (!host)
16
+ return undefined;
17
+ try {
18
+ // Canonicalize like URL.hostname so Unicode hosts match their punycode form.
19
+ return normalizeHostname(new URL(`https://${host}`).hostname);
20
+ }
21
+ catch {
22
+ return normalizeHostname(host);
23
+ }
24
+ }
25
+ /** Route matcher: `<prefix><one non-empty segment>`. Returns the segment, or undefined. */
26
+ export function matchRouteSegment(pathname, prefix) {
27
+ if (!pathname.startsWith(prefix))
28
+ return undefined;
29
+ const rest = pathname.slice(prefix.length);
30
+ return rest && !rest.includes('/') ? rest : undefined;
31
+ }
32
+ /**
33
+ * Protected-host policy. Each entry (URL or bare host) protects the host and all subdomains.
34
+ * The caller supplies the host list; nothing is read from the environment.
35
+ */
36
+ export function createProtectedHostPolicy(entries) {
37
+ const collect = (extra = []) => {
38
+ const hosts = new Set();
39
+ for (const entry of [...entries, ...extra]) {
40
+ const host = hostnameOf(entry);
41
+ if (host)
42
+ hosts.add(host);
43
+ }
44
+ return hosts;
45
+ };
46
+ return {
47
+ hosts: () => [...collect()],
48
+ isProtected(url, extraHosts) {
49
+ const host = normalizeHostname(url.hostname);
50
+ for (const protectedHost of collect(extraHosts)) {
51
+ if (host === protectedHost || host.endsWith(`.${protectedHost}`))
52
+ return true;
53
+ }
54
+ return false;
55
+ },
56
+ blockedHosts() {
57
+ const hosts = [...collect()];
58
+ return { exact: hosts, suffixes: hosts.map((host) => `.${host}`) };
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,23 @@
1
+ export declare function signPathWithKey(path: string, keyHex: string): string;
2
+ export declare function verifyPathWithKey(path: string, signature: string, keyHex: string): boolean;
3
+ /**
4
+ * Parse a comma-separated list of hex keys. Entries are trimmed; empty entries and
5
+ * case-insensitive placeholder entries are skipped.
6
+ */
7
+ export declare function parseSigningKeys(value: string | undefined, options?: {
8
+ placeholder?: string;
9
+ }): string[];
10
+ /** Sign with the first usable key. Returns '' when no key is usable. */
11
+ export declare function signPath(path: string, keys: readonly string[]): string;
12
+ export type VerifyPathOptions = {
13
+ /** Accept any signature when no keys are configured (dev mode). Defaults to false. */
14
+ allowUnsignedWhenNoKeys?: boolean;
15
+ };
16
+ /** Verify against every key (for rotation). Invalid keys never match. */
17
+ export declare function verifyPathSignature(path: string, signature: string, keys: readonly string[], options?: VerifyPathOptions): boolean;
18
+ /** Sign a path bound to an expiry (epoch milliseconds). Returns '' when no key is usable. */
19
+ export declare function signExpiringPath(path: string, expiresAtMs: number, keys: readonly string[]): string;
20
+ /** Verify an expiring signature. Fails closed for unsafe expiry values and expired links. */
21
+ export declare function verifyExpiringPath(path: string, expiresAtMs: number, signature: string, keys: readonly string[], options?: {
22
+ now?: number;
23
+ }): boolean;
@@ -0,0 +1,66 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ export function signPathWithKey(path, keyHex) {
3
+ if (!/^[\da-f]{64}$/i.test(keyHex))
4
+ throw new Error('Signing keys must be 64 hexadecimal characters');
5
+ return createHmac('sha256', Buffer.from(keyHex, 'hex')).update(path).digest('hex');
6
+ }
7
+ export function verifyPathWithKey(path, signature, keyHex) {
8
+ const expected = signPathWithKey(path, keyHex);
9
+ if (expected.length !== signature.length || !/^[\da-f]+$/i.test(signature))
10
+ return false;
11
+ return timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(signature, 'hex'));
12
+ }
13
+ /**
14
+ * Parse a comma-separated list of hex keys. Entries are trimmed; empty entries and
15
+ * case-insensitive placeholder entries are skipped.
16
+ */
17
+ export function parseSigningKeys(value, options = {}) {
18
+ if (!value)
19
+ return [];
20
+ const placeholder = (options.placeholder ?? 'PLACEHOLDER').toUpperCase();
21
+ return value.split(',').flatMap((entry) => {
22
+ const key = entry.trim();
23
+ return key && key.toUpperCase() !== placeholder ? [key] : [];
24
+ });
25
+ }
26
+ /** Sign with the first usable key. Returns '' when no key is usable. */
27
+ export function signPath(path, keys) {
28
+ for (const key of keys) {
29
+ try {
30
+ return signPathWithKey(path, key);
31
+ }
32
+ catch {
33
+ // Invalid key: try the next one.
34
+ }
35
+ }
36
+ return '';
37
+ }
38
+ /** Verify against every key (for rotation). Invalid keys never match. */
39
+ export function verifyPathSignature(path, signature, keys, options = {}) {
40
+ if (keys.length === 0)
41
+ return options.allowUnsignedWhenNoKeys === true;
42
+ return keys.some((key) => {
43
+ try {
44
+ return verifyPathWithKey(path, signature, key);
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ });
50
+ }
51
+ function expiringPayload(path, expiresAtMs) {
52
+ return `${expiresAtMs}\n${path}`;
53
+ }
54
+ /** Sign a path bound to an expiry (epoch milliseconds). Returns '' when no key is usable. */
55
+ export function signExpiringPath(path, expiresAtMs, keys) {
56
+ return signPath(expiringPayload(path, expiresAtMs), keys);
57
+ }
58
+ /** Verify an expiring signature. Fails closed for unsafe expiry values and expired links. */
59
+ export function verifyExpiringPath(path, expiresAtMs, signature, keys, options = {}) {
60
+ if (!Number.isSafeInteger(expiresAtMs))
61
+ return false;
62
+ const now = options.now ?? Date.now();
63
+ if (!Number.isFinite(now) || now > expiresAtMs)
64
+ return false;
65
+ return verifyPathSignature(expiringPayload(path, expiresAtMs), signature, keys);
66
+ }
@@ -0,0 +1,19 @@
1
+ export type BuildSignedProxyUrlOptions = {
2
+ /** Origin that serves the proxy route. */
3
+ origin: string;
4
+ /** Route prefix; the base64url target is appended, e.g. `/proxy/v1/`. */
5
+ pathPrefix: string;
6
+ /** Ordered query parameters; undefined values are skipped. The signature is appended last. */
7
+ query?: Record<string, string | number | undefined>;
8
+ signingKeys: readonly string[];
9
+ /** Return true to leave a URL unproxied (first-party hosts, legacy routes, ...). */
10
+ skip?: (url: URL) => boolean;
11
+ /** Name of the signature query parameter. Defaults to `sig`. */
12
+ signatureParam?: string;
13
+ };
14
+ /**
15
+ * Build a signed proxy URL for an external http(s) URL. Returns null for empty, relative,
16
+ * protocol-relative, non-http(s), already-proxied, or caller-skipped URLs. When no key is usable
17
+ * the URL is returned without a signature.
18
+ */
19
+ export declare function buildSignedProxyUrl(externalUrl: string, options: BuildSignedProxyUrlOptions): string | null;
@@ -0,0 +1,36 @@
1
+ import { signPath } from './url-signing-keys.mjs';
2
+ /**
3
+ * Build a signed proxy URL for an external http(s) URL. Returns null for empty, relative,
4
+ * protocol-relative, non-http(s), already-proxied, or caller-skipped URLs. When no key is usable
5
+ * the URL is returned without a signature.
6
+ */
7
+ export function buildSignedProxyUrl(externalUrl, options) {
8
+ const value = externalUrl.trim();
9
+ if (!value || value.startsWith('//'))
10
+ return null;
11
+ let target;
12
+ try {
13
+ target = new URL(value);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ if (target.protocol !== 'http:' && target.protocol !== 'https:')
19
+ return null;
20
+ const origin = new URL(options.origin).origin;
21
+ if (target.origin === origin && target.pathname.startsWith(options.pathPrefix))
22
+ return null;
23
+ if (options.skip?.(target))
24
+ return null;
25
+ const path = `${options.pathPrefix}${Buffer.from(value, 'utf8').toString('base64url')}`;
26
+ const params = new URLSearchParams();
27
+ for (const [name, entry] of Object.entries(options.query ?? {})) {
28
+ if (entry !== undefined)
29
+ params.append(name, String(entry));
30
+ }
31
+ const signature = signPath(path, options.signingKeys);
32
+ if (signature)
33
+ params.append(options.signatureParam ?? 'sig', signature);
34
+ const query = params.toString();
35
+ return `${origin}${path}${query ? `?${query}` : ''}`;
36
+ }
@@ -0,0 +1,3 @@
1
+ export { parseSigningKeys, signExpiringPath, signPath, signPathWithKey, verifyExpiringPath, verifyPathSignature, verifyPathWithKey, type VerifyPathOptions, } from './url-signing-keys.mts';
2
+ export { createProtectedHostPolicy, hostnameOf, matchRouteSegment, normalizeHostname, type ProtectedHostPolicy, } from './url-signing-hosts.mts';
3
+ export { buildSignedProxyUrl, type BuildSignedProxyUrlOptions } from './url-signing-proxy.mts';
@@ -0,0 +1,3 @@
1
+ export { parseSigningKeys, signExpiringPath, signPath, signPathWithKey, verifyExpiringPath, verifyPathSignature, verifyPathWithKey, } from './url-signing-keys.mjs';
2
+ export { createProtectedHostPolicy, hostnameOf, matchRouteSegment, normalizeHostname, } from './url-signing-hosts.mjs';
3
+ export { buildSignedProxyUrl } from './url-signing-proxy.mjs';
@@ -0,0 +1,26 @@
1
+ export interface VapidKeyPair {
2
+ /** Uncompressed P-256 point, base64url (the browser `applicationServerKey`). */
3
+ publicKey: string;
4
+ /** Raw 32-byte private scalar, base64url. */
5
+ privateKey: string;
6
+ }
7
+ export interface VapidJwtInput {
8
+ keys: VapidKeyPair;
9
+ /** Push service origin, for example `getPushServiceAudience(endpoint)`. */
10
+ audience: string;
11
+ /** `mailto:` or `https:` contact URI. */
12
+ subject: string;
13
+ /** Seconds since epoch; injectable for tests. */
14
+ now?: number;
15
+ /** Lifetime in seconds; RFC 8292 caps it at 24 hours. */
16
+ expiresInSeconds?: number;
17
+ }
18
+ export declare function generateVapidKeys(): VapidKeyPair;
19
+ /** Returns whether the private scalar corresponds to the public point. */
20
+ export declare function vapidKeysMatch(keys: VapidKeyPair): boolean;
21
+ /** Accepts `mailto:user@host` or an https URL with a host. */
22
+ export declare function isValidVapidSubject(subject: string): boolean;
23
+ /** Signs an ES256 VAPID JWT (RFC 8292). */
24
+ export declare function createVapidJwt(input: VapidJwtInput): string;
25
+ /** Builds the `Authorization` header value for the `vapid` scheme; `k=` is unpadded base64url. */
26
+ export declare function createVapidAuthorization(jwt: string, publicKey: string): string;
@@ -0,0 +1,107 @@
1
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto';
2
+ function decodeBase64Url(value) {
3
+ if (!/^[A-Za-z0-9_-]*={0,2}$/.test(value))
4
+ throw new TypeError('Invalid base64url string');
5
+ const base64 = value.replace(/=+$/, '').replaceAll('-', '+').replaceAll('_', '/');
6
+ if (base64.length % 4 === 1)
7
+ throw new TypeError('Invalid base64url string');
8
+ return Uint8Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')), (c) => c.charCodeAt(0));
9
+ }
10
+ function encodeBase64Url(bytes) {
11
+ let binary = '';
12
+ for (const byte of bytes)
13
+ binary += String.fromCharCode(byte);
14
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
15
+ }
16
+ /** Validates a VAPID public key (uncompressed P-256 point shape) and returns its bytes. */
17
+ function decodeVapidPublicKey(key) {
18
+ const bytes = decodeBase64Url(key);
19
+ if (bytes.length !== 65 || bytes[0] !== 0x04) {
20
+ throw new TypeError('VAPID public key must be an uncompressed P-256 point');
21
+ }
22
+ return bytes;
23
+ }
24
+ const MAX_VAPID_LIFETIME_SECONDS = 24 * 60 * 60;
25
+ export function generateVapidKeys() {
26
+ const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
27
+ const pub = publicKey.export({ format: 'jwk' });
28
+ const priv = privateKey.export({ format: 'jwk' });
29
+ const point = new Uint8Array([
30
+ 0x04,
31
+ ...decodeBase64Url(pub.x),
32
+ ...decodeBase64Url(pub.y),
33
+ ]);
34
+ return { publicKey: encodeBase64Url(point), privateKey: priv.d };
35
+ }
36
+ function toPrivateKey({ publicKey, privateKey }) {
37
+ const point = decodeVapidPublicKey(publicKey);
38
+ return createPrivateKey({
39
+ key: {
40
+ kty: 'EC',
41
+ crv: 'P-256',
42
+ x: encodeBase64Url(point.slice(1, 33)),
43
+ y: encodeBase64Url(point.slice(33)),
44
+ d: privateKey,
45
+ },
46
+ format: 'jwk',
47
+ });
48
+ }
49
+ /** Returns whether the private scalar corresponds to the public point. */
50
+ export function vapidKeysMatch(keys) {
51
+ try {
52
+ // Sign/verify rather than comparing exported points: some Node/OpenSSL builds keep the
53
+ // imported public coordinates instead of deriving them from the private scalar.
54
+ const point = decodeVapidPublicKey(keys.publicKey);
55
+ const publicKey = createPublicKey({
56
+ key: {
57
+ kty: 'EC',
58
+ crv: 'P-256',
59
+ x: encodeBase64Url(point.slice(1, 33)),
60
+ y: encodeBase64Url(point.slice(33)),
61
+ },
62
+ format: 'jwk',
63
+ });
64
+ const probe = Buffer.from('vapid-key-check');
65
+ const signature = sign('sha256', probe, toPrivateKey(keys));
66
+ return verify('sha256', probe, publicKey, signature);
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ /** Accepts `mailto:user@host` or an https URL with a host. */
73
+ export function isValidVapidSubject(subject) {
74
+ const url = URL.parse(subject);
75
+ if (!url)
76
+ return false;
77
+ if (url.protocol === 'https:')
78
+ return url.hostname.length > 0;
79
+ return url.protocol === 'mailto:' && /^[^@\s]+@[^@\s]+$/.test(decodeURIComponent(url.pathname));
80
+ }
81
+ /** Signs an ES256 VAPID JWT (RFC 8292). */
82
+ export function createVapidJwt(input) {
83
+ const lifetime = input.expiresInSeconds ?? MAX_VAPID_LIFETIME_SECONDS;
84
+ if (!(lifetime > 0) || lifetime > MAX_VAPID_LIFETIME_SECONDS) {
85
+ throw new RangeError('VAPID JWT lifetime must be between 1 second and 24 hours');
86
+ }
87
+ if (!isValidVapidSubject(input.subject)) {
88
+ throw new TypeError('VAPID subject must be a valid mailto: address or https: URL');
89
+ }
90
+ const now = input.now ?? Math.floor(Date.now() / 1000);
91
+ const encode = (value) => encodeBase64Url(new TextEncoder().encode(JSON.stringify(value)));
92
+ const signingInput = `${encode({ typ: 'JWT', alg: 'ES256' })}.${encode({
93
+ aud: input.audience,
94
+ exp: now + lifetime,
95
+ sub: input.subject,
96
+ })}`;
97
+ const signature = sign('sha256', Buffer.from(signingInput), {
98
+ key: toPrivateKey(input.keys),
99
+ dsaEncoding: 'ieee-p1363',
100
+ });
101
+ return `${signingInput}.${encodeBase64Url(signature)}`;
102
+ }
103
+ /** Builds the `Authorization` header value for the `vapid` scheme; `k=` is unpadded base64url. */
104
+ export function createVapidAuthorization(jwt, publicKey) {
105
+ decodeVapidPublicKey(publicKey);
106
+ return `vapid t=${jwt}, k=${encodeBase64Url(decodeVapidPublicKey(publicKey))}`;
107
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@vouchington/server-utils",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Dependency-free server-only utilities for Node and Bun.",
5
+ "homepage": "https://github.com/vouchington/vouchington-platform/tree/main/packages/server-utils#readme",
6
+ "license": "MIT",
7
+ "author": "Jonathan Ong",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vouchington/vouchington-platform.git",
11
+ "directory": "packages/server-utils"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "type": "module",
19
+ "exports": {
20
+ "./api-errors": {
21
+ "types": "./dist/api-errors.d.mts",
22
+ "import": "./dist/api-errors.mjs",
23
+ "default": "./dist/api-errors.mjs"
24
+ },
25
+ "./child-process": {
26
+ "types": "./dist/child-process.d.mts",
27
+ "import": "./dist/child-process.mjs",
28
+ "default": "./dist/child-process.mjs"
29
+ },
30
+ "./error-tree": {
31
+ "types": "./dist/error-tree.d.mts",
32
+ "import": "./dist/error-tree.mjs",
33
+ "default": "./dist/error-tree.mjs"
34
+ },
35
+ "./graceful-shutdown": {
36
+ "types": "./dist/graceful-shutdown.d.mts",
37
+ "import": "./dist/graceful-shutdown.mjs",
38
+ "default": "./dist/graceful-shutdown.mjs"
39
+ },
40
+ "./http-signatures": {
41
+ "types": "./dist/http-signatures.d.mts",
42
+ "import": "./dist/http-signatures.mjs",
43
+ "default": "./dist/http-signatures.mjs"
44
+ },
45
+ "./jsonl-partition-writer": {
46
+ "types": "./dist/jsonl-partition-writer.d.mts",
47
+ "import": "./dist/jsonl-partition-writer.mjs",
48
+ "default": "./dist/jsonl-partition-writer.mjs"
49
+ },
50
+ "./token-secrets": {
51
+ "types": "./dist/token-secrets.d.mts",
52
+ "import": "./dist/token-secrets.mjs",
53
+ "default": "./dist/token-secrets.mjs"
54
+ },
55
+ "./url-signing": {
56
+ "types": "./dist/url-signing.d.mts",
57
+ "import": "./dist/url-signing.mjs",
58
+ "default": "./dist/url-signing.mjs"
59
+ },
60
+ "./web-push-vapid": {
61
+ "types": "./dist/web-push-vapid.d.mts",
62
+ "import": "./dist/web-push-vapid.mjs",
63
+ "default": "./dist/web-push-vapid.mjs"
64
+ }
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ },
69
+ "engines": {
70
+ "node": ">=24.0.0"
71
+ },
72
+ "scripts": {
73
+ "build": "tsc --project tsconfig.build.json"
74
+ }
6
75
  }