@kya-brasil/core 0.11.0 → 0.13.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 +41 -0
- package/dist/freshness.d.ts +150 -0
- package/dist/freshness.js +268 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/revocation.d.ts +7 -1
- package/dist/revocation.js +8 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -58,6 +58,47 @@ 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 by your ceiling. The library holds no business values: every
|
|
67
|
+
parameter below is required, and so is the clock.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { freshnessPolicy, checkFreshAction, evidenceFromSignedStatus, evidenceFromRevocation } from "@kya-brasil/core";
|
|
71
|
+
|
|
72
|
+
const policy = freshnessPolicy({
|
|
73
|
+
max_expected_loss: { amount: 1, currency: "BRL" }, // L: your tolerance, per action
|
|
74
|
+
revocation_rate_per_hour: { credential: lambda, certificate: mu }, // λ: what you assume
|
|
75
|
+
require: ["credential"], // add "certificate" to also require a CRL
|
|
76
|
+
max_age_seconds: ceiling, // your ceiling, whatever the value
|
|
77
|
+
max_clock_skew_seconds: skew, // tolerance for evidence dated in the future
|
|
78
|
+
unvalued_action: "refuse", // or "ceiling": actions of unknown value
|
|
79
|
+
past_valid_until: "refuse", // or "accept": a CRL past nextUpdate, judged by age
|
|
80
|
+
// action_risk_value: { sign_contract: 100_000 }, max_age: ({ amount, kind, action }) => seconds
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// The agent may staple a recent signed verdict to its request: then no network is needed.
|
|
84
|
+
const evidence = [await evidenceFromSignedStatus(stapledVerdict, issuerPublicJwk, credential.credential_id)];
|
|
85
|
+
// evidence.push(evidenceFromRevocation(await checkRevocation({ crlDer, serial, issuerCertificate, pastNextUpdate: "accept" })));
|
|
86
|
+
|
|
87
|
+
const r = checkFreshAction(credential.mandate, { action: "buy", amount: 4200, currency: "BRL", now: trustedClock() }, { policy, evidence });
|
|
88
|
+
// r.allowed; r.freshness.refresh = kinds to fetch again (or ask the agent for); r.freshness.applied = policy and
|
|
89
|
+
// clock used, keep it with the verdict as the risk you accepted
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Actions without an amount (signing, reading data, calling an API) take the risk value you assign them:
|
|
93
|
+
`action_risk_value: { sign_contract: 100_000, read_data: 50 }` in the policy's currency; an action with neither an
|
|
94
|
+
amount nor a risk value is refused or gets the ceiling, as `unvalued_action` says. A custom `max_age` also receives the action.
|
|
95
|
+
The daily ceiling (`max_per_day` with your own `spent_today`) is what bounds a stolen key inside the window; the
|
|
96
|
+
counting, and any stricter ceiling of your own, are yours.
|
|
97
|
+
|
|
98
|
+
It fails closed: no evidence, another currency, an invalid amount, a missing or invalid clock, evidence dated in the
|
|
99
|
+
future beyond your skew, or a CRL past its `nextUpdate` when `past_valid_until` is `"refuse"`. The freshest statement wins, so a later revocation beats an earlier "active".
|
|
100
|
+
`checkFreshness` and `maxStatusAgeSeconds` are available on their own.
|
|
101
|
+
|
|
61
102
|
## Payment instruments (card networks, acquirers, issuers)
|
|
62
103
|
|
|
63
104
|
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,150 @@
|
|
|
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 interface FreshnessPolicyInput {
|
|
20
|
+
/** L: the expected loss the verifier accepts per action, in the currency of the amounts it checks. */
|
|
21
|
+
max_expected_loss: {
|
|
22
|
+
amount: number;
|
|
23
|
+
currency: string;
|
|
24
|
+
};
|
|
25
|
+
/** λ: probability per hour that a subject in force stops being so, per kind of evidence. */
|
|
26
|
+
revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
|
|
27
|
+
/** Kinds of evidence an action needs: one or more of "credential", "certificate". */
|
|
28
|
+
require: EvidenceKind[];
|
|
29
|
+
/** Ceiling on the evidence age, in seconds, whatever the value at risk. */
|
|
30
|
+
max_age_seconds: number;
|
|
31
|
+
/** Tolerance, in seconds, for evidence dated after the verifier's clock. */
|
|
32
|
+
max_clock_skew_seconds: number;
|
|
33
|
+
/**
|
|
34
|
+
* What to do with an action that has neither an amount nor a risk value in `action_risk_value`:
|
|
35
|
+
* "refuse" fails the check; "ceiling" accepts evidence up to `max_age_seconds`.
|
|
36
|
+
*/
|
|
37
|
+
unvalued_action: "refuse" | "ceiling";
|
|
38
|
+
/**
|
|
39
|
+
* What to do with evidence past its own `valid_until` (a CRL past nextUpdate): "refuse" fails the check;
|
|
40
|
+
* "accept" lets its age alone decide, as Li and Feigenbaum (FC 2001) propose.
|
|
41
|
+
*/
|
|
42
|
+
past_valid_until: "refuse" | "accept";
|
|
43
|
+
/**
|
|
44
|
+
* Value at risk, in the policy's currency, of actions that carry no amount (`sign`, `read`, `call`...),
|
|
45
|
+
* keyed by action name. Used only when the action has no amount; see `unvalued_action` for the rest.
|
|
46
|
+
*/
|
|
47
|
+
action_risk_value?: Record<string, number>;
|
|
48
|
+
/**
|
|
49
|
+
* Replaces the default formula. Receives the value at risk (the amount, or the action's risk value; undefined
|
|
50
|
+
* when there is neither), the action and the kind; returns seconds. The result is clamped to
|
|
51
|
+
* [0, max_age_seconds]; anything not finite counts as 0.
|
|
52
|
+
*/
|
|
53
|
+
max_age?: (p: {
|
|
54
|
+
amount: number | undefined;
|
|
55
|
+
currency: string;
|
|
56
|
+
kind: EvidenceKind;
|
|
57
|
+
action?: string;
|
|
58
|
+
}) => number;
|
|
59
|
+
}
|
|
60
|
+
export interface FreshnessPolicy {
|
|
61
|
+
max_expected_loss: {
|
|
62
|
+
amount: number;
|
|
63
|
+
currency: string;
|
|
64
|
+
};
|
|
65
|
+
revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
|
|
66
|
+
require: EvidenceKind[];
|
|
67
|
+
max_age_seconds: number;
|
|
68
|
+
max_clock_skew_seconds: number;
|
|
69
|
+
unvalued_action: "refuse" | "ceiling";
|
|
70
|
+
past_valid_until: "refuse" | "accept";
|
|
71
|
+
action_risk_value: Record<string, number>;
|
|
72
|
+
max_age?: FreshnessPolicyInput["max_age"];
|
|
73
|
+
}
|
|
74
|
+
/** Validates and normalizes a policy. Throws INVALID_INPUT on anything that would make it fail open. */
|
|
75
|
+
export declare function freshnessPolicy(input: FreshnessPolicyInput): FreshnessPolicy;
|
|
76
|
+
/** The value at risk of an action: its amount, or else the risk value the policy gives its name. */
|
|
77
|
+
export declare function valueAtRisk(policy: FreshnessPolicy, amount?: number, action?: string): number | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* Maximum evidence age, in whole seconds, for an action of `amount` (in the policy's currency) or, with no
|
|
80
|
+
* amount, of the risk value the policy assigns to `action`.
|
|
81
|
+
*/
|
|
82
|
+
export declare function maxStatusAgeSeconds(policy: FreshnessPolicy, kind: EvidenceKind, amount?: number, action?: string): number;
|
|
83
|
+
export interface FreshnessCheck {
|
|
84
|
+
rule: "freshness";
|
|
85
|
+
kind: EvidenceKind;
|
|
86
|
+
ok: boolean;
|
|
87
|
+
detail: string;
|
|
88
|
+
age_seconds: number | null;
|
|
89
|
+
max_age_seconds: number;
|
|
90
|
+
}
|
|
91
|
+
export interface FreshnessVerdict {
|
|
92
|
+
ok: boolean;
|
|
93
|
+
checks: FreshnessCheck[];
|
|
94
|
+
/** Kinds for which fresher (or any) evidence would change the answer: fetch it, or ask the agent for it. */
|
|
95
|
+
refresh: EvidenceKind[];
|
|
96
|
+
/** The policy and clock actually applied, to keep with the verdict as proof of the risk accepted. */
|
|
97
|
+
applied: {
|
|
98
|
+
now: string;
|
|
99
|
+
action: string | null;
|
|
100
|
+
amount: number | null;
|
|
101
|
+
/** The amount, or the risk value assigned to the action; null when there was neither (ceiling applied). */
|
|
102
|
+
value_at_risk: number | null;
|
|
103
|
+
currency: string;
|
|
104
|
+
max_expected_loss: {
|
|
105
|
+
amount: number;
|
|
106
|
+
currency: string;
|
|
107
|
+
};
|
|
108
|
+
revocation_rate_per_hour: Partial<Record<EvidenceKind, number>>;
|
|
109
|
+
max_age_seconds: number;
|
|
110
|
+
max_clock_skew_seconds: number;
|
|
111
|
+
unvalued_action: "refuse" | "ceiling";
|
|
112
|
+
past_valid_until: "refuse" | "accept";
|
|
113
|
+
custom_max_age: boolean;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Checks that, for every kind the policy requires, the freshest evidence given says "in force", is not
|
|
118
|
+
* past its own validity (unless the policy accepts that), is not dated in the future beyond the clock skew,
|
|
119
|
+
* and is younger than the maximum age for this value. Fails closed: missing, malformed or foreign-currency
|
|
120
|
+
* input never passes.
|
|
121
|
+
*/
|
|
122
|
+
export declare function checkFreshness(policy: FreshnessPolicy, evidence: StatusEvidence[], q: {
|
|
123
|
+
action?: string;
|
|
124
|
+
amount?: number;
|
|
125
|
+
currency?: string;
|
|
126
|
+
now: Date;
|
|
127
|
+
}): FreshnessVerdict;
|
|
128
|
+
/**
|
|
129
|
+
* The mandate (checkAction) and the freshness of the status, in one answer: allowed only when both pass.
|
|
130
|
+
* The freshness check uses the action's name, amount and currency and the same clock.
|
|
131
|
+
*/
|
|
132
|
+
export declare function checkFreshAction(mandate: Mandate, q: ActionQuery & {
|
|
133
|
+
now: Date;
|
|
134
|
+
}, p: {
|
|
135
|
+
policy: FreshnessPolicy;
|
|
136
|
+
evidence: StatusEvidence[];
|
|
137
|
+
}): {
|
|
138
|
+
allowed: boolean;
|
|
139
|
+
mandate: ActionVerdict;
|
|
140
|
+
freshness: FreshnessVerdict;
|
|
141
|
+
};
|
|
142
|
+
/** Evidence about the certificate from a CRL lookup (checkRevocation / verifyCrl().lookup). */
|
|
143
|
+
export declare function evidenceFromRevocation(r: RevocationStatus, source?: string): StatusEvidence;
|
|
144
|
+
/**
|
|
145
|
+
* Evidence about the credential from an answer the issuer signed (a verdict from /allowed, a paid
|
|
146
|
+
* verification receipt): any answer carrying `credential_id`, `status` and an Ed25519 `attestation`. The
|
|
147
|
+
* agent can staple such an answer to its request so the verifier needs no network. The answer must be
|
|
148
|
+
* about `credentialId` and verify with the issuer's key; the status instant is the signature's.
|
|
149
|
+
*/
|
|
150
|
+
export declare function evidenceFromSignedStatus(answer: Record<string, unknown>, issuerPublicJwk: JsonWebKey, credentialId: string): Promise<StatusEvidence>;
|
|
@@ -0,0 +1,268 @@
|
|
|
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
|
+
* Any action, not only payments: for an action with no amount (sign a document, read data, call an API) the
|
|
16
|
+
* verifier assigns a risk value per action (`action_risk_value`), or decides the age itself (`max_age`).
|
|
17
|
+
*
|
|
18
|
+
* Pure functions, no network, no business defaults: every value that expresses a risk decision (loss
|
|
19
|
+
* tolerance, rates, ceiling, clock skew, kinds required, what to do with an action of unknown value, the clock
|
|
20
|
+
* itself) is the caller's and must be passed. The module only validates that the values are well formed.
|
|
21
|
+
*/
|
|
22
|
+
import { verifyAttestation } from "./attestation.js";
|
|
23
|
+
import { checkAction } from "./mandate.js";
|
|
24
|
+
import { KyaError } from "./types.js";
|
|
25
|
+
const KINDS = ["credential", "certificate"];
|
|
26
|
+
const CURRENCY = /^[A-Z0-9]{2,10}$/;
|
|
27
|
+
const ACTION = /^[a-z][a-z0-9_-]{1,31}$/;
|
|
28
|
+
function bad(message) {
|
|
29
|
+
throw new KyaError("INVALID_INPUT", `freshness policy: ${message}`);
|
|
30
|
+
}
|
|
31
|
+
/** Validates and normalizes a policy. Throws INVALID_INPUT on anything that would make it fail open. */
|
|
32
|
+
export function freshnessPolicy(input) {
|
|
33
|
+
if (!input || typeof input !== "object")
|
|
34
|
+
bad("expected an object");
|
|
35
|
+
const loss = input.max_expected_loss;
|
|
36
|
+
if (!loss || typeof loss.amount !== "number" || !Number.isFinite(loss.amount) || loss.amount < 0)
|
|
37
|
+
bad("max_expected_loss.amount must be a finite number >= 0");
|
|
38
|
+
const currency = typeof loss.currency === "string" ? loss.currency.trim().toUpperCase() : "";
|
|
39
|
+
if (!CURRENCY.test(currency))
|
|
40
|
+
bad("max_expected_loss.currency must match ^[A-Z0-9]{2,10}$");
|
|
41
|
+
const require = input.require;
|
|
42
|
+
if (!Array.isArray(require) || !require.length || require.some((k) => !KINDS.includes(k)))
|
|
43
|
+
bad(`require must list one or more of ${KINDS.join(", ")}`);
|
|
44
|
+
const rates = {};
|
|
45
|
+
for (const [k, v] of Object.entries(input.revocation_rate_per_hour ?? {})) {
|
|
46
|
+
if (!KINDS.includes(k))
|
|
47
|
+
bad(`unknown evidence kind "${k}" in revocation_rate_per_hour`);
|
|
48
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
|
|
49
|
+
bad(`revocation_rate_per_hour.${k} must be a finite number >= 0`);
|
|
50
|
+
rates[k] = v;
|
|
51
|
+
}
|
|
52
|
+
if (!input.max_age)
|
|
53
|
+
for (const k of require)
|
|
54
|
+
if (rates[k] === undefined)
|
|
55
|
+
bad(`revocation_rate_per_hour.${k} is required (or give max_age)`);
|
|
56
|
+
const ceiling = input.max_age_seconds;
|
|
57
|
+
if (!Number.isSafeInteger(ceiling) || ceiling < 0)
|
|
58
|
+
bad("max_age_seconds is required: an integer >= 0");
|
|
59
|
+
const skew = input.max_clock_skew_seconds;
|
|
60
|
+
if (!Number.isSafeInteger(skew) || skew < 0)
|
|
61
|
+
bad("max_clock_skew_seconds is required: an integer >= 0");
|
|
62
|
+
const unvalued = input.unvalued_action;
|
|
63
|
+
if (unvalued !== "refuse" && unvalued !== "ceiling")
|
|
64
|
+
bad('unvalued_action is required: "refuse" or "ceiling"');
|
|
65
|
+
const pastValid = input.past_valid_until;
|
|
66
|
+
if (pastValid !== "refuse" && pastValid !== "accept")
|
|
67
|
+
bad('past_valid_until is required: "refuse" or "accept"');
|
|
68
|
+
if (input.max_age !== undefined && typeof input.max_age !== "function")
|
|
69
|
+
bad("max_age must be a function");
|
|
70
|
+
const values = {};
|
|
71
|
+
if (input.action_risk_value !== undefined) {
|
|
72
|
+
if (!input.action_risk_value || typeof input.action_risk_value !== "object" || Array.isArray(input.action_risk_value))
|
|
73
|
+
bad("action_risk_value must be an object of action -> value");
|
|
74
|
+
for (const [a, v] of Object.entries(input.action_risk_value)) {
|
|
75
|
+
if (!ACTION.test(a))
|
|
76
|
+
bad(`action_risk_value: "${a}" is not a mandate action name (^[a-z][a-z0-9_-]{1,31}$)`);
|
|
77
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
|
|
78
|
+
bad(`action_risk_value.${a} must be a finite number >= 0`);
|
|
79
|
+
values[a] = v;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
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, unvalued_action: unvalued, past_valid_until: pastValid, action_risk_value: values, max_age: input.max_age };
|
|
83
|
+
}
|
|
84
|
+
/** The value at risk of an action: its amount, or else the risk value the policy gives its name. */
|
|
85
|
+
export function valueAtRisk(policy, amount, action) {
|
|
86
|
+
if (amount !== undefined)
|
|
87
|
+
return amount;
|
|
88
|
+
const a = action?.trim().toLowerCase();
|
|
89
|
+
return a && Object.hasOwn(policy.action_risk_value, a) ? policy.action_risk_value[a] : undefined;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Maximum evidence age, in whole seconds, for an action of `amount` (in the policy's currency) or, with no
|
|
93
|
+
* amount, of the risk value the policy assigns to `action`.
|
|
94
|
+
*/
|
|
95
|
+
export function maxStatusAgeSeconds(policy, kind, amount, action) {
|
|
96
|
+
const ceiling = policy.max_age_seconds;
|
|
97
|
+
const value = valueAtRisk(policy, amount, action);
|
|
98
|
+
let seconds;
|
|
99
|
+
if (policy.max_age) {
|
|
100
|
+
seconds = policy.max_age({ amount: value, currency: policy.max_expected_loss.currency, kind, action: action?.trim().toLowerCase() || undefined });
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
const rate = policy.revocation_rate_per_hour[kind] ?? 0;
|
|
104
|
+
if (value === undefined || value <= 0 || rate === 0)
|
|
105
|
+
return ceiling;
|
|
106
|
+
seconds = (policy.max_expected_loss.amount / (value * rate)) * 3600;
|
|
107
|
+
}
|
|
108
|
+
if (!Number.isFinite(seconds) || seconds < 0)
|
|
109
|
+
return seconds === Infinity ? ceiling : 0;
|
|
110
|
+
// The epsilon keeps binary rounding (1 / (10000 × 1e-4) × 3600 = 3599.999…) from costing a whole second.
|
|
111
|
+
return Math.min(ceiling, Math.floor(seconds + 1e-6));
|
|
112
|
+
}
|
|
113
|
+
function human(seconds) {
|
|
114
|
+
if (seconds < 120)
|
|
115
|
+
return `${seconds} s`;
|
|
116
|
+
if (seconds < 7200)
|
|
117
|
+
return `${Math.floor(seconds / 60)} min`;
|
|
118
|
+
if (seconds < 172_800)
|
|
119
|
+
return `${Math.floor(seconds / 3600)} h`;
|
|
120
|
+
return `${Math.floor(seconds / 86_400)} d`;
|
|
121
|
+
}
|
|
122
|
+
function failAll(policy, detail) {
|
|
123
|
+
return policy.require.map((kind) => ({ rule: "freshness", kind, ok: false, detail, age_seconds: null, max_age_seconds: 0 }));
|
|
124
|
+
}
|
|
125
|
+
/** Why the action cannot be judged at all (bad clock, bad amount, other currency, unknown value refused), or null. */
|
|
126
|
+
function preconditionProblem(policy, nowValid, amountValid, qCurrency, c) {
|
|
127
|
+
const currency = policy.max_expected_loss.currency;
|
|
128
|
+
if (!nowValid)
|
|
129
|
+
return "the verifier's clock is not a valid date";
|
|
130
|
+
if (!amountValid)
|
|
131
|
+
return "amount is not a finite number >= 0";
|
|
132
|
+
if (qCurrency && qCurrency !== currency)
|
|
133
|
+
return `loss tolerance is in ${currency}, operation in ${qCurrency}`;
|
|
134
|
+
if (c.value === undefined && c.amount === undefined && policy.unvalued_action === "refuse") {
|
|
135
|
+
const subject = c.action ? `"${c.action}"` : "an unnamed action";
|
|
136
|
+
return `no amount and no risk value for ${subject}; the policy refuses actions of unknown value`;
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
/** What the limit is based on, for the verdict's text. */
|
|
141
|
+
function basisOf(c, currency) {
|
|
142
|
+
if (c.amount !== undefined)
|
|
143
|
+
return `for ${c.amount} ${currency}`;
|
|
144
|
+
if (c.value !== undefined)
|
|
145
|
+
return `for "${c.action}" (risk value ${c.value} ${currency})`;
|
|
146
|
+
const forAction = c.action ? ` and no risk value for "${c.action}"` : "";
|
|
147
|
+
return `no amount${forAction}, ceiling applies`;
|
|
148
|
+
}
|
|
149
|
+
/** The evidence with the latest as_of: a newer statement supersedes an older one, whatever it says. */
|
|
150
|
+
function freshestOf(usable) {
|
|
151
|
+
let e = usable[0];
|
|
152
|
+
let asOf = Date.parse(e.as_of);
|
|
153
|
+
for (const candidate of usable) {
|
|
154
|
+
const t = Date.parse(candidate.as_of);
|
|
155
|
+
if (t > asOf) {
|
|
156
|
+
e = candidate;
|
|
157
|
+
asOf = t;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return { e, asOf };
|
|
161
|
+
}
|
|
162
|
+
function isPastValidity(e, nowMs) {
|
|
163
|
+
if (!e.valid_until)
|
|
164
|
+
return false;
|
|
165
|
+
const until = Date.parse(e.valid_until);
|
|
166
|
+
return !Number.isNaN(until) && until < nowMs;
|
|
167
|
+
}
|
|
168
|
+
/** One required kind: its check, and whether fresher (or any) evidence would change the answer. */
|
|
169
|
+
function checkKind(kind, evidence, c) {
|
|
170
|
+
const { policy, nowMs } = c;
|
|
171
|
+
const max = maxStatusAgeSeconds(policy, kind, c.amount, c.action);
|
|
172
|
+
const limit = `${basisOf(c, policy.max_expected_loss.currency)}: at most ${human(max)}`;
|
|
173
|
+
const result = (ok, detail, age, refresh = false) => ({ check: { rule: "freshness", kind, ok, detail, age_seconds: age, max_age_seconds: max }, refresh });
|
|
174
|
+
const usable = evidence.filter((e) => e && e.kind === kind && !Number.isNaN(Date.parse(e.as_of)));
|
|
175
|
+
if (!usable.length)
|
|
176
|
+
return result(false, `no ${kind} status evidence; ${limit}`, null, true);
|
|
177
|
+
const { e, asOf } = freshestOf(usable);
|
|
178
|
+
const age = Math.floor((nowMs - asOf) / 1000);
|
|
179
|
+
const ageShown = Math.max(0, age);
|
|
180
|
+
const from = e.source ? ` (${e.source})` : "";
|
|
181
|
+
if (asOf - nowMs > policy.max_clock_skew_seconds * 1000) {
|
|
182
|
+
return result(false, `${kind} evidence${from} is dated ${e.as_of}, after the verifier's clock ${c.nowText} beyond the ${policy.max_clock_skew_seconds} s tolerance`, age);
|
|
183
|
+
}
|
|
184
|
+
if (policy.past_valid_until === "refuse" && isPastValidity(e, nowMs))
|
|
185
|
+
return result(false, `${kind} evidence${from} expired at ${e.valid_until}`, ageShown, true);
|
|
186
|
+
if (!e.in_force) {
|
|
187
|
+
const status = e.status ? ` (${e.status})` : "";
|
|
188
|
+
return result(false, `${kind} is not in force${status} as of ${e.as_of}${from}`, ageShown);
|
|
189
|
+
}
|
|
190
|
+
const fresh = ageShown <= max;
|
|
191
|
+
return result(fresh, `${kind} status${from} is ${human(ageShown)} old; ${limit}`, ageShown, !fresh);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Checks that, for every kind the policy requires, the freshest evidence given says "in force", is not
|
|
195
|
+
* past its own validity (unless the policy accepts that), is not dated in the future beyond the clock skew,
|
|
196
|
+
* and is younger than the maximum age for this value. Fails closed: missing, malformed or foreign-currency
|
|
197
|
+
* input never passes.
|
|
198
|
+
*/
|
|
199
|
+
export function checkFreshness(policy, evidence, q) {
|
|
200
|
+
const now = q.now;
|
|
201
|
+
const nowValid = now instanceof Date && !Number.isNaN(now.getTime());
|
|
202
|
+
const amount = q.amount;
|
|
203
|
+
const action = q.action?.trim().toLowerCase() || undefined;
|
|
204
|
+
const amountValid = amount === undefined || (typeof amount === "number" && Number.isFinite(amount) && amount >= 0);
|
|
205
|
+
const value = amountValid ? valueAtRisk(policy, amount, action) : undefined;
|
|
206
|
+
const nowText = nowValid ? now.toISOString() : "invalid";
|
|
207
|
+
const applied = {
|
|
208
|
+
now: nowText,
|
|
209
|
+
action: action ?? null,
|
|
210
|
+
amount: amount ?? null,
|
|
211
|
+
value_at_risk: value ?? null,
|
|
212
|
+
currency: policy.max_expected_loss.currency,
|
|
213
|
+
max_expected_loss: policy.max_expected_loss,
|
|
214
|
+
revocation_rate_per_hour: policy.revocation_rate_per_hour,
|
|
215
|
+
max_age_seconds: policy.max_age_seconds,
|
|
216
|
+
max_clock_skew_seconds: policy.max_clock_skew_seconds,
|
|
217
|
+
unvalued_action: policy.unvalued_action,
|
|
218
|
+
past_valid_until: policy.past_valid_until,
|
|
219
|
+
custom_max_age: !!policy.max_age
|
|
220
|
+
};
|
|
221
|
+
const c = { policy, nowMs: nowValid ? now.getTime() : Number.NaN, nowText, amount, action, value };
|
|
222
|
+
const problem = preconditionProblem(policy, nowValid, amountValid, q.currency?.trim().toUpperCase(), c);
|
|
223
|
+
if (problem)
|
|
224
|
+
return { ok: false, checks: failAll(policy, problem), refresh: [], applied };
|
|
225
|
+
const results = policy.require.map((kind) => checkKind(kind, evidence, c));
|
|
226
|
+
const checks = results.map((r) => r.check);
|
|
227
|
+
const refresh = policy.require.filter((_, i) => results[i].refresh);
|
|
228
|
+
return { ok: checks.length > 0 && checks.every((x) => x.ok), checks, refresh, applied };
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* The mandate (checkAction) and the freshness of the status, in one answer: allowed only when both pass.
|
|
232
|
+
* The freshness check uses the action's name, amount and currency and the same clock.
|
|
233
|
+
*/
|
|
234
|
+
export function checkFreshAction(mandate, q, p) {
|
|
235
|
+
const now = q.now;
|
|
236
|
+
const m = checkAction(mandate, { ...q, now });
|
|
237
|
+
const f = checkFreshness(p.policy, p.evidence, { action: q.action, amount: q.amount, currency: q.currency, now });
|
|
238
|
+
return { allowed: m.allowed && f.ok, mandate: m, freshness: f };
|
|
239
|
+
}
|
|
240
|
+
/** Evidence about the certificate from a CRL lookup (checkRevocation / verifyCrl().lookup). */
|
|
241
|
+
export function evidenceFromRevocation(r, source) {
|
|
242
|
+
return {
|
|
243
|
+
kind: "certificate",
|
|
244
|
+
in_force: !r.revoked,
|
|
245
|
+
as_of: r.crl_this_update,
|
|
246
|
+
valid_until: r.crl_next_update,
|
|
247
|
+
source: source ?? "CRL",
|
|
248
|
+
status: r.revoked ? (r.reason ?? "revoked") : "not revoked"
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Evidence about the credential from an answer the issuer signed (a verdict from /allowed, a paid
|
|
253
|
+
* verification receipt): any answer carrying `credential_id`, `status` and an Ed25519 `attestation`. The
|
|
254
|
+
* agent can staple such an answer to its request so the verifier needs no network. The answer must be
|
|
255
|
+
* about `credentialId` and verify with the issuer's key; the status instant is the signature's.
|
|
256
|
+
*/
|
|
257
|
+
export async function evidenceFromSignedStatus(answer, issuerPublicJwk, credentialId) {
|
|
258
|
+
if (!answer || typeof answer !== "object")
|
|
259
|
+
throw new KyaError("INVALID_INPUT", "signed status: expected an object");
|
|
260
|
+
if (answer.credential_id !== credentialId)
|
|
261
|
+
throw new KyaError("INVALID_INPUT", `signed status is about ${String(answer.credential_id)}, not ${credentialId}`);
|
|
262
|
+
if (typeof answer.status !== "string")
|
|
263
|
+
throw new KyaError("INVALID_INPUT", "signed status has no status");
|
|
264
|
+
const sig = await verifyAttestation(answer, issuerPublicJwk);
|
|
265
|
+
if (!sig.valid || !sig.signed_at)
|
|
266
|
+
throw new KyaError("INVALID_INPUT", `signed status does not verify: ${sig.reason ?? "no signature time"}`);
|
|
267
|
+
return { kind: "credential", in_force: answer.status === "active", as_of: sig.signed_at, source: "issuer signed status", status: answer.status };
|
|
268
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/revocation.d.ts
CHANGED
|
@@ -26,11 +26,16 @@ export interface VerifiedCrl {
|
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
28
|
* Parses and verifies a DER CRL against `issuerCertificate` (base64 DER). Throws REVOCATION_UNAVAILABLE
|
|
29
|
-
* when the CRL cannot be trusted (bad encoding, other issuer, bad signature
|
|
29
|
+
* when the CRL cannot be trusted (bad encoding, other issuer, bad signature).
|
|
30
|
+
*
|
|
31
|
+
* `pastNextUpdate` is the caller's choice for a CRL whose nextUpdate has passed: "refuse" throws (the usual
|
|
32
|
+
* reading of RFC 5280); "accept" returns it, still reporting next_update, for callers that bound the risk by
|
|
33
|
+
* the CRL's age instead (Li and Feigenbaum, FC 2001; SPEC section 18).
|
|
30
34
|
*/
|
|
31
35
|
export declare function verifyCrl(p: {
|
|
32
36
|
crlDer: ArrayBuffer | Uint8Array;
|
|
33
37
|
issuerCertificate: string;
|
|
38
|
+
pastNextUpdate: "refuse" | "accept";
|
|
34
39
|
now?: Date;
|
|
35
40
|
}): Promise<VerifiedCrl>;
|
|
36
41
|
/** One-shot check of `serial` against a DER CRL signed by `issuerCertificate`; see verifyCrl. */
|
|
@@ -38,6 +43,7 @@ export declare function checkRevocation(p: {
|
|
|
38
43
|
crlDer: ArrayBuffer | Uint8Array;
|
|
39
44
|
serial: string;
|
|
40
45
|
issuerCertificate: string;
|
|
46
|
+
pastNextUpdate: "refuse" | "accept";
|
|
41
47
|
now?: Date;
|
|
42
48
|
}): Promise<RevocationStatus>;
|
|
43
49
|
/**
|
package/dist/revocation.js
CHANGED
|
@@ -27,9 +27,15 @@ export function crlUrlsOf(cert) {
|
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
29
|
* Parses and verifies a DER CRL against `issuerCertificate` (base64 DER). Throws REVOCATION_UNAVAILABLE
|
|
30
|
-
* when the CRL cannot be trusted (bad encoding, other issuer, bad signature
|
|
30
|
+
* when the CRL cannot be trusted (bad encoding, other issuer, bad signature).
|
|
31
|
+
*
|
|
32
|
+
* `pastNextUpdate` is the caller's choice for a CRL whose nextUpdate has passed: "refuse" throws (the usual
|
|
33
|
+
* reading of RFC 5280); "accept" returns it, still reporting next_update, for callers that bound the risk by
|
|
34
|
+
* the CRL's age instead (Li and Feigenbaum, FC 2001; SPEC section 18).
|
|
31
35
|
*/
|
|
32
36
|
export async function verifyCrl(p) {
|
|
37
|
+
if (p.pastNextUpdate !== "refuse" && p.pastNextUpdate !== "accept")
|
|
38
|
+
throw new KyaError("INVALID_INPUT", 'pastNextUpdate is required: "refuse" or "accept"');
|
|
33
39
|
const now = p.now ?? new Date();
|
|
34
40
|
let crl;
|
|
35
41
|
let issuer;
|
|
@@ -44,7 +50,7 @@ export async function verifyCrl(p) {
|
|
|
44
50
|
throw new KyaError("REVOCATION_UNAVAILABLE", `CRL issued by "${crl.issuer}", not by the certificate's AC "${issuer.subject}"`);
|
|
45
51
|
if (!(await crl.verify({ publicKey: issuer }, globalThis.crypto)))
|
|
46
52
|
throw new KyaError("REVOCATION_UNAVAILABLE", "CRL signature does not match the AC certificate");
|
|
47
|
-
if (crl.nextUpdate && crl.nextUpdate < now)
|
|
53
|
+
if (p.pastNextUpdate === "refuse" && crl.nextUpdate && crl.nextUpdate < now)
|
|
48
54
|
throw new KyaError("REVOCATION_UNAVAILABLE", `CRL is stale (nextUpdate ${crl.nextUpdate.toISOString()})`);
|
|
49
55
|
const this_update = crl.thisUpdate.toISOString();
|
|
50
56
|
const next_update = crl.nextUpdate ? crl.nextUpdate.toISOString() : null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kya-brasil/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.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",
|