@agledger/verify-core 1.4.2 → 2.0.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/dist/failures.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * CHAIN_* per-record (and per-org schema-event) hash-chain entry checks
10
10
  * CHECKPOINT_* vault checkpoint cross-check against the live chain
11
11
  * TENANT_* org_admin_reads Merkle log + signed tree heads
12
+ * KEY_* the vault key statements themselves (the key registry)
12
13
  * <bare> input/format-level failures that precede any chain walk
13
14
  *
14
15
  * Every code carries an actionable next step (`suggestion`) so a result is a
@@ -30,13 +31,57 @@
30
31
  * a retired/wrong-key policy hit is alertable apart
31
32
  * from a benign missing key.
32
33
  * - CHAIN_KEY_EXPIRED (new) temporal key-validity: entry written after the
33
- * signing key's retired_at.
34
+ * signing key's retired_at, or after its
35
+ * distrustedKeys cutoff.
34
36
  * - CHAIN_KEY_NOT_YET_ACTIVE entry written before the key's activated_at.
35
37
  * Split from CHAIN_KEY_EXPIRED so a consumer is
36
38
  * not told "expired" about a key that had not
37
39
  * started yet.
38
40
  * - CHAIN_EMPTY (new) a chain/vault with nothing to verify is a non-clean
39
41
  * verdict, never a silent pass.
42
+ *
43
+ * Later additions:
44
+ * - CHAIN_ENTRY_UNSIGNED engine mirror of `signature_missing`: an entry with
45
+ * no signing key id after a signed entry in its
46
+ * chain, or written at or after the earliest
47
+ * activatedAt in the key set. Earlier unsigned
48
+ * entries stay reduced coverage.
49
+ * - CHECKPOINT_UNSIGNED engine mirror of `checkpoint_unsigned`: the same
50
+ * instant, applied to an unsigned checkpoint.
51
+ * - TENANT_READ_LEAF_UNSIGNED and TENANT_CHECKPOINT_UNSIGNED the same two
52
+ * rules on the org_admin_reads log (engine
53
+ * `leaf_signature_missing`, `checkpoint_unsigned`).
54
+ * - CHAIN_SIGNING_KEY_UNANCHORED engine mirror of `signing_key_unanchored`:
55
+ * the entry's key is not linked by signed key
56
+ * statements to a pinned trust anchor. With
57
+ * CHECKPOINT_KEY_UNANCHORED,
58
+ * TENANT_READ_KEY_UNANCHORED and
59
+ * TENANT_CHECKPOINT_KEY_UNANCHORED for the
60
+ * engine's `checkpoint_key_unanchored` and
61
+ * `leaf_key_unanchored`.
62
+ * - KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID, CHAIN_KEY_WINDOW_DRIFT
63
+ * engine mirrors of the key registry findings
64
+ * `key_statement_invalid`, `key_closure_invalid`
65
+ * and `key_window_drift`. They are about the
66
+ * registry, not about any one entry.
67
+ * - CHECKPOINT_CLAIM_MISMATCH, TENANT_READ_CLAIM_MISMATCH,
68
+ * TENANT_CHECKPOINT_CLAIM_MISMATCH engine mirrors of the vault's
69
+ * `checkpoint_claim_mismatch` and the read log's
70
+ * `leaf_claim_mismatch` and
71
+ * `checkpoint_claim_mismatch`: the claim signed
72
+ * inside the envelope does not decode, or says
73
+ * something the row's columns do not.
74
+ *
75
+ * Server-side cert re-checks are not mirrored here. The engine's chain
76
+ * verification also reports `cert_missing`, `cert_actor_drift`,
77
+ * `cert_window_drift`, `cert_expired` and `agent_signature_invalid`, by
78
+ * comparing what an entry sealed in `predicate.on_behalf_of.cert` against the
79
+ * live `ephemeral_certs` row. Neither the export nor the dump carries that
80
+ * table, so an offline verifier cannot reproduce those comparisons, and it
81
+ * does not need to: it trusts only the signed bytes, which already fix the
82
+ * sealed cert id, thumbprint and expiry. The one cert-related check that can
83
+ * run offline is the agent signature, and only when the caller supplies the
84
+ * cert's public key (CHAIN_AGENT_SIGNATURE_INVALID below).
40
85
  */
