@kagal/taistamp 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -239,14 +239,19 @@ or fall back to a strict-verify library such as
239
239
  ```typescript
240
240
  import {
241
241
  asNonce,
242
- extractLeapSeconds,
243
242
  composeSignaturePayload,
243
+ extractLeapSeconds,
244
+ readLabel,
244
245
  } from '@kagal/taistamp';
245
246
 
246
247
  const response = await fetch(taistampURL, {
247
248
  headers: { 'TAI-Nonce': clientNonce },
248
249
  });
249
- const label = await response.text();
250
+ // `application/tai64n` is octet-typed, not text. `readLabel`
251
+ // reads the raw body and decodes the 25-octet ASCII label;
252
+ // never `response.text()`, which UTF-8-decodes and would
253
+ // mangle a non-ASCII octet instead of surfacing it.
254
+ const label = await readLabel(response);
250
255
  const selector = response.headers.get('TAI-Key-Selector')!;
251
256
  const sigSf = response.headers.get('TAI-Signature')!;
252
257
 
@@ -342,6 +347,16 @@ Re-exported from `@kagal/ed25519-secret`:
342
347
  For verifier-side validation of a signed response
343
348
  (see [Verifying a signature](#verifying-a-signature)):
344
349
 
350
+ - `readLabel(response, context?)` — read the TAI64N
351
+ label from a response body. Use this instead of
352
+ `response.text()`, which UTF-8-decodes the octet-typed
353
+ `application/tai64n` body. Throws `TypeError` unless
354
+ the body is exactly 25 ASCII octets; pass `context` to
355
+ prefix the error. Consumes the body.
356
+ - `readASCII(response, context?)` — the unvalidated
357
+ reader behind `readLabel`: decode any response body as
358
+ 7-bit ASCII, with no length check. Throws `TypeError`
359
+ on any byte ≥ `0x80`; consumes the body.
345
360
  - `composeSignaturePayload(label, leapSeconds,
346
361
  selector, nonce)` — reconstructs the exact byte
347
362
  sequence the server signed.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,34 @@
1
1
  import { Signer, Signer as Signer$1, newSigner as newEd25519Signer } from "@kagal/ed25519-secret";
2
+ /**
3
+ * Read a response body as a 7-bit ASCII string.
4
+ *
5
+ * `application/tai64n` is an octet-typed media type, not
6
+ * text: the TAI64N label is a fixed sequence of ASCII
7
+ * bytes. Reading it with `Response.text()` would route
8
+ * the body through UTF-8 decoding and silently mangle any
9
+ * non-ASCII octet, so this reads the raw bytes and decodes
10
+ * them one code point per byte instead.
11
+ *
12
+ * Throws `TypeError` on any byte ≥ `0x80`, surfacing a
13
+ * malformed body rather than masking it; pass `context` to
14
+ * prefix that error message. Consumes the response body,
15
+ * which can only be read once.
16
+ *
17
+ * Use {@link readLabel} when the body is meant to be a
18
+ * TAI64N label and its length should be validated too.
19
+ */
20
+ declare const readASCII: (response: Response, context?: string) => Promise<string>;
21
+ /**
22
+ * Read and return the TAI64N label from a response body.
23
+ *
24
+ * Builds on {@link readASCII}, adding the structural
25
+ * invariant every label satisfies: the body is exactly
26
+ * `TAI64N_CONTENT_LENGTH` octets. Throws `TypeError` if the
27
+ * length differs or the body carries a non-ASCII octet;
28
+ * pass `context` to prefix that error message. Consumes the
29
+ * response body.
30
+ */
31
+ declare const readLabel: (response: Response, context?: string) => Promise<string>;
2
32
  declare const TAISTAMP_PATH = "/.well-known/taistamp";
3
33
  /** @deprecated Renamed to {@link TAISTAMP_PATH}. */
4
34
  declare const TAI64N_PATH = "/.well-known/taistamp";
@@ -240,5 +270,5 @@ declare const tai64nLabel: (value?: timestamp) => string;
240
270
  declare const tai64nLabelFromUTC: (utc: number) => string;
241
271
  /** Package version from package.json. */
242
272
  declare const VERSION: string;
243
- export { type LeapSeconds, type Nonce, type Signer, TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, type TaistampHandlerConfig, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, tai64nLabel, tai64nLabelFromUTC };
273
+ export { type LeapSeconds, type Nonce, type Signer, TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, type TaistampHandlerConfig, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, readASCII, readLabel, tai64nLabel, tai64nLabelFromUTC };
244
274
  //# sourceMappingURL=index.d.mts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,34 @@
1
1
  import { Signer, Signer as Signer$1, newSigner as newEd25519Signer } from "@kagal/ed25519-secret";
2
+ /**
3
+ * Read a response body as a 7-bit ASCII string.
4
+ *
5
+ * `application/tai64n` is an octet-typed media type, not
6
+ * text: the TAI64N label is a fixed sequence of ASCII
7
+ * bytes. Reading it with `Response.text()` would route
8
+ * the body through UTF-8 decoding and silently mangle any
9
+ * non-ASCII octet, so this reads the raw bytes and decodes
10
+ * them one code point per byte instead.
11
+ *
12
+ * Throws `TypeError` on any byte ≥ `0x80`, surfacing a
13
+ * malformed body rather than masking it; pass `context` to
14
+ * prefix that error message. Consumes the response body,
15
+ * which can only be read once.
16
+ *
17
+ * Use {@link readLabel} when the body is meant to be a
18
+ * TAI64N label and its length should be validated too.
19
+ */
20
+ declare const readASCII: (response: Response, context?: string) => Promise<string>;
21
+ /**
22
+ * Read and return the TAI64N label from a response body.
23
+ *
24
+ * Builds on {@link readASCII}, adding the structural
25
+ * invariant every label satisfies: the body is exactly
26
+ * `TAI64N_CONTENT_LENGTH` octets. Throws `TypeError` if the
27
+ * length differs or the body carries a non-ASCII octet;
28
+ * pass `context` to prefix that error message. Consumes the
29
+ * response body.
30
+ */
31
+ declare const readLabel: (response: Response, context?: string) => Promise<string>;
2
32
  declare const TAISTAMP_PATH = "/.well-known/taistamp";
3
33
  /** @deprecated Renamed to {@link TAISTAMP_PATH}. */
4
34
  declare const TAI64N_PATH = "/.well-known/taistamp";
@@ -240,5 +270,5 @@ declare const tai64nLabel: (value?: timestamp) => string;
240
270
  declare const tai64nLabelFromUTC: (utc: number) => string;
241
271
  /** Package version from package.json. */
242
272
  declare const VERSION: string;
243
- export { type LeapSeconds, type Nonce, type Signer, TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, type TaistampHandlerConfig, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, tai64nLabel, tai64nLabelFromUTC };
273
+ export { type LeapSeconds, type Nonce, type Signer, TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, type TaistampHandlerConfig, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, readASCII, readLabel, tai64nLabel, tai64nLabelFromUTC };
244
274
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { assertValidSelector, decodeBase64, encodeBase64, newSigner as newEd25519Signer } from "@kagal/ed25519-secret";
2
- var version = "0.1.0";
1
+ import { assertValidSelector, decodeASCII, decodeBase64, encodeBase64, newSigner as newEd25519Signer } from "@kagal/ed25519-secret";
2
+ var version = "0.1.1";
3
3
  const TAISTAMP_PATH = "/.well-known/taistamp";
4
4
  const TAI64N_PATH = TAISTAMP_PATH;
5
5
  const TAI64N_CONTENT_TYPE = "application/tai64n";
@@ -9,6 +9,15 @@ const TAI64N_HEADER_LEAP_SECONDS = "TAI-Leap-Seconds";
9
9
  const TAI64N_HEADER_NONCE = "TAI-Nonce";
10
10
  const TAI64N_HEADER_SIGNATURE = "TAI-Signature";
11
11
  const TAI64_EPOCH_HI = 1073741824;
12
+ const readASCII = async (response, context) => decodeASCII(new Uint8Array(await response.arrayBuffer()), context);
13
+ const readLabel = async (response, context) => {
14
+ const label = await readASCII(response, context);
15
+ if (label.length !== 25) {
16
+ const prefix = context ? `${context}: ` : "";
17
+ throw new TypeError(`${prefix}expected 25-octet TAI64N label, got ${label.length}`);
18
+ }
19
+ return label;
20
+ };
12
21
  const CORS_ALLOW_METHODS = "GET, HEAD";
13
22
  const CORS_ALLOW_HEADERS = TAI64N_HEADER_NONCE;
14
23
  const CORS_EXPOSE_HEADERS = [
@@ -166,6 +175,6 @@ const newTaistampHandler = (config = {}) => {
166
175
  };
167
176
  };
168
177
  const VERSION = version;
169
- export { TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, tai64nLabel, tai64nLabelFromUTC };
178
+ export { TAI64N_CONTENT_LENGTH, TAI64N_CONTENT_TYPE, TAI64N_HEADER_KEY_SELECTOR, TAI64N_HEADER_LEAP_SECONDS, TAI64N_HEADER_NONCE, TAI64N_HEADER_SIGNATURE, TAI64N_PATH, TAI64_EPOCH_HI, TAISTAMP_PATH, TAI_LEAP_SECONDS, TAI_LEAP_SECONDS_MAX, VERSION, asLeapSeconds, asNonce, composeSignaturePayload, extractLeapSeconds, fromUTC, newEd25519Signer, newTaistampHandler, now, readASCII, readLabel, tai64nLabel, tai64nLabelFromUTC };
170
179
 
171
180
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["pkg.version"],"sources":["../package.json","../src/const.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 {\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 * 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;ACD9B,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI;AAIX,MAAM,eAAe;;;;;;;;;;EA6BrB,OAAa;GAGX,+BACS;GAAE,GAAA;EAAW;EAAe,WAAW;GAAE,+BAAA;GAElD,gCAAuB;GACvB,gCACoB;GACpB,iCAAO;GACL,0BAAO;GACL,GAAA;;EAEF,UAAA;GACA,+BAAW;GACT,iCAA+B;GAC/B,GAAA;;;;MAMF,uBAAU;MAER,iBAAA,UAAA;KACA,CAAG,OAAA,UAAA,KAAA,KAAA,QAAA,KAAA,QAAA,YAAA,OAAA,KAAA;QACL;;;;;;;;;AC/CJ,MAAa,oBACX;MAOA,WAAO,UAAA;CACT,IAAA,CAAA,SAAA,MAAA,SAAA,MAAA,MAAA,SAAA,OAAA,CAAA,kBAAA,KAAA,KAAA,GAAA,OAAA,KAAA;;;;;;;;;;;EAcA,QAAa;;;;;;;;;CAUb,MAAM,QAAA,MAAA;;;;;;;AAUN,MAAa,mBAAA,YACX,OAC4B,eAAA;MAEvB,2BAAwB,OAAQ,aAAU,UAAA,UAAA;CAC/C,MAAA,aAAO,YAAwB,OAAC,KAAA;CAClC,MAAA,gBAAA,YAAA,OAAA,QAAA;;;;;;;;;;;CCrEA,KAAa,UAAA,cAAmB;;;;;;;;CAUhC,MAAa,EAAA,MAAA,UAAmB,WAAA;;;;;;;;;CAWhC,OAAM;;;;;;;;;;AA4BN,MAAa,sBAAgD,SAAA,CAAA,MAAA;CAC3D,MACG,EAAA,cACK,gBACN,kBAAM,MACL;CAEH,OAAO,OAAA,YAAA;EACT,IAAA,QAAA,WAAA,WAAA,OAAA,IAAA,SAAA,KAAA,GAAA;;;;;;EAOA,CAAA;EACE,IAAA,QAAM,WAAgB,SAAI,QAAA,WAAmB,QAAA,OAAA,IAAA,SAAA,KAAA,GAAA;GAC7C,QAAO;GACT,SAAA;;ICpEA,GAAa,YAAW;GAItB;EAAS,CAAA;EAAK,MADA,QAAM,aAAQ,QAAA,OAAA;EACR,MAAA,QAAA,YAAA;EAAyB,MAAA,UAAA,IAAA,QAAA;GAC/C,iBAAA;GAEA,kBAAoC,OAAA,EAAA;GAElC,gBADY;IAEd,6BAAA,OAAA,EAAA;GAEA,GAAa,YAAA;EACX,CAAA;EAEA,IAAA,SAAc,QAAK,WAAY,OAAQ;GACvC,QAAM,IAAQ,qBAAM,KAAA;GAMpB,IAAA,cAJuB,MAAS,aAAa,SAI3B,OAHK,KAAA;EAIzB;EAEA,MAAa,OAAA,QAAA,WAAsB,SAAwB,KAAY,IAAA;EAEvE,OAAM,IAAA,SAAW,MAAA;;GCjBjB;EAEA,CAAA"}
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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kagal/taistamp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Signed TAI64N timestamps over HTTP",
6
6
  "author": "Apptly Software Ltd <oss@apptly.co>",
@@ -41,7 +41,7 @@
41
41
  "dist"
42
42
  ],
43
43
  "dependencies": {
44
- "@kagal/ed25519-secret": "^0.2.0"
44
+ "@kagal/ed25519-secret": "^0.2.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@cloudflare/vitest-pool-workers": "^0.13.1",
@@ -52,7 +52,7 @@
52
52
  "@types/node": "^20.19.41",
53
53
  "@vitest/coverage-istanbul": "^4.1.6",
54
54
  "eslint": "^9.39.4",
55
- "npm-run-all2": "^8.0.4",
55
+ "npm-run-all2": "^9.0.1",
56
56
  "obuild": "^0.4.35",
57
57
  "publint": "^0.3.21",
58
58
  "rimraf": "^6.1.3",