@guardefi/cli 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +18 -0
  3. package/README.md +31 -2
  4. package/assurance/cli-check.js +446 -0
  5. package/assurance/cli-project-paths.js +56 -0
  6. package/assurance/cli-storage.js +289 -0
  7. package/assurance/cli-ui.js +617 -0
  8. package/assurance/guardefi-public.js +66 -0
  9. package/assurance/release-policy.js +212 -0
  10. package/core/behavioral-diff.js +555 -0
  11. package/core/canonical-json.js +9 -0
  12. package/core/engine/abi.js +99 -0
  13. package/core/engine/assumptions.json +86 -0
  14. package/core/engine/bytecode.js +119 -0
  15. package/core/engine/callee-binding.js +140 -0
  16. package/core/engine/deployment.js +175 -0
  17. package/core/engine/external-effects.js +40 -0
  18. package/core/engine/harness.js +503 -0
  19. package/core/engine/index.js +638 -0
  20. package/core/engine/integrity.js +124 -0
  21. package/core/engine/model.js +369 -0
  22. package/core/engine/policy.js +59 -0
  23. package/core/engine/proof-certificate.js +69 -0
  24. package/core/engine/provenance.js +354 -0
  25. package/core/engine/screen.js +117 -0
  26. package/core/engine/upgrade-authority.js +327 -0
  27. package/core/generic.js +334 -0
  28. package/core/hardhat.js +114 -0
  29. package/core/isl/behavior-profile.js +169 -0
  30. package/core/isl/behavior-solidity.js +267 -0
  31. package/core/isl/behavior-storage.js +151 -0
  32. package/core/isl/behavior-verify.js +223 -0
  33. package/core/isl/getter-profile.js +149 -0
  34. package/core/isl/vendor/NOTICE.md +38 -0
  35. package/core/isl/vendor/isl-parser.cjs +5872 -0
  36. package/core/isl-compiler.js +19 -0
  37. package/core/isl-firewall.js +1396 -0
  38. package/core/keccak.js +89 -0
  39. package/core/prove.js +376 -0
  40. package/core/release-receipt.js +793 -0
  41. package/core/rpc.js +74 -0
  42. package/core/tools.js +129 -0
  43. package/core/verdict-policy.js +195 -0
  44. package/docs/public-cli.md +32 -0
  45. package/package.json +29 -4