41
86
  /**
42
87
  * Actionable next step per failure code. Kept terse and operational: what the
@@ -49,29 +94,45 @@ const SUGGESTIONS = {
49
94
  CHAIN_GENESIS_INVALID: 'The first entry must carry previousHash = null. A non-null genesis link means the head of the chain was removed. Request the full chain from position 1.',
50
95
  CHAIN_LINK_BROKEN: 'An entry\'s previousHash does not match the prior entry\'s payloadHash. The chain was edited between these two entries. Treat every entry from this position on as untrusted.',
51
96
  CHAIN_HASH_MISMATCH: 'sha256(cose_sign1) does not equal the stored payloadHash. The envelope bytes or the stored hash were altered. The signed bytes are authoritative; the row was tampered with.',
52
- CHAIN_MALFORMED_ENTRY: 'An entry is missing a required field (coseSign1 or payloadHash). The export/dump is incomplete or corrupt. Regenerate it.',
97
+ CHAIN_MALFORMED_ENTRY: 'An entry is missing a field the engine writes on every entry (coseSign1, payloadHash, or a parseable createdAt where a key window or the start of signing needs one), or carries it as another type. The export/dump is incomplete or was edited, and an entry the verifier cannot place is never read as early unsigned history. Regenerate the export/dump from the operator and re-run.',
53
98
  CHAIN_COSE_DECODE_FAILED: 'The COSE_Sign1 envelope did not decode as a tagged 4-element structure. The signed bytes are corrupt. Regenerate the export/dump.',
54
99
  CHAIN_COSE_HEADER_MISMATCH: 'The position/previousHash signed in the COSE protected header disagree with the row columns. The visible columns were renumbered after signing. Trust the signed header, not the columns.',
55
100
  CHAIN_PAYLOAD_BINDING_MISMATCH: 'The signed payload\'s structure no longer matches the canonical projection of the row columns it is bound to: the visible (denormalised) payload was altered after signing. This is a binding-integrity failure, not a judgement on content.',
56
101
  CHAIN_OIDC_ACTOR_MISMATCH: 'The denormalised actor OIDC issuer/subject columns disagree with the identity signed in predicate.on_behalf_of. The actor columns were tampered with after signing.',
57
102
  CHAIN_SIGNATURE_INVALID: 'The COSE_Sign1 signature did not verify against the entry\'s signing key, under the algorithm that key commits to. The entry was forged or altered: obtain the verification keys out of band and re-run.',
58
103
  CHAIN_SIGNATURE_MISSING_KEY: 'No public key was available for the entry\'s signingKeyId. Supply the key out of band (GET /v1/verification-keys or /.well-known/scitt-keys) and re-run.',
59
- CHAIN_KEY_POLICY_VIOLATION: 'The entry\'s signing key violates the caller\'s trust policy (requireKeyId, or out-of-band keys required). Re-run with the expected key id, or with keys obtained out of band rather than the engine-embedded set.',
60
- CHAIN_KEY_EXPIRED: 'The entry was written AFTER its signing key was retired. Possible use of a compromised retired key: check the key rotation and retention record for that key id.',
104
+ CHAIN_KEY_POLICY_VIOLATION: 'The entry\'s signing key violates the caller\'s key policy (requireKeyId, or requireSuppliedKeys refusing a key the artifact embeds). Re-run with the expected key id, or supply the keys yourself. Where a key came from does not make it trusted: pin a trust anchor (trustAnchors) for that.',
105
+ CHAIN_KEY_EXPIRED: 'The entry was written AFTER its signing key was retired, or after the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for that key; the detail says which. Possible use of a compromised key: check the key rotation and retention record for that key id.',
61
106
  CHAIN_KEY_NOT_YET_ACTIVE: 'The entry was written BEFORE its signing key was activated. Not a rotation problem: the usual causes are a backdated entry or clock skew between the signer and the key registry. Compare the entry write time against the key activation time before treating this as tamper.',
62
107
  CHAIN_ALG_MISMATCH: 'The algorithm in the signed protected header (label 1) is not one the entry\'s trusted verification key can produce, or the key registry\'s declared algorithm contradicts the key material itself. Tamper class: the header alg or the key registry was rewritten. Treat the entry as forged; obtain the verification keys out of band and re-run.',
63
108
  CHAIN_UNSUPPORTED_ALGORITHM: 'The entry\'s trusted verification key commits to a signature algorithm that could not be computed, either because this verifier build does not implement it or because the host runtime refused it (an active OpenSSL FIPS provider carries no EdDSA). The chain is NOT verified, and this is NOT tamper evidence: the signature was never checked. Upgrade the verifier, or re-run on a host without the restriction. Never treat this result as a pass.',
64
109
  CHAIN_SIGNING_KEY_DRIFT: 'The entry\'s signingKeyId column names a different key than the signature-covered kid in the COSE protected header. The column is a denormalized convenience and was rewritten after signing (possibly to point verification at another key). Trust the signed kid; treat the row as tampered.',
110
+ CHAIN_ACTOR_ATTRIBUTION_MISMATCH: 'The entry\'s actorId / actorOwnerId columns name a different actor than the signature-covered actor claim in the COSE protected header (CWT_Claims label 15, private label -65539). The columns are the projection a report displays and they were rewritten after signing, re-attributing the action to another actor. Trust the signed claim; treat the row as tampered and re-obtain the export from the operator.',
111
+ CHAIN_AGENT_SIGNATURE_INVALID: 'The agent signature sealed in predicate.on_behalf_of.agent_signature does not verify under the supplied key whose RFC 7638 thumbprint the entry itself names, or is sealed in a shape nothing can verify. The engine checks this signature at intake and the envelope signature says the engine wrote it, so this is not a caller mistake: treat the agent attribution of this entry as unproven and escalate to the operator.',
112
+ CHAIN_ENTRY_UNSIGNED: 'The entry carries no signing key id where the install could not have written an unsigned entry: after a signed entry in the same chain, or at or after the earliest activation time in the signing key set (retired keys included). From that instant every writer holds a registered key, so this is what a writer without one leaves on the chain, or a signed row whose key id was nulled. Treat the entry as forged and escalate to the operator. Unsigned entries from before the first key activation stay reduced signature coverage, not a break.',
113
+ CHAIN_SIGNING_KEY_UNANCHORED: 'The entry is signed by a key that no signed key statement links to a trust anchor you pinned. Anything with write access to the Server\'s database can register a key and sign entries with it; what it cannot write is a statement signed by a key you trust. Treat the entry as forged. If the key is one you vouch for, pin it (trustAnchors) from a source outside the Server, never from the document that served it.',
114
+ CHAIN_KEY_WINDOW_DRIFT: 'A key registry column (activatedAt, retiredAt or status in a dump row or key document) differs from the value its signed key statements carry. The signed value is the one entries are graded against; the column was rewritten, or the retirement was written without its closure statement. Treat the registry as tampered and compare it with the Server\'s own scan (key_window_drift). Where the detail names a distrust entry the listing says the Server applies (distrustedFrom, VAULT_DISTRUSTED_KEYS), the listed retirement may be that entry\'s cut, which the verifier was not given or was given at another instant; the listing\'s word is unsigned, so it stays tampering until the Server\'s operator confirms the entry.',
65
115
  CHECKPOINT_ROW_MISSING: 'A signed checkpoint anchors a position that has no matching chain row. The chain was truncated below a checkpoint (out-of-band DELETE/TRUNCATE). The checkpoint is proof of the missing rows.',
66
116
  CHECKPOINT_HASH_MISMATCH: 'A checkpoint\'s payloadHash does not match the chain row at its position. The chain diverged from what was checkpointed. Treat the chain as tampered.',
67
117
  CHECKPOINT_SIGNATURE_INVALID: 'A checkpoint\'s COSE_Sign1 signature did not verify. The checkpoint was forged or altered. Re-run with out-of-band verification keys.',
68
- TENANT_READ_LEAF_HASH_MISMATCH: 'An org_admin_reads leaf hash does not match sha256(cose_sign1). The read-log leaf was altered after recording.',
118
+ CHECKPOINT_UNSIGNED: 'A checkpoint carries no signing key id but was written at or after the earliest activation time in the signing key set (retired keys included), when every writer holds a registered key. The checkpoint was forged or its key id nulled, and nothing it anchors can be trusted. Escalate to the operator.',
119
+ CHECKPOINT_KEY_UNANCHORED: 'A vault checkpoint is signed by a key that no signed key statement links to a trust anchor you pinned. Nothing it anchors can be trusted; treat it as forged (see CHAIN_SIGNING_KEY_UNANCHORED).',
120
+ CHECKPOINT_CLAIM_MISMATCH: 'The claim signed inside a vault checkpoint envelope does not decode, or says something the checkpoint row\'s columns do not (chain position, chain tip hash, subject digest or signed kid). A column was rewritten beside an intact envelope. Trust the signed claim, treat the checkpoint row as tampered, and obtain the dump from the operator again.',
121
+ TENANT_READ_LEAF_HASH_MISMATCH: 'An org_admin_reads leaf_hash does not match the RFC 9162 leaf hash of its envelope, sha256(0x00 || cose_sign1). The read-log leaf was altered after recording.',
69
122
  TENANT_READ_LEAF_INDEX_GAP: 'org_admin_reads leaf indices are not gap-free for this org. A read-log entry was removed. Obtain the complete log.',
70
123
  TENANT_READ_SIGNATURE_INVALID: 'An org_admin_reads leaf\'s COSE_Sign1 signature did not verify. The read-log leaf was forged or altered.',
124
+ TENANT_READ_LEAF_UNSIGNED: 'An org_admin_reads leaf carries the unsigned kid where the install could not have written one: after a signed leaf in the same org log, or at or after the earliest activation time in the signing key set. Treat the leaf as forged and escalate to the operator.',
125
+ TENANT_READ_KEY_UNANCHORED: 'An org_admin_reads leaf is signed by a key that no signed key statement links to a trust anchor you pinned. Treat the leaf as forged (see CHAIN_SIGNING_KEY_UNANCHORED).',
126
+ TENANT_READ_CLAIM_MISMATCH: 'The claim signed inside an org_admin_reads leaf envelope does not decode, or says something the leaf row\'s columns do not (position, previous_hash, record_id or subject digest). A column was rewritten beside an intact envelope. Trust the signed claim and treat the read-log leaf as tampered.',
71
127
  TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH: 'A signed tree head commits to more leaves than the dump contains. The read log was truncated below a checkpoint.',
72
- TENANT_CHECKPOINT_ROOT_MISMATCH: 'The recomputed Merkle root does not match the signed root_hash. The read log diverged from what was checkpointed.',
128
+ TENANT_CHECKPOINT_ROOT_MISMATCH: 'The RFC 9162 Merkle root recomputed over the leaves does not match the signed root_hash. The read log diverged from what was checkpointed.',
73
129
  TENANT_CHECKPOINT_SIGNATURE_INVALID: 'A signed-tree-head COSE_Sign1 signature did not verify. The STH was forged or altered.',
130
+ TENANT_CHECKPOINT_UNSIGNED: 'An org_admin_reads signed tree head carries no signing key id but was written at or after the earliest activation time in the signing key set. The tree head was forged or its key id nulled; escalate to the operator.',
131
+ TENANT_CHECKPOINT_KEY_UNANCHORED: 'An org_admin_reads signed tree head is signed by a key that no signed key statement links to a trust anchor you pinned. Treat it as forged (see CHAIN_SIGNING_KEY_UNANCHORED).',
132
+ TENANT_CHECKPOINT_CLAIM_MISMATCH: 'The claim signed inside an org_admin_reads tree-head envelope does not decode, or says something the tree-head row\'s columns do not (position, chain_tip_hash, leaf count, subject digest or signed kid). A column was rewritten beside an intact envelope. Trust the signed claim and treat the tree-head row as tampered.',
74
133
  TENANT_CHECKPOINT_FORK: 'Two signed tree heads at the same tree_size carry different roots. This is an engine fork or signing-key compromise. Escalate immediately.',
134
+ KEY_STATEMENT_INVALID: 'A key statement does not verify, disagrees with the columns it was stored under, touches no anchored key, or was signed by a key after its closure or after the key was already admitted. It admits nothing. One that does not verify, or that a key signed after its closure, is what a writer with database access or a leaked retired key produces: have the operator retire that key with force and add it to VAULT_DISTRUSTED_KEYS, and pass the same entry as distrustedKeys.',
135
+ KEY_CLOSURE_INVALID: 'A key is retired with no closure that counts for it, or a closure is signed by a key the walk does not anchor, by a key after its own retirement, or dates a retirement before its subject was activated, or is signed by a key the walk reaches but does not anchor and retires an anchored key earlier, or with force, than any closure a published key signed (so a walk over the published key documents reads that key differently). A closure that still counts ends its subject\'s window whoever wrote it; if its signer leaked, have the operator add it to VAULT_DISTRUSTED_KEYS and pass the same entry as distrustedKeys.',
75
136
  };
76
137
  /** The actionable next step for a failure code. */
