@kya-brasil/core 0.11.0 → 0.12.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 CHANGED
@@ -58,6 +58,36 @@ const verdict = checkDelegatedAction(r.mandates, { action: "quote", amount: 80,
58
58
  To delegate, `prepareDelegation({ credential, chain, delegate, mandate, ttlSeconds })` returns the delegation and
59
59
  the text the delegator signs with its agent key; `mandateSubsetProblems(parent, child)` says why a mandate is broader.
60
60
 
61
+ ## Status freshness proportional to the amount (offline)
62
+
63
+ Offline, a verifier only has status evidence of some age: an answer the issuer signed (the credential's status) or a
64
+ CRL (the certificate's). How old is acceptable is the verifier's call, because the verifier runs the risk (SPEC
65
+ section 18). Declare the expected loss you accept per action (`L`) and the revocation rate you assume (`λ`, per hour);
66
+ the maximum age is `L / (amount × λ)`, capped (one day by default):
67
+
68
+ ```ts
69
+ import { freshnessPolicy, checkFreshAction, evidenceFromSignedStatus, evidenceFromRevocation } from "@kya-brasil/core";
70
+
71
+ const policy = freshnessPolicy({
72
+ max_expected_loss: { amount: 1, currency: "BRL" }, // L: your tolerance, per action
73
+ revocation_rate_per_hour: { credential: lambda, certificate: mu }, // λ: what you assume; no default
74
+ require: ["credential"], // add "certificate" to also require a CRL
75
+ // max_age_seconds: 86_400, max_clock_skew_seconds: 300, or max_age: ({ amount, kind }) => seconds
76
+ });
77
+
78
+ // The agent may staple a recent signed verdict to its request: then no network is needed.
79
+ const evidence = [await evidenceFromSignedStatus(stapledVerdict, issuerPublicJwk, credential.credential_id)];
80
+ // evidence.push(evidenceFromRevocation(await checkRevocation({ crlDer, serial, issuerCertificate })));
81
+
82
+ const r = checkFreshAction(credential.mandate, { action: "buy", amount: 4200, currency: "BRL" }, { policy, evidence });
83
+ // r.allowed; r.freshness.refresh = kinds to fetch again (or ask the agent for); r.freshness.applied = policy and
84
+ // clock used, keep it with the verdict as the risk you accepted
85
+ ```
86
+
87
+ It fails closed: no evidence, another currency, an invalid amount or clock, evidence dated in the future beyond the
88
+ skew, or a CRL past its `nextUpdate`. The freshest statement wins, so a later revocation beats an earlier "active".
89
+ `checkFreshness` and `maxStatusAgeSeconds` are available on their own.
90
+
61
91
  ## Payment instruments (card networks, acquirers, issuers)
62
92
 
63
93
  A mandate can list the instruments the agent may pay with. Each one is a network and the SHA-256 of a reference
@@ -0,0 +1,119 @@
1
+ import { type ActionQuery, type ActionVerdict } from "./mandate.js";
2
+ import { type Mandate } from "./types.js";
3
+ import type { RevocationStatus } from "./revocation.js";
4
+ /** What a piece of evidence is about: the KYA credential (issuer status) or the ICP-Brasil certificate (CRL). */
5
+ export type EvidenceKind = "credential" | "certificate";
6
+ export interface StatusEvidence {
7
+ kind: EvidenceKind;
8
+ /** True when the evidence says the subject is in force: credential `active`, certificate not on the CRL. */
9
+ in_force: boolean;
10
+ /** Instant at which the status was true: the issuer's `attestation.signed_at`, or the CRL's thisUpdate. */
11
+ as_of: string;
12
+ /** Instant after which the evidence must not be used at all (a CRL's nextUpdate). */
13
+ valid_until?: string | null;
14
+ /** Free text for the verdict, e.g. "issuer verdict" or "CRL of AC X". */
15
+ source?: string;
16
+ /** Status as stated by the evidence, for the verdict ("active", "revoked", "certificateHold", ...). */
17
+ status?: string;
18
+ }
19
+ export declare const FRESHNESS_DEFAULT_MAX_AGE_SECONDS = 86400;
20
+ export declare const FRESHNESS_LIMIT_MAX_AGE_SECONDS: number;
21
+ export declare const FRESHNESS_DEFAULT_CLOCK_SKEW_SECONDS = 300;
22
+ export interface FreshnessPolicyInput {
23
+ /** L: the expected loss the verifier accepts per action, in the currency of the amounts it checks. */
24
+ max_expected_loss: {
25
+ amount: number;
26
+ currency: string;
27
+ };
28
+ /** λ: probability per hour that a subject in force stops being so, per kind of evidence. */
29
+ revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
30
+ /** Kinds of evidence an action needs. Default ["credential"]. */
31
+ require?: EvidenceKind[];
32
+ /** Ceiling on the evidence age, whatever the amount. Default 86400 (one day), at most 90 days. */
33
+ max_age_seconds?: number;
34
+ /** Tolerance for evidence dated after the verifier's clock. Default 300, at most 3600. */
35
+ max_clock_skew_seconds?: number;
36
+ /**
37
+ * Replaces the default formula. Receives the amount (undefined when the action has none) and the kind;
38
+ * returns seconds. The result is clamped to [0, max_age_seconds]; anything not finite counts as 0.
39
+ */
40
+ max_age?: (p: {
41
+ amount: number | undefined;
42
+ currency: string;
43
+ kind: EvidenceKind;
44
+ }) => number;
45
+ }
46
+ export interface FreshnessPolicy {
47
+ max_expected_loss: {
48
+ amount: number;
49
+ currency: string;
50
+ };
51
+ revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
52
+ require: EvidenceKind[];
53
+ max_age_seconds: number;
54
+ max_clock_skew_seconds: number;
55
+ max_age?: FreshnessPolicyInput["max_age"];
56
+ }
57
+ /** Validates and normalizes a policy. Throws INVALID_INPUT on anything that would make it fail open. */
58
+ export declare function freshnessPolicy(input: FreshnessPolicyInput): FreshnessPolicy;
59
+ /** Maximum evidence age, in whole seconds, for an action of `amount` (in the policy's currency). */
60
+ export declare function maxStatusAgeSeconds(policy: FreshnessPolicy, kind: EvidenceKind, amount?: number): number;
61
+ export interface FreshnessCheck {
62
+ rule: "freshness";
63
+ kind: EvidenceKind;
64
+ ok: boolean;
65
+ detail: string;
66
+ age_seconds: number | null;
67
+ max_age_seconds: number;
68
+ }
69
+ export interface FreshnessVerdict {
70
+ ok: boolean;
71
+ checks: FreshnessCheck[];
72
+ /** Kinds for which fresher (or any) evidence would change the answer: fetch it, or ask the agent for it. */
73
+ refresh: EvidenceKind[];
74
+ /** The policy and clock actually applied, to keep with the verdict as proof of the risk accepted. */
75
+ applied: {
76
+ now: string;
77
+ amount: number | null;
78
+ currency: string;
79
+ max_expected_loss: {
80
+ amount: number;
81
+ currency: string;
82
+ };
83
+ revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
84
+ max_age_seconds: number;
85
+ max_clock_skew_seconds: number;
86
+ custom_max_age: boolean;
87
+ };
88
+ }
89
+ /**
90
+ * Checks that, for every kind the policy requires, the freshest evidence given says "in force", is not
91
+ * past its own validity, is not dated in the future beyond the clock skew, and is younger than the maximum
92
+ * age for this amount. Fails closed: missing, malformed or foreign-currency input never passes.
93
+ */
94
+ export declare function checkFreshness(policy: FreshnessPolicy, evidence: StatusEvidence[], q?: {
95
+ amount?: number;
96
+ currency?: string;
97
+ now?: Date;
98
+ }): FreshnessVerdict;
99
+ /**
100
+ * The mandate (checkAction) and the freshness of the status, in one answer: allowed only when both pass.
101
+ * The freshness check uses the action's amount and currency and the same clock.
102
+ */
103
+ export declare function checkFreshAction(mandate: Mandate, q: ActionQuery, p: {
104
+ policy: FreshnessPolicy;
105
+ evidence: StatusEvidence[];
106
+ }): {
107
+ allowed: boolean;
108
+ mandate: ActionVerdict;
109
+ freshness: FreshnessVerdict;
110
+ };
111
+ /** Evidence about the certificate from a CRL lookup (checkRevocation / verifyCrl().lookup). */
112
+ export declare function evidenceFromRevocation(r: RevocationStatus, source?: string): StatusEvidence;
113
+ /**
114
+ * Evidence about the credential from an answer the issuer signed (a verdict from /allowed, a paid
115
+ * verification receipt): any answer carrying `credential_id`, `status` and an Ed25519 `attestation`. The
116
+ * agent can staple such an answer to its request so the verifier needs no network. The answer must be
117
+ * about `credentialId` and verify with the issuer's key; the status instant is the signature's.
118
+ */
119
+ export declare function evidenceFromSignedStatus(answer: Record<string, unknown>, issuerPublicJwk: JsonWebKey, credentialId: string): Promise<StatusEvidence>;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Status freshness proportional to what is at stake (D-32, SPEC section 18).
3
+ *
4
+ * A verifier working offline holds evidence of status that is some time old: an issuer answer signed at a
5
+ * given instant (the credential's status), or a CRL issued at a given instant (the e-CNPJ / e-CPF
6
+ * certificate's status). Following Rivest (1998), the recency requirement is set by whoever accepts the
7
+ * action and runs the risk, not by the issuer: this module turns the verifier's loss tolerance into a
8
+ * maximum evidence age that shrinks as the amount grows, and refuses older evidence.
9
+ *
10
+ * Expected loss of accepting an action of value v on evidence of age t, when status changes at a rate of
11
+ * λ per hour: v × λ × t. Keeping it under the tolerance L gives the default maximum age
12
+ *
13
+ * max_age(v) = L / (v × λ) hours, capped by max_age_seconds.
14
+ *
15
+ * Pure functions, no network: the caller obtains the evidence (cache, CRL download, an issuer answer the
16
+ * agent staples to its request) and passes the clock it trusts.
17
+ */
18
+ import { verifyAttestation } from "./attestation.js";
19
+ import { checkAction } from "./mandate.js";
20
+ import { KyaError } from "./types.js";
21
+ export const FRESHNESS_DEFAULT_MAX_AGE_SECONDS = 86_400;
22
+ export const FRESHNESS_LIMIT_MAX_AGE_SECONDS = 90 * 86_400;
23
+ export const FRESHNESS_DEFAULT_CLOCK_SKEW_SECONDS = 300;
24
+ const KINDS = ["credential", "certificate"];
25
+ const CURRENCY = /^[A-Z0-9]{2,10}$/;
26
+ function bad(message) {
27
+ throw new KyaError("INVALID_INPUT", `freshness policy: ${message}`);
28
+ }
29
+ /** Validates and normalizes a policy. Throws INVALID_INPUT on anything that would make it fail open. */
30
+ export function freshnessPolicy(input) {
31
+ if (!input || typeof input !== "object")
32
+ bad("expected an object");
33
+ const loss = input.max_expected_loss;
34
+ if (!loss || typeof loss.amount !== "number" || !Number.isFinite(loss.amount) || loss.amount < 0)
35
+ bad("max_expected_loss.amount must be a finite number >= 0");
36
+ const currency = typeof loss.currency === "string" ? loss.currency.trim().toUpperCase() : "";
37
+ if (!CURRENCY.test(currency))
38
+ bad("max_expected_loss.currency must match ^[A-Z0-9]{2,10}$");
39
+ const require = input.require ?? ["credential"];
40
+ if (!Array.isArray(require) || !require.length || require.some((k) => !KINDS.includes(k)))
41
+ bad(`require must list one or more of ${KINDS.join(", ")}`);
42
+ const rates = {};
43
+ for (const [k, v] of Object.entries(input.revocation_rate_per_hour ?? {})) {
44
+ if (!KINDS.includes(k))
45
+ bad(`unknown evidence kind "${k}" in revocation_rate_per_hour`);
46
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
47
+ bad(`revocation_rate_per_hour.${k} must be a finite number >= 0`);
48
+ rates[k] = v;
49
+ }
50
+ if (!input.max_age)
51
+ for (const k of require)
52
+ if (rates[k] === undefined)
53
+ bad(`revocation_rate_per_hour.${k} is required (or give max_age)`);
54
+ const ceiling = input.max_age_seconds ?? FRESHNESS_DEFAULT_MAX_AGE_SECONDS;
55
+ if (!Number.isInteger(ceiling) || ceiling < 0 || ceiling > FRESHNESS_LIMIT_MAX_AGE_SECONDS)
56
+ bad(`max_age_seconds must be an integer in 0..${FRESHNESS_LIMIT_MAX_AGE_SECONDS}`);
57
+ const skew = input.max_clock_skew_seconds ?? FRESHNESS_DEFAULT_CLOCK_SKEW_SECONDS;
58
+ if (!Number.isInteger(skew) || skew < 0 || skew > 3600)
59
+ bad("max_clock_skew_seconds must be an integer in 0..3600");
60
+ if (input.max_age !== undefined && typeof input.max_age !== "function")
61
+ bad("max_age must be a function");
62
+ return { max_expected_loss: { amount: loss.amount, currency }, revocation_rate_per_hour: rates, require: [...new Set(require)], max_age_seconds: ceiling, max_clock_skew_seconds: skew, max_age: input.max_age };
63
+ }
64
+ /** Maximum evidence age, in whole seconds, for an action of `amount` (in the policy's currency). */
65
+ export function maxStatusAgeSeconds(policy, kind, amount) {
66
+ const ceiling = policy.max_age_seconds;
67
+ let seconds;
68
+ if (policy.max_age) {
69
+ seconds = policy.max_age({ amount, currency: policy.max_expected_loss.currency, kind });
70
+ }
71
+ else {
72
+ const rate = policy.revocation_rate_per_hour[kind] ?? 0;
73
+ if (amount === undefined || amount <= 0 || rate === 0)
74
+ return ceiling;
75
+ seconds = (policy.max_expected_loss.amount / (amount * rate)) * 3600;
76
+ }
77
+ if (!Number.isFinite(seconds) || seconds < 0)
78
+ return seconds === Infinity ? ceiling : 0;
79
+ // The epsilon keeps binary rounding (1 / (10000 × 1e-4) × 3600 = 3599.999…) from costing a whole second.
80
+ return Math.min(ceiling, Math.floor(seconds + 1e-6));
81
+ }
82
+ function human(seconds) {
83
+ if (seconds < 120)
84
+ return `${seconds} s`;
85
+ if (seconds < 7200)
86
+ return `${Math.floor(seconds / 60)} min`;
87
+ if (seconds < 172_800)
88
+ return `${Math.floor(seconds / 3600)} h`;
89
+ return `${Math.floor(seconds / 86_400)} d`;
90
+ }
91
+ /**
92
+ * Checks that, for every kind the policy requires, the freshest evidence given says "in force", is not
93
+ * past its own validity, is not dated in the future beyond the clock skew, and is younger than the maximum
94
+ * age for this amount. Fails closed: missing, malformed or foreign-currency input never passes.
95
+ */
96
+ export function checkFreshness(policy, evidence, q = {}) {
97
+ const now = q.now ?? new Date();
98
+ const nowMs = now.getTime();
99
+ const currency = policy.max_expected_loss.currency;
100
+ const qCurrency = q.currency?.trim().toUpperCase();
101
+ const amount = q.amount;
102
+ const applied = {
103
+ now: Number.isNaN(nowMs) ? "invalid" : now.toISOString(),
104
+ amount: amount ?? null,
105
+ currency,
106
+ max_expected_loss: policy.max_expected_loss,
107
+ revocation_rate_per_hour: policy.revocation_rate_per_hour,
108
+ max_age_seconds: policy.max_age_seconds,
109
+ max_clock_skew_seconds: policy.max_clock_skew_seconds,
110
+ custom_max_age: !!policy.max_age
111
+ };
112
+ const checks = [];
113
+ const refresh = [];
114
+ if (Number.isNaN(nowMs)) {
115
+ for (const kind of policy.require)
116
+ checks.push({ rule: "freshness", kind, ok: false, detail: "the verifier's clock is not a valid date", age_seconds: null, max_age_seconds: 0 });
117
+ return { ok: false, checks, refresh, applied };
118
+ }
119
+ const amountOk = amount === undefined || (typeof amount === "number" && Number.isFinite(amount) && amount >= 0);
120
+ if (!amountOk || (qCurrency && qCurrency !== currency)) {
121
+ const detail = !amountOk ? "amount is not a finite number >= 0" : `loss tolerance is in ${currency}, operation in ${qCurrency}`;
122
+ for (const kind of policy.require)
123
+ checks.push({ rule: "freshness", kind, ok: false, detail, age_seconds: null, max_age_seconds: 0 });
124
+ return { ok: false, checks, refresh, applied };
125
+ }
126
+ for (const kind of policy.require) {
127
+ const max = maxStatusAgeSeconds(policy, kind, amount);
128
+ const limit = `${amount === undefined ? "no amount given, ceiling applies" : `for ${amount} ${currency}`}: at most ${human(max)}`;
129
+ const usable = evidence.filter((e) => e && e.kind === kind && !Number.isNaN(Date.parse(e.as_of)));
130
+ if (!usable.length) {
131
+ checks.push({ rule: "freshness", kind, ok: false, detail: `no ${kind} status evidence; ${limit}`, age_seconds: null, max_age_seconds: max });
132
+ refresh.push(kind);
133
+ continue;
134
+ }
135
+ // Freshest first: a newer statement supersedes an older one, whatever it says.
136
+ let e = usable[0];
137
+ let asOf = Date.parse(e.as_of);
138
+ for (const candidate of usable) {
139
+ const t = Date.parse(candidate.as_of);
140
+ if (t > asOf) {
141
+ e = candidate;
142
+ asOf = t;
143
+ }
144
+ }
145
+ const age = Math.floor((nowMs - asOf) / 1000);
146
+ const from = e.source ? ` (${e.source})` : "";
147
+ if (asOf - nowMs > policy.max_clock_skew_seconds * 1000) {
148
+ checks.push({ rule: "freshness", kind, ok: false, detail: `${kind} evidence${from} is dated ${e.as_of}, after the verifier's clock ${applied.now} beyond the ${policy.max_clock_skew_seconds} s tolerance`, age_seconds: age, max_age_seconds: max });
149
+ continue;
150
+ }
151
+ if (e.valid_until && !Number.isNaN(Date.parse(e.valid_until)) && Date.parse(e.valid_until) < nowMs) {
152
+ checks.push({ rule: "freshness", kind, ok: false, detail: `${kind} evidence${from} expired at ${e.valid_until}`, age_seconds: Math.max(0, age), max_age_seconds: max });
153
+ refresh.push(kind);
154
+ continue;
155
+ }
156
+ if (!e.in_force) {
157
+ checks.push({ rule: "freshness", kind, ok: false, detail: `${kind} is not in force${e.status ? ` (${e.status})` : ""} as of ${e.as_of}${from}`, age_seconds: Math.max(0, age), max_age_seconds: max });
158
+ continue;
159
+ }
160
+ const ageShown = Math.max(0, age);
161
+ const fresh = ageShown <= max;
162
+ checks.push({ rule: "freshness", kind, ok: fresh, detail: `${kind} status${from} is ${human(ageShown)} old; ${limit}`, age_seconds: ageShown, max_age_seconds: max });
163
+ if (!fresh)
164
+ refresh.push(kind);
165
+ }
166
+ return { ok: checks.length > 0 && checks.every((c) => c.ok), checks, refresh, applied };
167
+ }
168
+ /**
169
+ * The mandate (checkAction) and the freshness of the status, in one answer: allowed only when both pass.
170
+ * The freshness check uses the action's amount and currency and the same clock.
171
+ */
172
+ export function checkFreshAction(mandate, q, p) {
173
+ const now = q.now ?? new Date();
174
+ const m = checkAction(mandate, { ...q, now });
175
+ const f = checkFreshness(p.policy, p.evidence, { amount: q.amount, currency: q.currency, now });
176
+ return { allowed: m.allowed && f.ok, mandate: m, freshness: f };
177
+ }
178
+ /** Evidence about the certificate from a CRL lookup (checkRevocation / verifyCrl().lookup). */
179
+ export function evidenceFromRevocation(r, source) {
180
+ return {
181
+ kind: "certificate",
182
+ in_force: !r.revoked,
183
+ as_of: r.crl_this_update,
184
+ valid_until: r.crl_next_update,
185
+ source: source ?? "CRL",
186
+ status: r.revoked ? (r.reason ?? "revoked") : "not revoked"
187
+ };
188
+ }
189
+ /**
190
+ * Evidence about the credential from an answer the issuer signed (a verdict from /allowed, a paid
191
+ * verification receipt): any answer carrying `credential_id`, `status` and an Ed25519 `attestation`. The
192
+ * agent can staple such an answer to its request so the verifier needs no network. The answer must be
193
+ * about `credentialId` and verify with the issuer's key; the status instant is the signature's.
194
+ */
195
+ export async function evidenceFromSignedStatus(answer, issuerPublicJwk, credentialId) {
196
+ if (!answer || typeof answer !== "object")
197
+ throw new KyaError("INVALID_INPUT", "signed status: expected an object");
198
+ if (answer.credential_id !== credentialId)
199
+ throw new KyaError("INVALID_INPUT", `signed status is about ${String(answer.credential_id)}, not ${credentialId}`);
200
+ if (typeof answer.status !== "string")
201
+ throw new KyaError("INVALID_INPUT", "signed status has no status");
202
+ const sig = await verifyAttestation(answer, issuerPublicJwk);
203
+ if (!sig.valid || !sig.signed_at)
204
+ throw new KyaError("INVALID_INPUT", `signed status does not verify: ${sig.reason ?? "no signature time"}`);
205
+ return { kind: "credential", in_force: answer.status === "active", as_of: sig.signed_at, source: "issuer signed status", status: answer.status };
206
+ }
package/dist/index.d.ts CHANGED
@@ -11,3 +11,4 @@ export * from "./ecnpj-sign.js";
11
11
  export * from "./cloud-sign.js";
12
12
  export * from "./person.js";
13
13
  export * from "./delegation.js";
14
+ export * from "./freshness.js";
package/dist/index.js CHANGED
@@ -11,3 +11,4 @@ export * from "./ecnpj-sign.js";
11
11
  export * from "./cloud-sign.js";
12
12
  export * from "./person.js";
13
13
  export * from "./delegation.js";
14
+ export * from "./freshness.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-brasil/core",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "KYA Brasil as a library: verify and issue know-your-agent credentials for Brazilian companies without any hosted service. e-CNPJ (ICP-Brasil) CMS signature and chain validation, CRL revocation, CNPJ, agent key challenges (EVM, Ed25519 / Web Bot Auth, ERC-8004), mandate schema and evaluation (including payment instruments for card networks and acquirers), credential build, Ed25519 signing and verification, and e-CNPJ signing for the holder (A1 .pfx, or any token/HSM/cloud signer through a raw-sign callback). Pure functions: storage and network are yours.",
5
5
  "license": "MIT",
6
6
  "type": "module",