@@ -0,0 +1,212 @@
1
+ // Release Policy: what is authorized. Deterministic evaluation of evidence against declared guarantees.
2
+ // SHIP authorized: every mandatory guarantee passed with an accepted kind of evidence.
3
+ // REVIEW blocked: evidence is incomplete or unsuitable, or an advisory check requires review.
4
+ // NO_SHIP blocked: a mandatory guarantee failed or policy treats a violation as blocking.
5
+ // The set of guarantees comes from the policy (and the spec it is built from), never from the evidence supplied.
6
+ const { createHash } = require('node:crypto');
7
+ const { canonical } = require('../core/canonical-json');
8
+
9
+ const LEGACY_POLICY_SCHEMA = 'guardefi.release-policy.v1';
10
+ const POLICY_SCHEMA = 'guardefi.release-policy.v2';
11
+ // Kinds of evidence. They are not ranked: a proof, a simulation and a live read establish different things,
12
+ // so each guarantee lists the kinds it accepts.
13
+ // proven unbounded proof bounded symbolic result within declared model bounds
14
+ // simulation executed transaction/fork static analysis of code or build artifacts
15
+ // runtime live chain observation none no evidence (only with status unknown)
16
+ const ASSURANCE = Object.freeze(['proven', 'bounded', 'simulation', 'static', 'runtime', 'none']);
17
+ const STATUSES = new Set(['pass', 'fail', 'unknown']);
18
+ const ID = /^[a-z0-9][a-z0-9._:-]{0,127}$/;
19
+ const POLICY_KEYS = new Set(['schema', 'name', 'version', 'guarantees', 'failOnUnclaimedEvidence', 'advisoryFailure']);
20
+ const GUARANTEE_KEYS = new Set(['id', 'statement', 'mandatory', 'accepts', 'evidence']);
21
+
22
+ function deepFreeze(value) {
23
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
24
+ Object.freeze(value);
25
+ for (const v of Object.values(value)) deepFreeze(v);
26
+ }
27
+ return value;
28
+ }
29
+
30
+ function parsePolicy(input) {
31
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Release policy must be a JSON object.');
32
+ for (const key of Object.keys(input)) if (!POLICY_KEYS.has(key)) throw new Error(`Unknown release policy field: ${key}`);
33
+ const policy = { failOnUnclaimedEvidence: true, advisoryFailure: 'REVIEW', ...input };
34
+ if (![POLICY_SCHEMA, LEGACY_POLICY_SCHEMA].includes(policy.schema)) {
35
+ throw new Error(`Release policy must use schema ${POLICY_SCHEMA} or ${LEGACY_POLICY_SCHEMA}.`);
36
+ }
37
+ if (typeof policy.name !== 'string' || !policy.name || typeof policy.version !== 'string' || !policy.version) throw new Error('Release policy needs a name and version.');
38
+ if (typeof policy.failOnUnclaimedEvidence !== 'boolean') throw new Error('failOnUnclaimedEvidence must be true or false.');
39
+ if (!['NO_SHIP', 'REVIEW'].includes(policy.advisoryFailure)) throw new Error('advisoryFailure must be NO_SHIP or REVIEW.');
40
+ if (!Array.isArray(policy.guarantees) || !policy.guarantees.length) throw new Error('A release policy must declare at least one guarantee.');
41
+ const ids = new Set();
42
+ for (const g of policy.guarantees) {
43
+ if (!g || typeof g !== 'object') throw new Error('Each guarantee must be an object.');
44
+ for (const key of Object.keys(g)) if (!GUARANTEE_KEYS.has(key)) throw new Error(`Unknown field ${key} in guarantee ${g.id}.`);
45
+ if (!ID.test(g.id || '') || ids.has(g.id)) throw new Error(`Invalid or duplicate guarantee id: ${g.id}`);
46
+ ids.add(g.id);
47
+ if (typeof g.statement !== 'string' || !g.statement) throw new Error(`Guarantee ${g.id} needs a statement.`);
48
+ if (typeof g.mandatory !== 'boolean') throw new Error(`Guarantee ${g.id} must say whether it is mandatory.`);
49
+ if (!Array.isArray(g.accepts) || !g.accepts.length || !g.accepts.every((a) => ASSURANCE.includes(a) && a !== 'none') || new Set(g.accepts).size !== g.accepts.length) {
50
+ throw new Error(`Guarantee ${g.id} must list the evidence kinds it accepts (${ASSURANCE.filter((a) => a !== 'none').join(', ')}).`);
51
+ }
52
+ if (!Array.isArray(g.evidence) || !g.evidence.length || !g.evidence.every((e) => ID.test(e)) || new Set(g.evidence).size !== g.evidence.length) {
53
+ throw new Error(`Guarantee ${g.id} must name at least one evidence source.`);
54
+ }
55
+ }
56
+ if (!policy.guarantees.some((g) => g.mandatory)) throw new Error('A release policy must have at least one mandatory guarantee.');
57
+ return policy;
58
+ }
59
+
60
+ /** Hash of the normalized policy. Receipts carry it, so any policy edit invalidates earlier evidence. */
61
+ const policyDigest = (policy) => createHash('sha256').update(canonical(parsePolicy(policy)), 'utf8').digest('hex');
62
+
63
+ function checkItem(item) {
64
+ if (!item || !ID.test(item.source || '') || !STATUSES.has(item.status) || !ASSURANCE.includes(item.assurance)) {
65
+ throw new Error(`Invalid evidence item: ${JSON.stringify(item)}`);
66
+ }
67
+ if (item.status !== 'unknown' && item.assurance === 'none') throw new Error(`Evidence ${item.source} decides a result with no assurance.`);
68
+ return { source: item.source, status: item.status, assurance: item.assurance, detail: item.detail ?? null };
69
+ }
70
+
71
+ const guarantee = (id, statement, evidence, accepts, mandatory = true) => ({ id, statement, mandatory, accepts, evidence });
72
+
73
+ /**
74
+ * Policy for an upgrade, built from what the project declares, not from what the checks happened to report.
75
+ * spec: the parsed spec/*.spec.json or null. hasBaseline: the release replaces a known implementation.
76
+ */
77
+ function upgradePolicy({ spec = null, hasBaseline = false, name = 'GuardeFi upgrade policy' } = {}) {
78
+ const guarantees = [];
79
+ if (spec && (spec.status === 'draft' || spec.authorized === false)) throw new Error('The project spec is an unreviewed draft (status: draft / authorized: false).');
80
+ if (spec) {
81
+ guarantees.push(guarantee('approved-interface', 'The candidate exposes only functions the spec approves.', ['spec:approved-interface'], ['static']));
82
+ for (const p of spec.properties) guarantees.push(guarantee(`spec.${p.toLowerCase()}`, `Spec property ${p} holds for the candidate.`, [`spec:${p.toLowerCase()}`], ['proven', 'bounded']));
83
+ }
84
+ if (hasBaseline) {
85
+ guarantees.push(
86
+ guarantee('storage-layout', 'Existing storage variables keep their slot, type and name.', ['generic:layout'], ['static']),
87
+ guarantee('no-dangerous-opcodes', 'No new SELFDESTRUCT, DELEGATECALL or CALLCODE.', ['generic:opcodes'], ['static']),
88
+ guarantee('roles-not-expanded', 'A caller without a role cannot change a role it could not change before.', ['generic:roles'], ['proven', 'bounded']),
89
+ guarantee('guards-not-removed', 'A call the old code rejected from an unprivileged caller is still rejected.', ['generic:guards'], ['proven', 'bounded']),
90
+ );
91
+ if (!spec) {
92
+ for (const p of ['layout', 'opcodes', 'guards', 'mutations', 'values', 'capabilities', 'upgrade', 'init', 'reentrancy', 'context']) {
93
+ guarantees.push(guarantee(`engine.${p}`, `Upgrade engine property ${p} holds.`, [`engine:${p}`], ['proven', 'bounded', 'static']));
94
+ }
95
+ }
96
+ }
97
+ if (!guarantees.length) throw new Error('Nothing to verify: the project has no spec and the release names no baseline.');
98
+ return deepFreeze({ schema: POLICY_SCHEMA, name, version: '1', failOnUnclaimedEvidence: true, advisoryFailure: 'REVIEW', guarantees });
99
+ }
100
+
101
+ /** Policy for a proposed multisig transaction. Every check is mandatory; reviewTransaction always emits each source. */
102
+ const TRANSACTION_POLICY = deepFreeze({
103
+ schema: POLICY_SCHEMA, name: 'GuardeFi transaction policy', version: '1', failOnUnclaimedEvidence: true, advisoryFailure: 'REVIEW',
104
+ guarantees: [
105
+ guarantee('tx.decoded', 'Every call that would execute is decoded.', ['tx:decoded'], ['static']),
106
+ guarantee('tx.no-untrusted-delegatecall', 'No delegatecall to a target the policy does not trust.', ['tx:delegatecall'], ['static']),
107
+ guarantee('tx.simulated', 'The transaction succeeds when simulated from the multisig at a pinned block.', ['tx:simulation'], ['simulation']),
108
+ guarantee('tx.upgrades-reviewed', 'Every new implementation matches a SHIP release receipt.', ['tx:upgrade-reviewed'], ['runtime', 'static']),
109
+ guarantee('tx.privileges-authorized', 'Every privilege grant goes to an authorized principal.', ['tx:privilege-authorized'], ['static']),
110
+ guarantee('tx.recipients-approved', 'Every asset recipient is on the allowlist.', ['tx:recipients-approved'], ['static']),
111
+ guarantee('tx.nonce-current', 'The transaction uses the multisig\'s next nonce.', ['tx:nonce-current'], ['runtime', 'static']),
112
+ ],
113
+ });
114
+ const LEGACY_TRANSACTION_POLICY = deepFreeze({ ...TRANSACTION_POLICY, schema: LEGACY_POLICY_SCHEMA });
115
+
116
+ /** Evidence items from a core/prove.js result. Halmos spec results are labelled bounded, not unbounded proofs. */
117
+ function evidenceFromProof(proof) {
118
+ const items = [];
119
+ const STATIC = new Set(['upgrade_layout', 'upgrade_opcodes']);
120
+ for (const p of proof.properties || []) {
121
+ if (p.name === 'Spec harness self-check' || p.name === 'Approved contract interface') continue;
122
+ const status = p.status === 'proven' || (p.status === undefined && p.proven) ? 'pass'
123
+ : p.status === 'failed' || p.status === 'violated' || (p.status === undefined && p.proven === false && p.counterexample) ? 'fail' : 'unknown';
124
+ const source = p.name.startsWith('upgrade_') ? `generic:${p.name.slice(8)}` : `spec:${p.name}`;
125
+ items.push({ source: source.toLowerCase(), status, assurance: status === 'unknown' ? 'none' : STATIC.has(p.name) ? 'static' : 'bounded',
126
+ detail: p.counterexample ? `Counterexample: ${JSON.stringify(p.counterexample)}` : p.name });
127
+ }
128
+ if (proof.properties?.some((p) => !p.name.startsWith('upgrade_'))) {
129
+ const outside = (proof.reasons || []).filter((r) => r.startsWith('function not in spec: ')).map((r) => r.slice(22));
130
+ items.push({ source: 'spec:approved-interface', status: outside.length ? 'fail' : 'pass', assurance: 'static',
131
+ detail: outside.length ? `Functions outside the approved interface: ${outside.join(', ')}` : 'Every external function is in the approved spec.' });
132
+ }
133
+ for (const p of proof.engineReport?.properties || []) {
134
+ const status = ['proven', 'bounded', 'accepted'].includes(p.status) ? 'pass' : ['violated', 'failed'].includes(p.status) ? 'fail' : 'unknown';
135
+ items.push({ source: `engine:${p.name}`.toLowerCase(), status,
136
+ assurance: status === 'unknown' ? 'none' : p.status === 'proven' ? 'proven' : p.status === 'bounded' ? 'bounded' : 'static',
137
+ detail: `${p.name}: ${p.status}${p.findings ? `, ${p.findings} finding(s)` : ''}${p.unverified ? `, ${p.unverified} unverified` : ''}` });
138
+ }
139
+ return items.map(checkItem);
140
+ }
141
+
142
+ /** Evidence items from an ISL getter observation (core/isl-observation.js) of the proposed deployment. A live read, not a proof. */
143
+ function evidenceFromIslObservation(observation) {
144
+ return observation.proposed.results.map((r) => checkItem({
145
+ source: `isl:${String(r.id).toLowerCase()}`,
146
+ status: r.status === 'satisfied' ? 'pass' : r.status === 'violated' ? 'fail' : 'unknown',
147
+ assurance: r.status === 'inconclusive' ? 'none' : 'runtime',
148
+ detail: `${r.signature} = ${r.value ?? 'unreadable'} on ${observation.proposed.address} at block ${observation.block} (${observation.blockHash})`,
149
+ }));
150
+ }
151
+
152
+ /** Decide the release. Pure and deterministic: the same policy and evidence give identical output. */
153
+ function decide(policyInput, evidenceInput) {
154
+ const policy = parsePolicy(policyInput);
155
+ if (!Array.isArray(evidenceInput)) throw new Error('Evidence must be a list.');
156
+ const evidence = evidenceInput.map(checkItem).sort((a, b) => (canonical(a) < canonical(b) ? -1 : canonical(a) > canonical(b) ? 1 : 0));
157
+ const claimed = new Set(policy.guarantees.flatMap((g) => g.evidence));
158
+
159
+ const results = policy.guarantees.map((g) => {
160
+ const items = evidence.filter((e) => g.evidence.includes(e.source));
161
+ const missing = g.evidence.filter((source) => !items.some((e) => e.source === source));
162
+ const rejected = items.filter((e) => e.status === 'pass' && !g.accepts.includes(e.assurance));
163
+ let status = 'pass';
164
+ let reason = null;
165
+ if (items.some((e) => e.status === 'fail')) { status = 'fail'; reason = 'An evidence source reports a violation.'; }
166
+ else if (missing.length) { status = 'unknown'; reason = `No evidence from ${missing.join(', ')}.`; }
167
+ else if (items.some((e) => e.status === 'unknown')) { status = 'unknown'; reason = 'An evidence source could not decide.'; }
168
+ else if (rejected.length) { status = 'unknown'; reason = `This guarantee accepts ${g.accepts.join('/')} evidence; got ${[...new Set(rejected.map((e) => e.assurance))].join('/')}.`; }
169
+ return { id: g.id, statement: g.statement, mandatory: g.mandatory, accepts: g.accepts, status, reason,
170
+ assurance: [...new Set(items.map((e) => e.assurance))].sort(), evidence: items };
171
+ }).sort((a, b) => (a.id < b.id ? -1 : 1));
172
+
173
+ // Evidence no guarantee claims is never silently ignored: a violation or an undecided check blocks or forces review.
174
+ const unclaimed = evidence.filter((e) => !claimed.has(e.source));
175
+ const legacy = policy.schema === LEGACY_POLICY_SCHEMA;
176
+ const blocking = [];
177
+ const review = [];
178
+ const pending = results.filter(r => r.status !== 'pass');
179
+ for (const r of [...pending.filter(r => r.mandatory), ...pending.filter(r => !r.mandatory)]) {
180
+ const blocks = r.mandatory ? legacy || r.status === 'fail'
181
+ : r.status === 'fail' && policy.advisoryFailure === 'NO_SHIP';
182
+ (blocks ? blocking : review).push(r.id);
183
+ }
184
+ for (const source of new Set(unclaimed.filter((e) => e.status !== 'pass').map((e) => e.source))) {
185
+ const blocks = policy.failOnUnclaimedEvidence &&
186
+ (legacy || unclaimed.some(e => e.source === source && e.status === 'fail'));
187
+ (blocks ? blocking : review).push(`unclaimed:${source}`);
188
+ }
189
+ const verdict = blocking.length ? 'NO_SHIP' : review.length ? 'REVIEW' : 'SHIP';
190
+ return {
191
+ verdict, authorized: verdict === 'SHIP',
192
+ policy: { name: policy.name, version: policy.version, digest: policyDigest(policy) },
193
+ blocking, review, guarantees: results,
194
+ unclaimedEvidence: unclaimed,
195
+ };
196
+ }
197
+
198
+ const ORDER = { SHIP: 0, REVIEW: 1, NO_SHIP: 2 };
199
+ /** The stricter of two verdicts. Used to combine this policy with the frozen engine's own release gate. */
200
+ function stricter(a, b) {
201
+ if (!Object.hasOwn(ORDER, a) || !Object.hasOwn(ORDER, b)) {
202
+ throw new Error(`Unknown verdict ${!Object.hasOwn(ORDER, a) ? a : b}.`);
203
+ }
204
+ return ORDER[a] >= ORDER[b] ? a : b;
205
+ }
206
+
207
+ /** Process exit code for CI: SHIP 0, NO_SHIP 1, usage or runtime error 2, REVIEW 3. Only 0 authorizes. */
208
+ const EXIT_CODES = { SHIP: 0, NO_SHIP: 1, REVIEW: 3 };
209
+ const exitCode = (verdict) => Object.hasOwn(EXIT_CODES, verdict) ? EXIT_CODES[verdict] : 2;
210
+
211
+ module.exports = { ASSURANCE, POLICY_SCHEMA, TRANSACTION_POLICY, LEGACY_TRANSACTION_POLICY, deepFreeze, parsePolicy, policyDigest, upgradePolicy,
212
+ evidenceFromProof, evidenceFromIslObservation, decide, stricter, exitCode };