77
138
  export function suggestion(code) {
package/dist/index.d.ts CHANGED
@@ -5,9 +5,13 @@
5
5
  */
6
6
  export { suggestion } from './failures.js';
7
7
  export type { FailureCode } from './failures.js';
8
- export { buildKeyRegistry, verifyChain, } from './chain.js';
9
- export type { KeySource, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, VerifyChainOptions, } from './chain.js';
8
+ export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, verifyChain, writtenWhileSigning, } from './chain.js';
9
+ export type { AccountedEntry, AccountedEntryCode, AgentKeyRegistry, KeySource, KeyTrustState, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, VerifyChainOptions, } from './chain.js';
10
10
  export { verifyAuditExport } from './audit-export.js';
11
- export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, OutOfBandKeyEntry, EntryVerificationResult, VerifyExportResult, } from './audit-export.js';
12
- export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, merkleRoot, verifyInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
13
- export type { CoseSign1Parts, CoseVerifyOutcome, KeyAlgorithm, ChainClaim, ReceiptInclusionProof, ReceiptVerifyOutcome, } from './primitives.js';
11
+ export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, SuppliedKeyEntry, EntryVerificationResult, VerifyExportResult, } from './audit-export.js';
12
+ export { KEY_STATEMENT_CTY, KEY_STATEMENT_KINDS, applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementFromDumpRow, keyStatementsFromExport, keyStatementsFromVerificationKeys, parseDistrustedKeys, parseTrustAnchors, reportKeyTrust, settleKeyTrust, spkiSha256, verdictOf, trustKeyFromDumpRow, } from './key-statements.js';
13
+ export type { ComputeKeyTrustInput, DistrustedKey, DistrustSpan, DumpKeyStatementRow, DumpSigningKeyRow, KeyRegistryFinding, KeyRegistryFindingCode, KeyStatementInput, KeyStatementKind, KeyTrust, KeyTrustEntry, KeyTrustNote, KeyTrustReport, KeyTrustStatus, PublishedKeyStatement, TrustKeyInput, Verdict, VerificationKeysDocument, } from './key-statements.js';
14
+ export { instantMs } from './instant.js';
15
+ export { assertKnownOptions } from './options.js';
16
+ export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, extractAgentSignatureClaim, ed25519JwkThumbprint, ed25519JwkToSpki, verifyAgentSignature, AGENT_SIGNATURE_CONTEXT, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, orgReadLeafHash, orgReadMerkleRoot, verifyOrgReadInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
17
+ export type { CoseSign1Parts, CoseVerifyOutcome, KeyAlgorithm, ActorClaim, ChainClaim, AgentPublicKeyJwk, AgentSignatureClaim, AgentSignatureOutcome, ReceiptInclusionProof, ReceiptVerifyOutcome, } from './primitives.js';
package/dist/index.js CHANGED
@@ -4,6 +4,9 @@
4
4
  * the MCP server, and @agledger/verify all build on this single body of logic.
