@kagal/taistamp 0.1.2 → 0.2.0
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.
- package/README.md +214 -53
- package/dist/_chunks/time.d.mts +144 -0
- package/dist/_chunks/time.mjs +68 -0
- package/dist/_chunks/time.mjs.map +1 -0
- package/dist/index.api.json +2094 -1546
- package/dist/index.d.mts +66 -83
- package/dist/index.d.ts +66 -83
- package/dist/index.mjs +52 -72
- package/dist/index.mjs.map +1 -1
- package/dist/utils.api.json +825 -0
- package/dist/utils.d.mts +29 -0
- package/dist/utils.d.ts +29 -0
- package/dist/utils.mjs +2 -0
- package/package.json +9 -5
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["pkg.version"],"sources":["../package.json","../src/const.ts","../src/body.ts","../src/cors.ts","../src/leap-seconds.ts","../src/nonce.ts","../src/utils.ts","../src/handler.ts","../src/index.ts"],"sourcesContent":["","export const TAISTAMP_PATH = '/.well-known/taistamp';\n\n/** @deprecated Renamed to {@link TAISTAMP_PATH}. */\nexport const TAI64N_PATH = TAISTAMP_PATH;\n\nexport const TAI64N_CONTENT_TYPE = 'application/tai64n';\nexport const TAI64N_CONTENT_LENGTH = 1 + 16 + 8; // '@' + sec (16 hex chars) + nano (8 hex chars)\n\nexport const TAI64N_HEADER_KEY_SELECTOR = 'TAI-Key-Selector';\nexport const TAI64N_HEADER_LEAP_SECONDS = 'TAI-Leap-Seconds';\nexport const TAI64N_HEADER_NONCE = 'TAI-Nonce';\nexport const TAI64N_HEADER_SIGNATURE = 'TAI-Signature';\n\nexport const TAI64_EPOCH_HI = 0x40_00_00_00;\n","import { decodeASCII } from '@kagal/ed25519-secret';\n\nimport { TAI64N_CONTENT_LENGTH } from './const';\n\n/**\n * Read a response body as a 7-bit ASCII string.\n *\n * `application/tai64n` is an octet-typed media type, not\n * text: the TAI64N label is a fixed sequence of ASCII\n * bytes. Reading it with `Response.text()` would route\n * the body through UTF-8 decoding and silently mangle any\n * non-ASCII octet, so this reads the raw bytes and decodes\n * them one code point per byte instead.\n *\n * Throws `TypeError` on any byte ≥ `0x80`, surfacing a\n * malformed body rather than masking it; pass `context` to\n * prefix that error message. Consumes the response body,\n * which can only be read once.\n *\n * Use {@link readLabel} when the body is meant to be a\n * TAI64N label and its length should be validated too.\n */\nexport const readASCII = async (\n response: Response,\n context?: string,\n): Promise<string> =>\n decodeASCII(new Uint8Array(await response.arrayBuffer()), context);\n\n/**\n * Read and return the TAI64N label from a response body.\n *\n * Builds on {@link readASCII}, adding the structural\n * invariant every label satisfies: the body is exactly\n * `TAI64N_CONTENT_LENGTH` octets. Throws `TypeError` if the\n * length differs or the body carries a non-ASCII octet;\n * pass `context` to prefix that error message. Consumes the\n * response body.\n */\nexport const readLabel = async (\n response: Response,\n context?: string,\n): Promise<string> => {\n const label = await readASCII(response, context);\n // readASCII admitted only 7-bit bytes, so the string has\n // one code unit per octet — its length is the octet count.\n if (label.length !== TAI64N_CONTENT_LENGTH) {\n const prefix = context ? `${context}: ` : '';\n throw new TypeError(\n `${prefix}expected ${TAI64N_CONTENT_LENGTH}-octet ` +\n `TAI64N label, got ${label.length}`,\n );\n }\n return label;\n};\n","import {\n TAI64N_HEADER_KEY_SELECTOR,\n TAI64N_HEADER_LEAP_SECONDS,\n TAI64N_HEADER_NONCE,\n TAI64N_HEADER_SIGNATURE,\n} from './const';\n\n// `Access-Control-Allow-Methods` (Fetch) is the list\n// of methods JS would ever preflight, so `OPTIONS` is\n// omitted. This is intentionally narrower than the\n// `Allow` header (RFC 9110 §9.3.7 method discovery,\n// `GET, HEAD, OPTIONS`) the handler itself emits.\nconst CORS_ALLOW_METHODS = 'GET, HEAD';\nconst CORS_ALLOW_HEADERS = TAI64N_HEADER_NONCE;\nconst CORS_EXPOSE_HEADERS = [\n TAI64N_HEADER_LEAP_SECONDS,\n TAI64N_HEADER_NONCE,\n TAI64N_HEADER_KEY_SELECTOR,\n TAI64N_HEADER_SIGNATURE,\n].join(', ');\n// Spec §5.2 SHOULDs at least 600s; 10 minutes is the\n// floor the spec example uses and keeps high-traffic\n// cross-origin clients off a pre-flight per fetch.\nconst CORS_MAX_AGE = '600';\n\n/**\n * The three CORS header maps the handler splices into\n * responses, keyed by response kind.\n *\n * - `preflight` — added to `OPTIONS 200` replies.\n * - `response` — added to successful `GET` / `HEAD`\n * replies; carries `Access-Control-Expose-Headers`\n * so browser JS can read the `TAI-*` headers.\n * - `error` — added to `405` replies; just the origin\n * header (and `Vary` when scoped).\n */\nexport type CORSHeaderSets = {\n error: Record<string, string>\n preflight: Record<string, string>\n response: Record<string, string>\n};\n\n/**\n * Pre-bake the three CORS header maps the handler\n * splices into responses, keyed by response kind.\n * `cors === false` collapses every map to `{}` so the\n * spread is a no-op; missing or empty input falls back\n * to `'*'`; `cors === '*'` skips `Vary: Origin` (a\n * wildcard does not vary by origin); a scoped origin\n * adds `Vary: Origin` so caches can keep per-origin\n * variants distinct.\n */\nexport const buildCORSHeaders = (\n cors: false | string | undefined,\n): CORSHeaderSets => {\n if (cors === false) {\n return { error: {}, preflight: {}, response: {} };\n }\n const origin = cors || '*';\n const vary: Record<string, string> =\n origin === '*' ? {} : { vary: 'Origin' };\n return {\n error: {\n 'access-control-allow-origin': origin,\n ...vary,\n },\n preflight: {\n 'access-control-allow-origin': origin,\n 'access-control-allow-methods': CORS_ALLOW_METHODS,\n 'access-control-allow-headers': CORS_ALLOW_HEADERS,\n 'access-control-expose-headers': CORS_EXPOSE_HEADERS,\n 'access-control-max-age': CORS_MAX_AGE,\n ...vary,\n },\n response: {\n 'access-control-allow-origin': origin,\n 'access-control-expose-headers': CORS_EXPOSE_HEADERS,\n ...vary,\n },\n };\n};\n","// cspell:words IERS\n\nimport { TAI64N_HEADER_LEAP_SECONDS } from './const';\n\n/**\n * Upper bound for `leapSeconds` in the taistamp signed\n * payload. The framing encodes the value as a 4-byte\n * big-endian unsigned integer, so any input outside\n * `[0, 2^32-1]` cannot be represented. Verifiers MUST\n * treat an out-of-range `TAI-Leap-Seconds` response\n * header as unsigned, per spec §5.3.\n */\nexport const TAI_LEAP_SECONDS_MAX = 0xFF_FF_FF_FF;\n\ndeclare const LeapSecondsBrand: unique symbol;\n\n/**\n * `number` that has been confirmed to fit the\n * `[0, TAI_LEAP_SECONDS_MAX]` u32be range required by\n * the taistamp signed-payload framing. Construct only\n * via {@link extractLeapSeconds} or {@link asLeapSeconds};\n * the brand prevents an arbitrary number from reaching\n * the signing path.\n */\nexport type LeapSeconds = number & { readonly [LeapSecondsBrand]: never };\n\n/**\n * Coerce a `number` to a {@link LeapSeconds}. Returns\n * `undefined` when `value` is non-integer, negative,\n * or exceeds {@link TAI_LEAP_SECONDS_MAX}.\n */\nexport const asLeapSeconds = (\n value: number,\n): LeapSeconds | undefined => {\n if (\n !Number.isInteger(value) ||\n value < 0 ||\n value > TAI_LEAP_SECONDS_MAX\n ) return undefined;\n return value as LeapSeconds;\n};\n\n/**\n * Current TAI − UTC offset in whole seconds, used by\n * `fromUTC()` and emitted in the `TAI-Leap-Seconds`\n * response header. The value 37 has been in force\n * since 2017-01-01; update on the next IERS leap-second\n * announcement.\n *\n * @remarks\n * Stays a single `LeapSeconds` until a leap-seconds\n * table is added so the offset can be computed for any\n * TAI second; this constant becomes redundant then.\n */\nexport const TAI_LEAP_SECONDS: LeapSeconds = 37 as LeapSeconds;\n\n/**\n * Strict decimal integer: a single `0` or a non-zero\n * leading digit followed by digits. Rejects hex\n * (`0x25`), float-style integers (`37.0`), signs,\n * whitespace, exponential notation, and leading zeros\n * — every input `Number()` would silently coerce to\n * an integer despite not being a canonical decimal.\n */\nconst DECIMAL_INTEGER = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Extract a usable leap-seconds count from response\n * headers. Returns `undefined` when the\n * `TAI-Leap-Seconds` field is missing, empty,\n * non-numeric, non-integer, negative, or out-of-range\n * — every \"treat as unsigned\" case in spec §5.3\n * collapsed into one verdict.\n */\nexport const extractLeapSeconds = (\n headers: Headers,\n): LeapSeconds | undefined => {\n const raw = headers.get(TAI64N_HEADER_LEAP_SECONDS);\n if (!raw || !DECIMAL_INTEGER.test(raw)) return undefined;\n return asLeapSeconds(Number(raw));\n};\n","import { TAI64N_HEADER_NONCE } from './const';\n\n/**\n * Wire-form lower bound on `TAI-Nonce`. Spec §5.4 sets\n * the normative bound on decoded length (≥ 7 octets);\n * 14 is the smallest wire form (`:` + 12 base64 chars\n * + `:`) that can decode to 7 octets, so the wire\n * check rejects undersize input before base64 decoding.\n * sf-binary is ASCII-only — the string length equals\n * the octet count.\n */\nexport const NONCE_MIN_OCTETS = 14;\n\n/**\n * Wire-form upper bound on `TAI-Nonce`. Spec §5.4 sets\n * the normative bound on decoded length (≤ 129 octets);\n * 174 is the longest wire form (`:` + 172 base64 chars\n * + `:`) whose decoded payload stays within 129 octets,\n * so the wire check rejects oversize input before\n * base64 decoding.\n */\nexport const NONCE_MAX_OCTETS = 174;\n\n/**\n * sf-binary item per RFC 9651 §3.3.5: standard base64\n * with `=` padding, wrapped in a leading and trailing\n * colon. The empty payload (`::`) is excluded — a\n * zero-length nonce is treated as absent per spec\n * §5.4. The alphabet contains no `,`, so a duplicated\n * field (joined by the Web `Headers` API with `,`)\n * fails the same check.\n */\nconst SF_BINARY_PATTERN =\n /^:(?:[\\d+/A-Za-z]{4})*(?:[\\d+/A-Za-z]{4}|[\\d+/A-Za-z]{3}=|[\\d+/A-Za-z]{2}==):$/;\n\ndeclare const NonceBrand: unique symbol;\n\n/**\n * `string` that has been confirmed to satisfy the\n * sf-binary syntax of RFC 9651 §3.3.5 and to fall\n * inside the wire-form length range\n * `[NONCE_MIN_OCTETS, NONCE_MAX_OCTETS]` — the\n * pre-decode form of spec §5.4's normative\n * decoded-length bound of 7..129 octets. Construct\n * only via {@link asNonce} or {@link extractNonce};\n * the brand prevents arbitrary strings from reaching\n * the signing path.\n */\nexport type Nonce = string & { readonly [NonceBrand]: never };\n\n/**\n * Brand `value` as a {@link Nonce} when it satisfies\n * sf-binary syntax (RFC 9651 §3.3.5) and falls inside\n * `[NONCE_MIN_OCTETS, NONCE_MAX_OCTETS]` — the wire\n * range equivalent to spec §5.4's normative\n * decoded-length bound of 7..129 octets. Returns\n * `undefined` for anything else — every \"treat as\n * absent\" case in spec §5.4 collapsed into one\n * verdict.\n */\nexport const asNonce = (value: string): Nonce | undefined => {\n if (\n !value ||\n value.length < NONCE_MIN_OCTETS ||\n value.length > NONCE_MAX_OCTETS ||\n !SF_BINARY_PATTERN.test(value)\n ) return undefined;\n return value as Nonce;\n};\n\n/**\n * Extract a usable `TAI-Nonce` from request headers.\n * Returns `undefined` when the field is missing or\n * fails {@link asNonce} validation.\n */\nexport const extractNonce = (headers: Headers): Nonce | undefined => {\n const value = headers.get(TAI64N_HEADER_NONCE);\n return value === null ? undefined : asNonce(value);\n};\n","import { TAI64_EPOCH_HI } from './const';\nimport { TAI_LEAP_SECONDS } from './leap-seconds';\n\ntype timestamp = {\n nano: number\n sec: number\n\n offset?: number\n};\n\nexport const fromUTC = (utc: number): timestamp => {\n // TODO: leap seconds table\n const sec = Math.floor(utc / 1000) + TAI_LEAP_SECONDS;\n const nano = (utc % 1000) * 1e6;\n return { sec, nano, offset: TAI_LEAP_SECONDS };\n};\n\nexport const now = (): timestamp => {\n const utc = Date.now();\n return fromUTC(utc);\n};\n\nexport const tai64nLabel = (value?: timestamp): string => {\n const { sec, nano } = value ?? now();\n\n const secHi = Math.trunc(sec / u32Range) + TAI64_EPOCH_HI;\n const secLo = sec % u32Range;\n\n const secHiHex = secHi.toString(16).padStart(8, '0');\n const secLoHex = secLo.toString(16).padStart(8, '0');\n const nanoHex = nano.toString(16).padStart(8, '0');\n\n return `@${secHiHex}${secLoHex}${nanoHex}`;\n};\n\nexport const tai64nLabelFromUTC = (utc: number): string => tai64nLabel(fromUTC(utc));\n\nconst u32Range = 0x1_00_00_00_00;\n","import {\n assertValidSelector,\n decodeBase64,\n encodeBase64,\n type Signer,\n} from '@kagal/ed25519-secret';\n\nimport {\n TAI64N_CONTENT_LENGTH,\n TAI64N_CONTENT_TYPE,\n TAI64N_HEADER_KEY_SELECTOR,\n TAI64N_HEADER_LEAP_SECONDS,\n TAI64N_HEADER_NONCE,\n TAI64N_HEADER_SIGNATURE,\n} from './const';\nimport { buildCORSHeaders } from './cors';\nimport { type LeapSeconds, TAI_LEAP_SECONDS } from './leap-seconds';\nimport { extractNonce, type Nonce } from './nonce';\nimport { tai64nLabel } from './utils';\n\nconst ALLOW_HEADER = 'GET, HEAD, OPTIONS';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * Domain-separation tag prepended to every signed\n * payload. Versioned so a v2 protocol can use the same\n * key without colliding with v1 signatures, and\n * NUL-terminated so the boundary between tag and\n * label is unambiguous.\n */\nconst DOMAIN_SEPARATOR = textEncoder.encode('taistamp-v1\\0');\n\n/**\n * Compose the byte sequence covered by a TAI-Signature.\n *\n * @param label - the 25-byte TAI64N label string the\n * server is returning\n * @param leapSeconds - the leap-seconds count the server\n * advertises in `TAI-Leap-Seconds`\n * @param selector - the key selector the server\n * advertises in `TAI-Key-Selector`; verifiers use\n * this to look up the public key in DNS at\n * `<selector>._taistamp.<host>`\n * @param nonce - the client-supplied nonce, echoed\n * verbatim in `TAI-Nonce`; brand a verifier-side\n * string with {@link asNonce} before passing it in\n * @returns the byte sequence verifiers reconstruct\n * from the response and pass to their public-key\n * verify routine. The framing is the\n * domain-separation tag (`taistamp-v1` plus a\n * trailing NUL byte), then the label bytes, then\n * the leap-seconds count as a 4-byte big-endian\n * unsigned integer, then a 1-byte selector length,\n * then the selector bytes, then the decoded sf-binary\n * octets of the nonce (spec §6.1 — the wire\n * `:base64:` framing is not signed).\n *\n * @remarks\n * Binding the selector into the signed payload stops a\n * downgrade attacker from rewriting `TAI-Key-Selector`\n * to point at a compromised or weaker key — the\n * signature would no longer verify under that key.\n * `leapSeconds` is encoded as a 4-byte big-endian\n * unsigned integer; the selector is length-prefixed by\n * a single byte (selectors are ≤ 63 chars per\n * {@link newTaistampHandler}'s validation).\n */\nexport const composeSignaturePayload = (\n label: string,\n leapSeconds: LeapSeconds,\n selector: string,\n nonce: Nonce,\n): ArrayBuffer => {\n const labelBytes = textEncoder.encode(label);\n const selectorBytes = textEncoder.encode(selector);\n const nonceBytes = decodeBase64(nonce.slice(1, -1));\n\n const buffer = new ArrayBuffer(\n DOMAIN_SEPARATOR.length +\n labelBytes.length +\n 4 +\n 1 +\n selectorBytes.length +\n nonceBytes.length,\n );\n const view = new Uint8Array(buffer);\n\n let offset = 0;\n view.set(DOMAIN_SEPARATOR, offset);\n offset += DOMAIN_SEPARATOR.length;\n view.set(labelBytes, offset);\n offset += labelBytes.length;\n new DataView(buffer).setUint32(offset, leapSeconds, false);\n offset += 4;\n view[offset] = selectorBytes.length;\n offset += 1;\n view.set(selectorBytes, offset);\n offset += selectorBytes.length;\n view.set(nonceBytes, offset);\n\n return buffer;\n};\n\n/**\n * Configuration for {@link newTaistampHandler}.\n *\n * @remarks\n * `signer` and `selector` are co-required: pass both\n * to enable authenticated responses, or neither for\n * an unsigned handler. Passing only one is rejected\n * at construction time — without the selector\n * verifiers cannot find the key in DNS, and a\n * selector without a signer is a misconfiguration.\n */\nexport interface TaistampHandlerConfig {\n /**\n * Key selector advertised in the `TAI-Key-Selector`\n * response header and bound into the signed payload.\n * Verifiers look up the public key at\n * `<selector>._taistamp.<host>` in DNS.\n *\n * Must match `[A-Za-z][A-Za-z0-9_-]{0,62}` (a single\n * DNS label starting with a letter, using\n * DKIM-compatible characters and a valid sf-token);\n * rotate by changing the selector and publishing a\n * new TXT record.\n */\n selector?: string\n\n /**\n * {@link Signer} that produces `TAI-Signature` over\n * the framed payload from {@link composeSignaturePayload}.\n * Without a signer the nonce is still echoed but the\n * response is unsigned.\n */\n signer?: Signer\n\n /**\n * CORS origin policy. Defaults to `'*'`; pass `false`\n * to disable CORS entirely, or a specific origin\n * (e.g. `'https://example.com'`) to scope the policy.\n *\n * Every response (`GET` / `HEAD` / `OPTIONS` / `405`)\n * gains `Access-Control-Allow-Origin`; pre-flight\n * `OPTIONS` also carries `-Allow-Methods`,\n * `-Allow-Headers`, `-Expose-Headers`, and\n * `-Max-Age: 600` per spec §5.2; success\n * `GET` / `HEAD` carry `-Expose-Headers` so browser\n * JS can read the `TAI-*` response headers. A\n * non-`'*'` value adds `Vary: Origin` so caches can\n * keep per-origin variants distinct.\n *\n * Disabling CORS does not affect method discovery:\n * `OPTIONS` is still answered with `200` and\n * `Allow: GET, HEAD, OPTIONS` per RFC 9110 §9.3.7.\n */\n cors?: false | string\n}\n\n/**\n * Validate a {@link TaistampHandlerConfig} and return\n * it unchanged when every field is well-formed.\n * Throws `TypeError` otherwise so misconfiguration\n * surfaces at handler construction rather than on the\n * first request.\n *\n * @throws TypeError if `signer` and `selector` are not\n * both set or both unset, or if `selector` does not\n * match `[A-Za-z][A-Za-z0-9_-]{0,62}`.\n */\nconst validateHandlerConfig = (\n config: TaistampHandlerConfig,\n): TaistampHandlerConfig => {\n const { cors, selector, signer } = config;\n\n if ((signer === undefined) !== (selector === undefined)) {\n throw new TypeError(\n 'newTaistampHandler: signer and selector must be set together',\n );\n }\n if (cors !== undefined && cors !== false && typeof cors !== 'string') {\n throw new TypeError(\n 'newTaistampHandler: cors must be false or a string origin',\n );\n }\n if (selector !== undefined) {\n assertValidSelector(selector, 'newTaistampHandler');\n }\n\n return config;\n};\n\n/**\n * Validate a {@link TaistampHandlerConfig} and derive\n * the construction-time state the handler closure\n * captures: the pre-baked CORS header maps and an\n * `addSignature` helper that mutates a response\n * `Headers` to carry `TAI-Key-Selector` and\n * `TAI-Signature` over the framed payload, present\n * only when both `signer` and `selector` are\n * configured. Validation is delegated to\n * {@link validateHandlerConfig}.\n *\n * @throws TypeError per {@link validateHandlerConfig}.\n */\nconst fromHandlerConfig = (config: TaistampHandlerConfig) => {\n const { cors, selector, signer } = validateHandlerConfig(config);\n\n const corsHeaders = buildCORSHeaders(cors);\n\n const addSignature = selector !== undefined && signer !== undefined ?\n async (\n headers: Headers,\n label: string,\n nonce: Nonce,\n ): Promise<void> => {\n const payload = composeSignaturePayload(\n label, TAI_LEAP_SECONDS, selector, nonce,\n );\n const signature = await signer.sign(payload);\n headers.set(TAI64N_HEADER_KEY_SELECTOR, selector);\n headers.set(\n TAI64N_HEADER_SIGNATURE,\n `:${encodeBase64(new Uint8Array(signature))}:`,\n );\n } :\n undefined;\n\n return { addSignature, corsHeaders };\n};\n\n/**\n * Build a handler for `/.well-known/taistamp`.\n *\n * @param config - optional {@link TaistampHandlerConfig}\n * @returns an `async (request) => Response` callable\n * directly as a Web `fetch` handler or as a Hono\n * route handler.\n *\n * @throws TypeError if `signer` and `selector` are not\n * both set or both unset, or if `selector` does not\n * match `[A-Za-z][A-Za-z0-9_-]{0,62}`.\n *\n * @remarks\n * Behaviour:\n *\n * - `GET` / `HEAD` — body is a fresh 25-byte TAI64N\n * label (`HEAD` omits the body). Response headers:\n * Content-Type `application/tai64n`, Content-Length\n * `25`, Cache-Control `no-store`, plus\n * `TAI-Leap-Seconds` carrying the current count.\n * - `OPTIONS` — `200` with `Allow: GET, HEAD, OPTIONS`.\n * When CORS is enabled (the default) the response\n * also carries `Access-Control-Allow-*` and\n * `-Expose-Headers` per\n * {@link TaistampHandlerConfig.cors}. `OPTIONS` is\n * never signed.\n * - Any other method — `405 Method Not Allowed` with\n * `Allow: GET, HEAD, OPTIONS`.\n * - Request `TAI-Nonce` — on `GET`, the value is echoed\n * verbatim in the response. A missing, empty,\n * duplicated, structurally malformed, or\n * length-out-of-range field is treated as absent (no\n * echo, no signature) per spec §5.4 — see\n * {@link extractNonce}. `HEAD`, `OPTIONS`, and `405`\n * responses never carry `TAI-Nonce` per spec §5.1.\n * - Request `TAI-Nonce` *and* `signer` configured *and*\n * the request method is `GET` — adds\n * `TAI-Key-Selector` and `TAI-Signature` (sf-binary)\n * over the bytes produced by\n * {@link composeSignaturePayload}. The\n * domain-separation tag means the same key cannot\n * be tricked into producing valid signatures for\n * other protocols. `HEAD`, `OPTIONS`, and `405`\n * responses are never signed.\n *\n * The corresponding public key is expected to be\n * published out-of-band as a DNS TXT record at\n * `<selector>._taistamp.<host>` — verifiers fetch the\n * key by selector so the operator can rotate keys by\n * publishing a new selector while the old one is\n * still cached.\n *\n * @see {@link https://cr.yp.to/libtai/tai64.html} for\n * TAI64N format\n */\nexport const newTaistampHandler = (\n config: TaistampHandlerConfig = {},\n): ((request: Request) => Promise<Response>) => {\n const { addSignature, corsHeaders } = fromHandlerConfig(config);\n\n return async (request) => {\n if (request.method === 'OPTIONS') {\n return new Response(undefined, {\n status: 200,\n headers: { allow: ALLOW_HEADER, ...corsHeaders.preflight },\n });\n }\n\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return new Response(undefined, {\n status: 405,\n headers: { allow: ALLOW_HEADER, ...corsHeaders.error },\n });\n }\n\n const nonce = extractNonce(request.headers);\n const label = tai64nLabel();\n\n const headers = new Headers({\n 'cache-control': 'no-store',\n 'content-length': String(TAI64N_CONTENT_LENGTH),\n 'content-type': TAI64N_CONTENT_TYPE,\n [TAI64N_HEADER_LEAP_SECONDS]: String(TAI_LEAP_SECONDS),\n ...corsHeaders.response,\n });\n\n if (nonce && request.method === 'GET') {\n headers.set(TAI64N_HEADER_NONCE, nonce);\n if (addSignature) {\n await addSignature(headers, label, nonce);\n }\n }\n\n const body = request.method === 'HEAD' ? undefined : label;\n return new Response(body, { status: 200, headers });\n };\n};\n","import pkg from '../package.json' with { type: 'json' };\n\n/** Package version from package.json. */\nexport const VERSION: string = pkg.version;\n\nexport {\n newSigner as newEd25519Signer,\n type Signer,\n} from '@kagal/ed25519-secret';\n\nexport { readASCII, readLabel } from './body';\nexport * from './const';\nexport {\n composeSignaturePayload,\n newTaistampHandler,\n type TaistampHandlerConfig,\n} from './handler';\nexport {\n asLeapSeconds,\n extractLeapSeconds,\n type LeapSeconds,\n TAI_LEAP_SECONDS,\n TAI_LEAP_SECONDS_MAX,\n} from './leap-seconds';\nexport {\n asNonce,\n type Nonce,\n} from './nonce';\nexport {\n fromUTC,\n now,\n tai64nLabel,\n tai64nLabelFromUTC,\n} from './utils';\n"],"mappings":";;ACAA,MAAa,gBAAgB;AAG7B,MAAa,cAAc;AAE3B,MAAa,sBAAsB;AACnC,MAAa,wBAAwB;AAErC,MAAa,6BAA6B;AAC1C,MAAa,6BAA6B;AAC1C,MAAa,sBAAsB;AACnC,MAAa,0BAA0B;AAEvC,MAAa,iBAAiB;;;;;;;;;;;;;;;;CCS9B;;;;;;;;;;CAgBA,MAAa,OAAA,WACX,MAAA,CAAA,IACA,EAAA,MAAA,SACoB;CACpB,OAAM;EAGN,OAAI;GACF,+BAA4B;GAC5B,GAAA;EAIF;EACA,WAAO;GACT,+BAAA;;GCzCA,gCAA2B;GAC3B,iCAA2B;GAC3B,0BAA4B;GAC1B,GAAA;EACA;EACA,UAAA;GACA,+BAAA;GACA,iCAAS;GAIX,GAAM;;;;;;;;AA6BN;MAIa,mBAAQ;MAAkB,kBAAW;MAEhD,sBAAuB,YAAA;CACvB,MAAM,MAAA,QACJ,IAAW,0BAAmB;CAChC,IAAA,CAAA,OAAO,CAAA,gBAAA,KAAA,GAAA,GAAA,OAAA,KAAA;QACL,cAAO,OAAA,GAAA,CAAA;;MAQL,oBAAA;MAEG,WAAA,UAAA;KACL,CAAA,SAAA,MAAA,SAAA,MAAA,MAAA,SAAA,OAAA,CAAA,kBAAA,KAAA,KAAA,GAAA,OAAA,KAAA;QACA;;MAGK,gBAAA,YAAA;OACL,QAAA,QAAA,IAAA,mBAAA;CACF,OAAA,UAAA,OAAA,KAAA,IAAA,QAAA,KAAA;AACF;;;;;;;;;CCpEA,OAAa,QAAA,KAAA,IAAA,CAAA;;;;;;CAmBb,OAAa,IAAA,MAAA,SACX,EAAA,EAAA,SAC4B,GAAA,GAAA,IAAA,MAAA,SAAA,EAAA,EAAA,SAAA,GAAA,GAAA,IAAA,KAAA,SAAA,EAAA,EAAA,SAAA,GAAA,GAAA;;MAM5B,sBAAO,QAAA,YAAA,QAAA,GAAA,CAAA;AACT,MAAA,WAAA;;;;;;;;;;CAcA,IAAA,SAAa;;;;;;;;;CAUb,KAAM,IAAA,eAAkB,MAAA;;;;;;;;CAUxB,IAAA,SAAa,KAAA,KAAA,SACX,SAC4B,OAAA,SAAA,UAAA,MAAA,IAAA,UAAA,2DAAA;CAC5B,IAAA,aAAY,KAAQ,GAAI,oBAAA,UAA0B,oBAAA;CAClD,OAAK;;;;;;;;;;;;ECnEP;;;;;;;;GAUA,SAAa;;;;;;;;;;GAWb;;;;;;;;;;;EA4BA,IAAa,SAAA,QAAW,WAAqC,OAAA;GAC3D,QACG,IACD,qBACA,KAAA;GAGF,IAAA,cAAO,MAAA,aAAA,SAAA,OAAA,KAAA;EACT;;;;;;CAOA;;;SC7DS,uBAAA,qBAAA,4BAAA,4BAAA,qBAAA,yBAAA,aAAA,gBAAA,eAAA,kBAAA,sBAAA,SAAA,eAAA,SAAA,yBAAA,oBAAA,SAAA,kBAAA,oBAAA,KAAA,WAAA,WAAA,aAAA"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["pkg.version"],"sources":["../package.json","../src/body.ts","../src/cors.ts","../src/nonce.ts","../src/handler.ts","../src/signature.ts","../src/index.ts"],"sourcesContent":["","import { decodeASCII } from '@kagal/ed25519-secret';\n\nimport { TAI64N_LABEL_LENGTH } from './const';\n\n/**\n * Read a response body as a 7-bit ASCII string.\n *\n * `application/tai64n` is an octet-typed media type, not\n * text: the TAI64N label is a fixed sequence of ASCII\n * bytes. Reading it with `Response.text()` would route\n * the body through UTF-8 decoding and silently mangle any\n * non-ASCII octet, so this reads the raw bytes and decodes\n * them one code point per byte instead.\n *\n * Throws `TypeError` on any byte ≥ `0x80`, surfacing a\n * malformed body rather than masking it; pass `context` to\n * prefix that error message. Consumes the response body,\n * which can only be read once.\n *\n * Use {@link readLabel} when the body is meant to be a\n * TAI64N label and its length should be validated too.\n */\nexport const readASCII = async (\n response: Response,\n context?: string,\n): Promise<string> =>\n decodeASCII(new Uint8Array(await response.arrayBuffer()), context);\n\n/**\n * Read and return the TAI64N label from a response body.\n *\n * Builds on {@link readASCII}, adding the structural\n * invariant every label satisfies: the body is exactly\n * `TAI64N_LABEL_LENGTH` octets. Throws `TypeError` if the\n * length differs or the body carries a non-ASCII octet;\n * pass `context` to prefix that error message. Consumes the\n * response body.\n */\nexport const readLabel = async (\n response: Response,\n context?: string,\n): Promise<string> => {\n const label = await readASCII(response, context);\n // readASCII admitted only 7-bit bytes, so the string has\n // one code unit per octet — its length is the octet count.\n if (label.length !== TAI64N_LABEL_LENGTH) {\n const prefix = context ? `${context}: ` : '';\n throw new TypeError(\n `${prefix}expected ${TAI64N_LABEL_LENGTH}-octet ` +\n `TAI64N label, got ${label.length}`,\n );\n }\n return label;\n};\n","import { atLeast } from '@kagal/ed25519-secret';\n\nimport {\n TAISTAMP_HEADER_KEY_SELECTOR,\n TAISTAMP_HEADER_LEAP_SECONDS,\n TAISTAMP_HEADER_NONCE,\n TAISTAMP_HEADER_SIGNATURE,\n} from './const';\n\n// `Access-Control-Allow-Methods` (Fetch) is the list\n// of methods JS would ever preflight, so `OPTIONS` is\n// omitted. This is intentionally narrower than the\n// `Allow` header (RFC 9110 §9.3.7 method discovery,\n// `GET, HEAD, OPTIONS`) the handler itself emits.\nconst CORS_ALLOW_METHODS = 'GET, HEAD';\nconst CORS_ALLOW_HEADERS = TAISTAMP_HEADER_NONCE;\nconst CORS_EXPOSE_HEADERS = [\n TAISTAMP_HEADER_LEAP_SECONDS,\n TAISTAMP_HEADER_NONCE,\n TAISTAMP_HEADER_KEY_SELECTOR,\n TAISTAMP_HEADER_SIGNATURE,\n].join(', ');\n// Spec §5.2 SHOULDs at least 600s; 10 minutes is the\n// floor the spec example uses and keeps high-traffic\n// cross-origin clients off a pre-flight per fetch. It is\n// both the default and the minimum: a caller-supplied\n// corsMaxAge below this clamps up to it.\nconst CORS_MAX_AGE_MIN = 600;\n\n/**\n * The three CORS header maps the handler splices into\n * responses, keyed by response kind.\n *\n * - `preflight` — added to `OPTIONS 200` replies.\n * - `response` — added to successful `GET` / `HEAD`\n * replies; carries `Access-Control-Expose-Headers`\n * so browser JS can read the `TAI-*` headers.\n * - `error` — added to `405` replies; just the origin\n * header (and `Vary` when scoped).\n */\nexport type CORSHeaderSets = {\n error: Record<string, string>\n preflight: Record<string, string>\n response: Record<string, string>\n};\n\n/**\n * Pre-bake the three CORS header maps the handler\n * splices into responses, keyed by response kind.\n * `cors === false` collapses every map to `{}` so the\n * spread is a no-op; missing or empty input falls back\n * to `'*'`; `cors === '*'` skips `Vary: Origin` (a\n * wildcard does not vary by origin); a scoped origin\n * adds `Vary: Origin` so caches can keep per-origin\n * variants distinct. `corsMaxAge` sets the pre-flight\n * `Access-Control-Max-Age` in seconds, clamped up to a\n * 600s floor; omitted, it defaults to 600.\n */\nexport const buildCORSHeaders = (\n cors: false | string | undefined,\n corsMaxAge?: number,\n): CORSHeaderSets => {\n if (cors === false) {\n return { error: {}, preflight: {}, response: {} };\n }\n const origin = cors || '*';\n const maxAge = atLeast(CORS_MAX_AGE_MIN, corsMaxAge);\n const vary: Record<string, string> =\n origin === '*' ? {} : { Vary: 'Origin' };\n return {\n error: {\n 'Access-Control-Allow-Origin': origin,\n ...vary,\n },\n preflight: {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': CORS_ALLOW_METHODS,\n 'Access-Control-Allow-Headers': CORS_ALLOW_HEADERS,\n 'Access-Control-Expose-Headers': CORS_EXPOSE_HEADERS,\n 'Access-Control-Max-Age': String(maxAge),\n ...vary,\n },\n response: {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Expose-Headers': CORS_EXPOSE_HEADERS,\n ...vary,\n },\n };\n};\n","import { getRandom, isInRange } from '@kagal/ed25519-secret';\n\nimport { TAISTAMP_HEADER_NONCE } from './const';\nimport { encodeSFBinary, SF_BINARY_PATTERN } from './sf-binary';\n\n/**\n * Decoded-length lower bound on `TAI-Nonce` — spec\n * §5.4's normative minimum of 7 octets, providing the\n * client-supplied entropy for the replay defence.\n */\nexport const NONCE_MIN_BYTES = 7;\n\n/**\n * Decoded-length upper bound on `TAI-Nonce` — spec\n * §5.4's normative maximum of 129 octets, capping the\n * nonce's contribution to overall response size.\n */\nexport const NONCE_MAX_BYTES = 129;\n\n/**\n * Wire-form lower bound on `TAI-Nonce`. Spec §5.4 sets\n * the normative bound on decoded length (≥ 7 octets);\n * 14 is the smallest wire form (`:` + 12 base64 chars\n * + `:`) that can decode to 7 octets, so the wire\n * check rejects undersize input before base64 decoding.\n * This also rejects the empty payload (`::`) — a\n * zero-length nonce is treated as absent per spec §5.4.\n * sf-binary is ASCII-only — the string length equals\n * the octet count.\n */\nexport const NONCE_MIN_OCTETS = 14;\n\n/**\n * Wire-form upper bound on `TAI-Nonce`. Spec §5.4 sets\n * the normative bound on decoded length (≤ 129 octets);\n * 174 is the longest wire form (`:` + 172 base64 chars\n * + `:`) whose decoded payload stays within 129 octets,\n * so the wire check rejects oversize input before\n * base64 decoding.\n */\nexport const NONCE_MAX_OCTETS = 174;\n\ndeclare const NonceBrand: unique symbol;\n\n/**\n * `string` that has been confirmed to satisfy the\n * sf-binary syntax of RFC 9651 §3.3.5 and to fall\n * inside the wire-form length range\n * `[NONCE_MIN_OCTETS, NONCE_MAX_OCTETS]` — the\n * pre-decode form of spec §5.4's normative\n * decoded-length bound of 7..129 octets. Construct\n * only via {@link asNonce}, {@link extractNonce}, or\n * {@link newNonce}; the brand prevents arbitrary\n * strings from reaching the signing path.\n */\nexport type Nonce = string & { readonly [NonceBrand]: never };\n\n/**\n * Brand `value` as a {@link Nonce} when it satisfies\n * sf-binary syntax (RFC 9651 §3.3.5) and falls inside\n * `[NONCE_MIN_OCTETS, NONCE_MAX_OCTETS]` — the wire\n * range equivalent to spec §5.4's normative\n * decoded-length bound of 7..129 octets. Returns\n * `undefined` for anything else — every \"treat as\n * absent\" case in spec §5.4 collapsed into one\n * verdict.\n */\nexport const asNonce = (value: string): Nonce | undefined => {\n if (\n !value ||\n value.length < NONCE_MIN_OCTETS ||\n value.length > NONCE_MAX_OCTETS ||\n !SF_BINARY_PATTERN.test(value)\n ) return undefined;\n return value as Nonce;\n};\n\n/**\n * Extract a usable `TAI-Nonce` from headers — the\n * request on the serving side, the response's nonce\n * echo on the verifying side. Returns `undefined` when\n * the field is missing or fails {@link asNonce}\n * validation.\n */\nexport const extractNonce = (headers: Headers): Nonce | undefined => {\n const value = headers.get(TAISTAMP_HEADER_NONCE);\n return value === null ? undefined : asNonce(value);\n};\n\n/**\n * Mint a fresh client `TAI-Nonce`: `byteLength` random\n * bytes framed as an sf-binary item, branded directly —\n * the result is conformant by construction.\n * `byteLength` must be an integer within\n * `[NONCE_MIN_BYTES, NONCE_MAX_BYTES]` —\n * spec §5.4's decoded-length bound; anything else\n * throws `TypeError`. `context` (default `'newNonce'`)\n * prefixes the thrown error.\n */\nexport const newNonce = (\n byteLength: number = 16,\n context: string = 'newNonce',\n): Nonce => {\n if (!isInRange(byteLength, NONCE_MIN_BYTES, NONCE_MAX_BYTES)) {\n const prefix = context ? `${context}: ` : '';\n throw new TypeError(\n `${prefix}expected integer byte length within ` +\n `${NONCE_MIN_BYTES}..${NONCE_MAX_BYTES}, got ${byteLength}`,\n );\n }\n return encodeSFBinary(getRandom(byteLength, context)) as Nonce;\n};\n","import {\n assertValidSelector,\n isInRange,\n type Signer,\n} from '@kagal/ed25519-secret';\n\nimport {\n TAISTAMP_CONTENT_LENGTH,\n TAISTAMP_CONTENT_TYPE,\n TAISTAMP_HEADER_KEY_SELECTOR,\n TAISTAMP_HEADER_LEAP_SECONDS,\n TAISTAMP_HEADER_NONCE,\n TAISTAMP_HEADER_SIGNATURE,\n} from './const';\nimport { buildCORSHeaders } from './cors';\nimport { type LeapSeconds, TAI_LEAP_SECONDS } from './leap-seconds';\nimport { extractNonce, type Nonce } from './nonce';\nimport { decodeSFBinary, encodeSFBinary } from './sf-binary';\nimport { tai64nLabel } from './time';\n\nconst ALLOW_HEADER = 'GET, HEAD, OPTIONS';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * Domain-separation tag prepended to every signed\n * payload. Versioned so a v2 protocol can use the same\n * key without colliding with v1 signatures, and\n * NUL-terminated so the boundary between tag and\n * label is unambiguous.\n */\nconst DOMAIN_SEPARATOR = textEncoder.encode('taistamp-v1\\0');\n\n/**\n * Compose the byte sequence covered by a TAI-Signature.\n *\n * @param label - the 25-byte TAI64N label string the\n * server is returning\n * @param leapSeconds - the leap-seconds count the server\n * advertises in `TAI-Leap-Seconds`\n * @param selector - the key selector the server\n * advertises in `TAI-Key-Selector`; verifiers use\n * this to look up the public key in DNS at\n * `<selector>._taistamp.<host>`\n * @param nonce - the client-supplied nonce, echoed\n * verbatim in `TAI-Nonce`; brand a verifier-side\n * string with {@link asNonce} before passing it in\n * @returns the byte sequence verifiers reconstruct\n * from the response and pass to their public-key\n * verify routine. The framing is the\n * domain-separation tag (`taistamp-v1` plus a\n * trailing NUL byte), then the label bytes, then\n * the leap-seconds count as a 4-byte big-endian\n * unsigned integer, then a 1-byte selector length,\n * then the selector bytes, then the decoded sf-binary\n * octets of the nonce (spec §6.1 — the wire\n * `:base64:` framing is not signed).\n *\n * @remarks\n * Binding the selector into the signed payload stops a\n * downgrade attacker from rewriting `TAI-Key-Selector`\n * to point at a compromised or weaker key — the\n * signature would no longer verify under that key.\n * `leapSeconds` is encoded as a 4-byte big-endian\n * unsigned integer; the selector is length-prefixed by\n * a single byte (selectors are ≤ 63 chars per\n * {@link newTaistampHandler}'s validation).\n */\nexport const composeSignaturePayload = (\n label: string,\n leapSeconds: LeapSeconds,\n selector: string,\n nonce: Nonce,\n): ArrayBuffer => {\n const labelBytes = textEncoder.encode(label);\n const selectorBytes = textEncoder.encode(selector);\n const nonceBytes = decodeSFBinary(nonce, 'composeSignaturePayload');\n\n const buffer = new ArrayBuffer(\n DOMAIN_SEPARATOR.length +\n labelBytes.length +\n 4 +\n 1 +\n selectorBytes.length +\n nonceBytes.length,\n );\n const view = new Uint8Array(buffer);\n\n let offset = 0;\n view.set(DOMAIN_SEPARATOR, offset);\n offset += DOMAIN_SEPARATOR.length;\n view.set(labelBytes, offset);\n offset += labelBytes.length;\n new DataView(buffer).setUint32(offset, leapSeconds, false);\n offset += 4;\n view[offset] = selectorBytes.length;\n offset += 1;\n view.set(selectorBytes, offset);\n offset += selectorBytes.length;\n view.set(nonceBytes, offset);\n\n return buffer;\n};\n\n/**\n * Configuration for {@link newTaistampHandler}.\n *\n * @remarks\n * `signer` and `selector` are co-required: pass both\n * to enable authenticated responses, or neither for\n * an unsigned handler. Passing only one is rejected\n * at construction time — without the selector\n * verifiers cannot find the key in DNS, and a\n * selector without a signer is a misconfiguration.\n */\nexport interface TaistampHandlerConfig {\n /**\n * Key selector advertised in the `TAI-Key-Selector`\n * response header and bound into the signed payload.\n * Verifiers look up the public key at\n * `<selector>._taistamp.<host>` in DNS.\n *\n * Must match `[A-Za-z]([A-Za-z0-9_-]{0,61}[A-Za-z0-9])?` —\n * a single DNS-safe label that starts with a letter,\n * ends with a letter or digit, and is also a valid\n * Structured Field token; rotate by changing the\n * selector and publishing a new TXT record.\n */\n selector?: string\n\n /**\n * {@link Signer} that produces `TAI-Signature` over\n * the framed payload from {@link composeSignaturePayload}.\n * Without a signer the nonce is still echoed but the\n * response is unsigned.\n */\n signer?: Signer\n\n /**\n * CORS origin policy. Defaults to `'*'`; pass `false`\n * to disable CORS entirely, or a specific origin\n * (e.g. `'https://example.com'`) to scope the policy.\n *\n * Every response (`GET` / `HEAD` / `OPTIONS` / `405`)\n * gains `Access-Control-Allow-Origin`; pre-flight\n * `OPTIONS` also carries `-Allow-Methods`,\n * `-Allow-Headers`, `-Expose-Headers`, and\n * `-Max-Age` (default 600s, see {@link corsMaxAge})\n * per spec §5.2; success\n * `GET` / `HEAD` carry `-Expose-Headers` so browser\n * JS can read the `TAI-*` response headers. A\n * non-`'*'` value adds `Vary: Origin` so caches can\n * keep per-origin variants distinct.\n *\n * Disabling CORS does not affect method discovery:\n * `OPTIONS` is still answered with `200` and\n * `Allow: GET, HEAD, OPTIONS` per RFC 9110 §9.3.7.\n */\n cors?: false | string\n\n /**\n * `Access-Control-Max-Age` for pre-flight `OPTIONS`\n * responses, in seconds. Defaults to 600 (10 minutes,\n * the spec §5.2 floor); a value below 600 clamps up to\n * it so the pre-flight stays spec-compliant. Ignored\n * when `cors` is `false`. Must be a non-negative\n * integer.\n */\n corsMaxAge?: number\n}\n\n/**\n * Validate a {@link TaistampHandlerConfig} and return\n * it unchanged when every field is well-formed.\n * Throws `TypeError` otherwise so misconfiguration\n * surfaces at handler construction rather than on the\n * first request.\n *\n * @throws TypeError if `signer` and `selector` are not\n * both set or both unset, if `selector` does not match\n * `[A-Za-z]([A-Za-z0-9_-]{0,61}[A-Za-z0-9])?`, or if\n * `corsMaxAge` is not a non-negative integer.\n */\nconst validateHandlerConfig = (\n config: TaistampHandlerConfig,\n): TaistampHandlerConfig => {\n const { cors, corsMaxAge, selector, signer } = config;\n\n if ((signer === undefined) !== (selector === undefined)) {\n throw new TypeError(\n 'newTaistampHandler: signer and selector must be set together',\n );\n }\n if (cors !== undefined && cors !== false && typeof cors !== 'string') {\n throw new TypeError(\n 'newTaistampHandler: cors must be false or a string origin',\n );\n }\n if (corsMaxAge !== undefined && !isInRange(corsMaxAge, 0)) {\n throw new TypeError(\n 'newTaistampHandler: corsMaxAge must be a non-negative integer',\n );\n }\n if (selector !== undefined) {\n assertValidSelector(selector, 'newTaistampHandler');\n }\n\n return config;\n};\n\n/**\n * Validate a {@link TaistampHandlerConfig} and derive\n * the construction-time state the handler closure\n * captures: the pre-baked CORS header maps and an\n * `addSignature` helper that mutates a response\n * `Headers` to carry `TAI-Key-Selector` and\n * `TAI-Signature` over the framed payload, present\n * only when both `signer` and `selector` are\n * configured. Validation is delegated to\n * {@link validateHandlerConfig}.\n *\n * @throws TypeError per {@link validateHandlerConfig}.\n */\nconst fromHandlerConfig = (config: TaistampHandlerConfig) => {\n const { cors, corsMaxAge, selector, signer } = validateHandlerConfig(config);\n\n const corsHeaders = buildCORSHeaders(cors, corsMaxAge);\n\n const addSignature = selector !== undefined && signer !== undefined ?\n async (\n headers: Headers,\n label: string,\n nonce: Nonce,\n ): Promise<void> => {\n const payload = composeSignaturePayload(\n label, TAI_LEAP_SECONDS, selector, nonce,\n );\n const signature = await signer.sign(payload);\n headers.set(TAISTAMP_HEADER_KEY_SELECTOR, selector);\n headers.set(\n TAISTAMP_HEADER_SIGNATURE,\n encodeSFBinary(new Uint8Array(signature)),\n );\n } :\n undefined;\n\n return { addSignature, corsHeaders };\n};\n\n/**\n * Build a handler for `/.well-known/taistamp`.\n *\n * @param config - optional {@link TaistampHandlerConfig}\n * @returns an `async (request) => Response` callable\n * directly as a Web `fetch` handler or as a Hono\n * route handler.\n *\n * @throws TypeError if `signer` and `selector` are not\n * both set or both unset, if `selector` does not match\n * `[A-Za-z]([A-Za-z0-9_-]{0,61}[A-Za-z0-9])?`, or if\n * `corsMaxAge` is not a non-negative integer.\n *\n * @remarks\n * Behaviour:\n *\n * - `GET` / `HEAD` — body is a fresh 25-byte TAI64N\n * label (`HEAD` omits the body). Response headers:\n * Content-Type `application/tai64n`, Content-Disposition\n * `inline` (so a browser renders the label in place\n * rather than offering it as a download), Content-Length\n * `25`, Cache-Control `no-store`, plus\n * `TAI-Leap-Seconds` carrying the current count.\n * - `OPTIONS` — `200` with `Allow: GET, HEAD, OPTIONS`.\n * When CORS is enabled (the default) the response\n * also carries `Access-Control-Allow-*` and\n * `-Expose-Headers` per\n * {@link TaistampHandlerConfig.cors}. `OPTIONS` is\n * never signed.\n * - Any other method — `405 Method Not Allowed` with\n * `Allow: GET, HEAD, OPTIONS`.\n * - Request `TAI-Nonce` — on `GET`, the value is echoed\n * verbatim in the response. A missing, empty,\n * duplicated, structurally malformed, or\n * length-out-of-range field is treated as absent (no\n * echo, no signature) per spec §5.4 — see\n * {@link extractNonce}. `HEAD`, `OPTIONS`, and `405`\n * responses never carry `TAI-Nonce` per spec §5.1.\n * - Request `TAI-Nonce` *and* `signer` configured *and*\n * the request method is `GET` — adds\n * `TAI-Key-Selector` and `TAI-Signature` (sf-binary)\n * over the bytes produced by\n * {@link composeSignaturePayload}. The\n * domain-separation tag means the same key cannot\n * be tricked into producing valid signatures for\n * other protocols. `HEAD`, `OPTIONS`, and `405`\n * responses are never signed.\n *\n * The corresponding public key is expected to be\n * published out-of-band as a DNS TXT record at\n * `<selector>._taistamp.<host>` — verifiers fetch the\n * key by selector so the operator can rotate keys by\n * publishing a new selector while the old one is\n * still cached.\n *\n * @see {@link https://cr.yp.to/libtai/tai64.html} for\n * TAI64N format\n */\nexport const newTaistampHandler = (\n config: TaistampHandlerConfig = {},\n): ((request: Request) => Promise<Response>) => {\n const { addSignature, corsHeaders } = fromHandlerConfig(config);\n\n return async (request) => {\n if (request.method === 'OPTIONS') {\n return new Response(undefined, {\n status: 200,\n headers: { Allow: ALLOW_HEADER, ...corsHeaders.preflight },\n });\n }\n\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return new Response(undefined, {\n status: 405,\n headers: { Allow: ALLOW_HEADER, ...corsHeaders.error },\n });\n }\n\n const nonce = extractNonce(request.headers);\n const label = tai64nLabel();\n\n const headers = new Headers({\n 'Cache-Control': 'no-store',\n 'Content-Disposition': 'inline',\n 'Content-Length': String(TAISTAMP_CONTENT_LENGTH),\n 'Content-Type': TAISTAMP_CONTENT_TYPE,\n [TAISTAMP_HEADER_LEAP_SECONDS]: String(TAI_LEAP_SECONDS),\n ...corsHeaders.response,\n });\n\n if (nonce && request.method === 'GET') {\n headers.set(TAISTAMP_HEADER_NONCE, nonce);\n if (addSignature) {\n await addSignature(headers, label, nonce);\n }\n }\n\n const body = request.method === 'HEAD' ? undefined : label;\n return new Response(body, { status: 200, headers });\n };\n};\n","import { type Bytes } from '@kagal/ed25519-secret';\n\nimport { TAISTAMP_HEADER_SIGNATURE } from './const';\nimport { decodeSFBinary, SF_BINARY_PATTERN } from './sf-binary';\n\n/**\n * Decoded length of every valid `TAI-Signature`: a raw\n * Ed25519 signature is 64 octets (RFC 8032).\n */\nexport const SIGNATURE_BYTES = 64;\n\n/**\n * Decode a `TAI-Signature` wire value into the raw\n * Ed25519 signature bytes. Returns `undefined` when\n * `value` fails sf-binary syntax (RFC 9651 §3.3.5) or\n * does not decode to exactly `SIGNATURE_BYTES`\n * octets — a malformed field is equivalent to a\n * missing one. This validates form only; semantics\n * involving other fields (nonce echo, selector,\n * verification) stay with the caller.\n */\nexport const asSignature = (value: string): Bytes | undefined => {\n if (!SF_BINARY_PATTERN.test(value)) return undefined;\n const bytes = decodeSFBinary(value);\n return bytes.length === SIGNATURE_BYTES ? bytes : undefined;\n};\n\n/**\n * Extract the raw Ed25519 signature from response\n * headers. Returns `undefined` when the\n * `TAI-Signature` field is missing or fails\n * {@link asSignature} validation.\n */\nexport const extractSignature = (\n headers: Headers,\n): Bytes | undefined => {\n const value = headers.get(TAISTAMP_HEADER_SIGNATURE);\n return value === null ? undefined : asSignature(value);\n};\n","import pkg from '../package.json' with { type: 'json' };\n\n/** Package version from package.json. */\nexport const VERSION: string = pkg.version;\n\nexport {\n type KeyConfig,\n type KeyRecord,\n newSigner as newEd25519Signer,\n parseRecordToVerifier,\n parseSecretsToKeys,\n parseSecretToKey,\n type Signer,\n type Verifier,\n} from '@kagal/ed25519-secret';\n\nexport { readASCII, readLabel } from './body';\nexport {\n TAISTAMP_CONTENT_LENGTH,\n TAISTAMP_CONTENT_TYPE,\n TAISTAMP_HEADER_KEY_SELECTOR,\n TAISTAMP_HEADER_LEAP_SECONDS,\n TAISTAMP_HEADER_NONCE,\n TAISTAMP_HEADER_SIGNATURE,\n TAISTAMP_PATH,\n} from './const';\nexport {\n composeSignaturePayload,\n newTaistampHandler,\n type TaistampHandlerConfig,\n} from './handler';\nexport {\n asLeapSeconds,\n extractLeapSeconds,\n type LeapSeconds,\n TAI_LEAP_SECONDS,\n TAI_LEAP_SECONDS_MAX,\n} from './leap-seconds';\nexport {\n asNonce,\n extractNonce,\n newNonce,\n type Nonce,\n} from './nonce';\nexport { asSignature, extractSignature } from './signature';\nexport { tai64nLabelFromUTC, tai64nLabelToUTC } from './time';\n"],"mappings":";;;;;;;;;;;;;;;;;;CCsBA;;;;;;;;;;CAgBA,MAAa,SAAA,QAAY,kBAEvB,UACoB;CACpB,MAAM,OAAA,WAAc,MAAU,CAAA,IAAA,EAAA,MAAU,SAAO;CAG/C,OAAI;EACF,OAAM;GACN,+BACY;GAGd,GAAA;EACA;EACF,WAAA;;GCvCA,gCAA2B;GAC3B,gCAA2B;GAC3B,iCAA4B;GAC1B,0BAAA,OAAA,MAAA;GACA,GAAA;EACA;EACA,UAAA;GACA,+BAAS;GAMX,iCAAyB;;;;;MAoCZ,WAAQ,UAAA;KAAG,CAAA,SAAY,MAAA,SAAA,MAAA,MAAA,SAAA,OAAA,CAAA,kBAAA,KAAA,KAAA,GAAA,OAAA,KAAA;QAAG;;MAGrC,gBAAe,YAAQ;CACvB,MAAM,QACJ,QAAA,IAAW,qBAAmB;CAChC,OAAO,UAAA,OAAA,KAAA,IAAA,QAAA,KAAA;;MAGA,YAAA,aAAA,IAAA,UAAA,eAAA;KACL,CAAA,UAAA,YAAA,GAAA,GAAA,GAAA;EACA,MAAA,SAAW,UAAA,GAAA,QAAA,MAAA;QACT,IAAA,UAAA,GAAA,OAAA,kDAA+B,YAAA;;QAE/B,eAAA,UAAA,YAAgC,OAAA,CAAA;;MAG7B,eAAA;MACL,cAAA,IAAA,YAAA;MAEE,mBAAA,YAA+B,OAAA,eAAA;MAE5B,2BAAA,OAAA,aAAA,UAAA,UAAA;OACL,aAAA,YAAA,OAAA,KAAA;CACF,MAAA,gBAAA,YAAA,OAAA,QAAA;CACF,MAAA,aAAA,eAAA,OAAA,yBAAA;;;;;;;CC9EA,UAAa,WAAA;;;;;;CAOb,UAAa,cAAkB;;;;;;;;;;;AAa/B;;;;;;;;GAUA,QAAa,IAAA,8BAAmB,QAAA;;;;;;;;;;GA2BhC,QAAa;GACX,SACG;IAKH,OAAO;IACT,GAAA,YAAA;;;;;;;;GASA;EACE,CAAA;EACA,MAAO,QAAA,aAAiB,QAAY,OAAQ;EAC9C,MAAA,QAAA,YAAA;;;;;;;;;;;GAYA,IAAa,cACX,MAAA,aACA,SAAkB,OAAA,KACR;EACV;EACE,MAAM,OAAA,QAAS,WAAa,SAAQ,KAAM,IAAA;EAC1C,OAAM,IAAI,SACR,MAAG;GAGP,QAAA;GACA;EACF,CAAA;;AC3FA;;;;;AAWA"}
|