5
5
  */
6
6
  export { suggestion } from './failures.js';
7
- export { buildKeyRegistry, verifyChain, } from './chain.js';
7
+ export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, verifyChain, writtenWhileSigning, } from './chain.js';
8
8
  export { verifyAuditExport } from './audit-export.js';
9
- export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, merkleRoot, verifyInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
9
+ export { KEY_STATEMENT_CTY, KEY_STATEMENT_KINDS, applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementFromDumpRow, keyStatementsFromExport, keyStatementsFromVerificationKeys, parseDistrustedKeys, parseTrustAnchors, reportKeyTrust, settleKeyTrust, spkiSha256, verdictOf, trustKeyFromDumpRow, } from './key-statements.js';
10
+ export { instantMs } from './instant.js';
11
+ export { assertKnownOptions } from './options.js';
12
+ export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, extractAgentSignatureClaim, ed25519JwkThumbprint, ed25519JwkToSpki, verifyAgentSignature, AGENT_SIGNATURE_CONTEXT, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, orgReadLeafHash, orgReadMerkleRoot, verifyOrgReadInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
3
+ * the engine reads a microsecond instant (its `instantToDate`). Key statements
4
+ * sign microsecond instants; entry write times, dump columns and key documents
5
+ * carry milliseconds, so every comparison between them is made here. Strict:
6
+ * a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
7
+ * anything else, so no instant is ever placed by how the host's `Date.parse`
8
+ * reads a date with no offset, a space separator or an impossible day.
9
+ */
10
+ export declare function instantMs(instant: string): number;
11
+ /** {@link instantMs}, under the name the strictness is the point of. */
12
+ export declare function rfc3339Ms(instant: string): number;
13
+ /**
14
+ * Microseconds of a strict RFC 3339 instant, and whether it carries a full
15
+ * microsecond fraction. The key surfaces publish a statement's write time at
16
+ * microsecond precision and a dump at milliseconds, so two dump rows in one
17
+ * millisecond tie here without being simultaneous. NaN when the string is not
18
+ * strict RFC 3339 (see {@link rfc3339Ms}).
19
+ */
20
+ export declare function instantUs(instant: string): {
21
+ us: number;
22
+ micro: boolean;
23
+ };
@@ -0,0 +1,50 @@
1
+ /** RFC 3339 date-time: a `T`, a numeric offset or `Z`, any fraction. */
2
+ const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|([+-])(\d{2}):(\d{2}))$/;
3
+ /**
4
+ * Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
5
+ * the engine reads a microsecond instant (its `instantToDate`). Key statements
6
+ * sign microsecond instants; entry write times, dump columns and key documents
7
+ * carry milliseconds, so every comparison between them is made here. Strict:
8
+ * a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
9
+ * anything else, so no instant is ever placed by how the host's `Date.parse`
10
+ * reads a date with no offset, a space separator or an impossible day.
11
+ */
12
+ export function instantMs(instant) {
13
+ return rfc3339Ms(instant);
14
+ }
15
+ /** {@link instantMs}, under the name the strictness is the point of. */
16
+ export function rfc3339Ms(instant) {
17
+ return parse(instant)?.ms ?? Number.NaN;
18
+ }
19
+ function parse(instant) {
20
+ if (typeof instant !== 'string')
21
+ return null;
22
+ const m = RFC3339.exec(instant);
23
+ if (!m)
24
+ return null;
25
+ const [, y, mo, d, h, mi, s, frac = '', zone, sign, oh, om] = m;
26
+ if (Number(h) > 23 || Number(mi) > 59 || Number(s) > 59)
27
+ return null;
28
+ if (sign !== undefined && (Number(oh) > 23 || Number(om) > 59))
29
+ return null;
30
+ const fields = `${y}-${mo}-${d}T${h}:${mi}:${s}`;
31
+ const local = Date.parse(`${fields}Z`);
32
+ // Date.parse rolls an impossible date over (February 30 reads as March 2).
33
+ if (Number.isNaN(local) || !new Date(local).toISOString().startsWith(fields))
34
+ return null;
35
+ const offset = zone === 'Z' || zone === 'z' ? 0 : (sign === '-' ? -1 : 1) * (Number(oh) * 60 + Number(om)) * 60_000;
36
+ return { ms: local + Number(frac.slice(0, 3).padEnd(3, '0')) - offset, frac };
37
+ }
38
+ /**
39
+ * Microseconds of a strict RFC 3339 instant, and whether it carries a full
40
+ * microsecond fraction. The key surfaces publish a statement's write time at
41
+ * microsecond precision and a dump at milliseconds, so two dump rows in one
42
+ * millisecond tie here without being simultaneous. NaN when the string is not
43
+ * strict RFC 3339 (see {@link rfc3339Ms}).
44
+ */
45
+ export function instantUs(instant) {
46
+ const p = parse(instant);
47
+ if (p === null)
48
+ return { us: Number.NaN, micro: false };
49
+ return { us: p.ms * 1000 + Number(p.frac.slice(3, 6).padEnd(3, '0')), micro: p.frac.length >= 6 };
50
+ }