@crediolabs/policy-synth 0.1.18 → 0.2.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 (42) hide show
  1. package/README.md +3 -2
  2. package/dist/install/authority-overlap.d.ts +134 -0
  3. package/dist/install/authority-overlap.js +0 -0
  4. package/dist/install/build-add-context-rule.d.ts +8 -0
  5. package/dist/install/build-add-context-rule.js +1 -1
  6. package/dist/install/build-merge-policy.d.ts +70 -0
  7. package/dist/install/build-merge-policy.js +130 -0
  8. package/dist/install/index.d.ts +2 -0
  9. package/dist/install/index.js +7 -0
  10. package/dist/install/plan-merge-policy.d.ts +49 -0
  11. package/dist/install/plan-merge-policy.js +86 -0
  12. package/dist/install/read-account-rules.d.ts +100 -0
  13. package/dist/install/read-account-rules.js +283 -0
  14. package/dist/run/index.d.ts +93 -8
  15. package/dist/run/index.js +282 -11
  16. package/dist/run/schemas.d.ts +290 -11
  17. package/dist/run/schemas.js +77 -11
  18. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  19. package/dist-cjs/install/authority-overlap.js +0 -0
  20. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  21. package/dist-cjs/install/build-add-context-rule.js +1 -0
  22. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  23. package/dist-cjs/install/build-merge-policy.js +134 -0
  24. package/dist-cjs/install/index.d.ts +2 -0
  25. package/dist-cjs/install/index.js +23 -2
  26. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  27. package/dist-cjs/install/plan-merge-policy.js +90 -0
  28. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  29. package/dist-cjs/install/read-account-rules.js +296 -0
  30. package/dist-cjs/run/index.d.ts +93 -8
  31. package/dist-cjs/run/index.js +283 -10
  32. package/dist-cjs/run/schemas.d.ts +290 -11
  33. package/dist-cjs/run/schemas.js +78 -12
  34. package/package.json +1 -1
  35. package/src/install/authority-overlap.ts +0 -0
  36. package/src/install/build-add-context-rule.ts +12 -1
  37. package/src/install/build-merge-policy.ts +219 -0
  38. package/src/install/index.ts +34 -0
  39. package/src/install/plan-merge-policy.ts +133 -0
  40. package/src/install/read-account-rules.ts +376 -0
  41. package/src/run/index.ts +386 -14
  42. package/src/run/schemas.ts +84 -11
package/dist/run/index.js CHANGED
@@ -17,17 +17,23 @@
17
17
  // No business logic. No retries. No session state. The same call shape can
18
18
  // drive the CLI (which calls into the same core directly without MCP).
19
19
  import { createHash } from 'node:crypto';
20
- import { rpc } from '@stellar/stellar-sdk';
20
+ import { rpc, xdr } from '@stellar/stellar-sdk';
21
21
  import { placeholderOzConfig, recordTransaction, synthesizeFromMandate, synthesizeFromRecording, } from "../index.js";
22
+ import { findAuthorityOverlaps, } from "../install/authority-overlap.js";
22
23
  import { buildInstallPolicyXdr, buildRevokePolicyXdr, rpcClientFromServer, } from "../install/build-install-policy.js";
24
+ import { buildMergePolicyXdr } from "../install/build-merge-policy.js";
23
25
  import { getInterpreterInfo } from "../install/get-interpreter-info.js";
26
+ import { planMergePolicy } from "../install/plan-merge-policy.js";
27
+ import { accountRuleReaderFromServer, collectObservedRules, nonceLedgerKey, } from "../install/read-account-rules.js";
28
+ import { decodePredicate } from "../predicate/decode.js";
29
+ import { encodePredicate } from "../predicate/encode.js";
24
30
  import { simulatePolicy, verifyPolicy } from "../verify/index.js";
25
- import { GetInterpreterInfoInputSchema, InstallPolicyInputSchema, NETWORK_PASSPHRASES, PINNED_INTERPRETER_ADDRESS_BY_NETWORK, PINNED_INTERPRETER_GRAMMAR_VERSION, PINNED_INTERPRETER_WASM_SHA256, RecordTransactionInputSchema, RevokePolicyInputSchema, RPC_URL_BY_NETWORK, SimulatePolicyInputSchema, SynthesizePolicyInputSchema, VerifyPolicyInputSchema, } from "./schemas.js";
31
+ import { GetInterpreterInfoInputSchema, InstallPolicyInputSchema, MergePolicyInputSchema, NETWORK_PASSPHRASES, PINNED_INTERPRETER_ADDRESS_BY_NETWORK, PINNED_INTERPRETER_GRAMMAR_VERSION, PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK, RecordTransactionInputSchema, RevokePolicyInputSchema, RPC_URL_BY_NETWORK, SimulatePolicyInputSchema, SynthesizePolicyInputSchema, VerifyPolicyInputSchema, } from "./schemas.js";
26
32
  // Re-export the underlying Zod schemas so the MCP package (and any other
27
33
  // downstream consumer) can import the canonical input shapes from the same
28
34
  // module that owns the tool-body glue. The strict schemas are the source of
29
35
  // truth - MCP tool shapes are derived from them.
30
- export { ComposeUserResponsesSchema, GetInterpreterInfoInputSchema, InstallPolicyInputSchema, InterpreterOptionsSchema, MAINNET_RPC_URL, MandateSpecSchema, NetworkSchema, OraclePriceFixtureSchema, OzAdapterConfigSchema, PINNED_INTERPRETER_ADDRESS_BY_NETWORK, PINNED_INTERPRETER_GRAMMAR_VERSION, PINNED_INTERPRETER_MAINNET_ADDRESS, PINNED_INTERPRETER_TESTNET_ADDRESS, PINNED_INTERPRETER_WASM_SHA256, PredicateLeafSchema, PredicateNodeSchema, RecordedTransactionSchema, RecordTransactionInputSchema, RevokePolicyInputSchema, RPC_URL_BY_NETWORK, SimulatePolicyInputSchema, SynthesizePolicyInputSchema, TESTNET_RPC_URL, ToolErrorSchema, VerifyPolicyInputSchema, } from "./schemas.js";
36
+ export { ComposeUserResponsesSchema, GetInterpreterInfoInputSchema, InstallPolicyInputSchema, InterpreterOptionsSchema, MAINNET_RPC_URL, MandateSpecSchema, NetworkSchema, OraclePriceFixtureSchema, OzAdapterConfigSchema, PINNED_INTERPRETER_ADDRESS_BY_NETWORK, PINNED_INTERPRETER_GRAMMAR_VERSION, PINNED_INTERPRETER_MAINNET_ADDRESS, PINNED_INTERPRETER_TESTNET_ADDRESS, PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK, PredicateLeafSchema, PredicateNodeSchema, RecordedTransactionSchema, RecordTransactionInputSchema, RevokePolicyInputSchema, RPC_URL_BY_NETWORK, SimulatePolicyInputSchema, SynthesizePolicyInputSchema, TESTNET_RPC_URL, ToolErrorSchema, VerifyPolicyInputSchema, } from "./schemas.js";
31
37
  /** Map every tool name to its canonical domain error code. Replaces a 7-way
32
38
  * if/else so adding a tool adds one line here rather than a new branch in
33
39
  * each envelope call. */
@@ -254,6 +260,25 @@ export async function runInstallPolicy(raw) {
254
260
  const predicateHash = createHash('sha256')
255
261
  .update(Buffer.from(encodedPredicate, 'base64'))
256
262
  .digest('hex');
263
+ // ---- Cross-rule authority scan ----
264
+ // OZ enforces only the policies of the rule the caller names, so a signer
265
+ // who also sits in a wider rule keeps that wider authority no matter what
266
+ // this predicate says. Refuse by default when the wider rule has no policy
267
+ // at all, because that makes this install decorative.
268
+ const authorityScan = input.skipAuthorityScan
269
+ ? { ran: false, skipped: true, reason: 'skipped at caller request', overlaps: [] }
270
+ : await scanAuthorityOverlap({
271
+ smartAccount: input.smartAccount,
272
+ interpreterAddress: expectedInterpreter,
273
+ rule: input.rule,
274
+ encodedPredicate,
275
+ rpcUrl: input.rpcUrl ?? expectedRpc,
276
+ network,
277
+ });
278
+ const overlapError = enforceAuthorityScan(authorityScan, input.allowAuthorityOverlap);
279
+ if (overlapError) {
280
+ return { ok: false, error: overlapError };
281
+ }
257
282
  const result = await buildInstallPolicyXdr({
258
283
  smartAccount: input.smartAccount,
259
284
  sourceAccount: input.sourceAccount,
@@ -265,7 +290,7 @@ export async function runInstallPolicy(raw) {
265
290
  rpc: rpcClient,
266
291
  ...(input.baseFee !== undefined ? { baseFee: input.baseFee } : {}),
267
292
  });
268
- return { ok: true, data: result };
293
+ return { ok: true, data: authorityScan ? { ...result, authorityScan } : result };
269
294
  }
270
295
  catch (e) {
271
296
  return {
@@ -274,6 +299,252 @@ export async function runInstallPolicy(raw) {
274
299
  };
275
300
  }
276
301
  }
302
+ /** Default-deny on the cross-rule scan.
303
+ *
304
+ * Refuses whenever the scan cannot establish that this policy binds the calls
305
+ * it names. An unpoliced neighbour provably does not constrain them. An
306
+ * opaque one, policed by a contract this tool cannot decode, is not KNOWN to,
307
+ * and "not known to" is not "safe" - the same posture as the interpreter and
308
+ * RPC pins. An incomplete scan is refused for the same reason: the overlap
309
+ * list is then a subset of the account, so an empty list proves nothing.
310
+ *
311
+ * `not-restricting` is reported but does NOT block. Both rules are ours and
312
+ * both constrain the calls, and the conjunction remedy is offered; refusing
313
+ * there would also block the legitimate act of adding a separate capability,
314
+ * which OZ composes correctly as a union.
315
+ *
316
+ * Returns a ToolError or null, matching `enforceInterpreterPin`. */
317
+ export function enforceAuthorityScan(scan, allowOverlap) {
318
+ if (!scan || allowOverlap === true)
319
+ return null;
320
+ // Default-deny by exclusion rather than by enumeration: anything that is not
321
+ // the one known-safe severity blocks. Listing the blocking severities
322
+ // instead would mean a severity added later silently passes until someone
323
+ // remembers to add it here, and the safe direction is the opposite.
324
+ const blocking = scan.overlaps.filter((o) => o.severity !== 'not-restricting');
325
+ const unpoliced = blocking.filter((o) => o.severity === 'bypass').map((o) => o.ruleId);
326
+ const opaque = blocking.filter((o) => o.severity === 'unknown').map((o) => o.ruleId);
327
+ const unrecognised = blocking
328
+ .filter((o) => o.severity !== 'bypass' && o.severity !== 'unknown')
329
+ .map((o) => o.ruleId);
330
+ if (blocking.length > 0) {
331
+ const parts = [
332
+ unpoliced.length > 0 ? `rule ${unpoliced.join(', ')} has no policy attached` : '',
333
+ opaque.length > 0
334
+ ? `rule ${opaque.join(', ')} is policed by a contract this tool cannot decode`
335
+ : '',
336
+ unrecognised.length > 0
337
+ ? `rule ${unrecognised.join(', ')} carries an overlap this build does not recognise`
338
+ : '',
339
+ ].filter(Boolean);
340
+ return {
341
+ code: 'INSTALL_BUILD_FAILED',
342
+ message: `install_policy: a signer of this rule can already make the same calls through another context rule, so this policy is not established to restrict them: ${parts.join('; ')}. Remove the shared signer from that rule, attach a policy this tool can read, or set allowAuthorityOverlap: true to install anyway`,
343
+ severity: 'error',
344
+ retryable: false,
345
+ remediation: { toolCall: { name: 'install_policy', args: {} } },
346
+ };
347
+ }
348
+ // A scan that was meant to run and threw tells us nothing. Reporting it in
349
+ // a string field and proceeding is the same fail-open shape as an incomplete
350
+ // scan, and a caller that does not read `ran` cannot tell it from a clean
351
+ // result.
352
+ if (scan.ran === false && scan.skipped !== true) {
353
+ return {
354
+ code: 'INSTALL_BUILD_FAILED',
355
+ message: `install_policy: the cross-rule authority scan could not run (${scan.reason ?? 'unknown error'}), so it cannot establish that this policy restricts anything; retry, or set allowAuthorityOverlap: true to install without that assurance`,
356
+ severity: 'error',
357
+ retryable: true,
358
+ remediation: { toolCall: { name: 'install_policy', args: {} } },
359
+ };
360
+ }
361
+ if (scan.incomplete === true) {
362
+ return {
363
+ code: 'INSTALL_BUILD_FAILED',
364
+ message: 'install_policy: the account has more context rules than the scan could account for, so the overlap result is incomplete and cannot establish that this policy restricts anything; set allowAuthorityOverlap: true to install without that assurance',
365
+ severity: 'error',
366
+ retryable: false,
367
+ remediation: { toolCall: { name: 'install_policy', args: {} } },
368
+ };
369
+ }
370
+ return null;
371
+ }
372
+ /** Read the account's other context rules and report where this install's
373
+ * signers already hold authority over the same calls.
374
+ *
375
+ * A failure to read is reported rather than thrown, and the caller-facing
376
+ * decision is made by `enforceAuthorityScan`: a scan that tried and failed
377
+ * tells us nothing, so it refuses rather than passing as a clean account.
378
+ *
379
+ * The account data this trusts comes from whichever RPC answered, so a
380
+ * hostile RPC could describe an account with no overlapping rules. That is
381
+ * bounded by the pin already enforced above: `enforceRpcPin` returns before
382
+ * this runs, so the URL is the pinned one for the network unless the caller
383
+ * explicitly set `allowUnpinnedRpcUrl`. This scan deliberately does not add a
384
+ * second pin check, because two places deciding the same thing drift. */
385
+ async function scanAuthorityOverlap(args) {
386
+ try {
387
+ if (!args.encodedPredicate) {
388
+ // Not applicable rather than failed: this rule installs no interpreter
389
+ // predicate, so there is nothing of ours for another rule to undercut.
390
+ // Returning undefined keeps it out of the refusal path, which is
391
+ // reserved for scans that were meant to run and could not.
392
+ return undefined;
393
+ }
394
+ const server = new rpc.Server(args.rpcUrl, { allowHttp: false });
395
+ const reader = accountRuleReaderFromServer(server, NETWORK_PASSPHRASES[args.network]);
396
+ const collected = await collectObservedRules({
397
+ reader,
398
+ smartAccount: args.smartAccount,
399
+ interpreterAddress: args.interpreterAddress,
400
+ });
401
+ const overlaps = findAuthorityOverlaps({
402
+ intended: {
403
+ // `add_context_rule` always creates a NEW rule, so there is no id to
404
+ // exclude; -1 matches nothing on the account.
405
+ ruleId: -1,
406
+ contextType: toOverlapContextType(args.rule.contextRuleType),
407
+ signers: args.rule.signers,
408
+ predicate: decodePredicate(args.encodedPredicate),
409
+ },
410
+ existing: collected.rules,
411
+ });
412
+ return { ran: true, incomplete: collected.incomplete, overlaps };
413
+ }
414
+ catch (e) {
415
+ return {
416
+ ran: false,
417
+ reason: e instanceof Error ? e.message : String(e),
418
+ overlaps: [],
419
+ };
420
+ }
421
+ }
422
+ /** The rule draft names the callee `contract`; the analyser calls it
423
+ * `address`. Same value, two vocabularies. */
424
+ function toOverlapContextType(ct) {
425
+ switch (ct.kind) {
426
+ case 'call_contract':
427
+ return { kind: 'call_contract', address: ct.contract };
428
+ case 'create_contract':
429
+ return { kind: 'create_contract', wasmHash: ct.wasmHash };
430
+ default:
431
+ return { kind: 'default' };
432
+ }
433
+ }
434
+ /** `merge_policy` body - the tightening remedy for a cross-rule overlap.
435
+ *
436
+ * Replaces a rule's predicate with the conjunction of it and a new one. This
437
+ * is the action `install_policy` recommends when it reports an overlap
438
+ * between two rules our interpreter polices, and it is deliberately NOT
439
+ * something `install_policy` does on its own: it detaches a live policy, so
440
+ * the operator has to ask for it.
441
+ *
442
+ * Two transactions in order. `add_policy` refuses a policy already on the
443
+ * rule, so the old attachment goes first, and the second transaction cannot
444
+ * be simulated until the first confirms. */
445
+ export async function runMergePolicy(raw) {
446
+ const parsed = MergePolicyInputSchema.safeParse(raw);
447
+ if (!parsed.success) {
448
+ return { ok: false, error: validationError('install_policy', parsed.error.issues) };
449
+ }
450
+ const input = parsed.data;
451
+ const network = input.network ?? 'testnet';
452
+ const expectedInterpreter = PINNED_INTERPRETER_ADDRESS_BY_NETWORK[network];
453
+ const expectedRpc = RPC_URL_BY_NETWORK[network];
454
+ const rpcPinningError = enforceRpcPin('install_policy', input.rpcUrl, input.allowUnpinnedRpcUrl, expectedRpc, network);
455
+ if (rpcPinningError)
456
+ return { ok: false, error: rpcPinningError };
457
+ try {
458
+ const rpcUrl = input.rpcUrl ?? expectedRpc;
459
+ const server = new rpc.Server(rpcUrl, { allowHttp: false });
460
+ const reader = accountRuleReaderFromServer(server, NETWORK_PASSPHRASES[network]);
461
+ const collected = await collectObservedRules({
462
+ reader,
463
+ smartAccount: input.smartAccount,
464
+ interpreterAddress: expectedInterpreter,
465
+ });
466
+ const rule = collected.rules.find((r) => r.id === input.ruleId);
467
+ if (!rule) {
468
+ return {
469
+ ok: false,
470
+ error: {
471
+ code: 'INSTALL_BUILD_FAILED',
472
+ message: `merge_policy: rule ${input.ruleId} was not found on ${input.smartAccount}${collected.incomplete
473
+ ? ' (the rule scan was incomplete, so it may exist but was not reached)'
474
+ : ''}`,
475
+ severity: 'error',
476
+ retryable: false,
477
+ remediation: { toolCall: { name: 'install_policy', args: {} } },
478
+ },
479
+ };
480
+ }
481
+ const plan = planMergePolicy({
482
+ rule,
483
+ interpreterAddress: expectedInterpreter,
484
+ incoming: decodePredicate(input.incomingPredicateBlobBase64),
485
+ step: input.step,
486
+ });
487
+ if (!plan.ok) {
488
+ return {
489
+ ok: false,
490
+ error: {
491
+ code: 'INSTALL_BUILD_FAILED',
492
+ message: `merge_policy: ${plan.reason}`,
493
+ severity: 'error',
494
+ retryable: false,
495
+ remediation: { toolCall: { name: 'install_policy', args: {} } },
496
+ },
497
+ };
498
+ }
499
+ const encoded = encodePredicate(plan.predicate);
500
+ // The nonce is read, not assumed. OZ's `remove_policy` discards the result
501
+ // of `try_uninstall`, so a detach whose uninstall panicked - our
502
+ // `uninstall` panics MissingState when the master set has been archived -
503
+ // detaches the policy while leaving our nonce behind. Re-installing at 1
504
+ // would then be refused as a replay and the rule would sit unpoliced.
505
+ let installNonce = 1;
506
+ const nonceWarnings = [];
507
+ if (input.step === 'reinstall') {
508
+ const entries = await server.getLedgerEntries(nonceLedgerKey(expectedInterpreter, input.smartAccount, input.ruleId));
509
+ const raw = entries.entries?.[0]?.val;
510
+ const stored = raw && raw.switch() === xdr.LedgerEntryType.contractData()
511
+ ? raw.contractData().val()
512
+ : undefined;
513
+ if (stored && stored.switch() === xdr.ScValType.scvU32()) {
514
+ installNonce = stored.u32() + 1;
515
+ nonceWarnings.push(`the previous uninstall did not complete: rule ${input.ruleId} still holds interpreter state at nonce ${stored.u32()}, so this reinstalls at ${installNonce} rather than 1. The rule's counters were NOT reset.`);
516
+ }
517
+ }
518
+ const built = await buildMergePolicyXdr({
519
+ smartAccount: input.smartAccount,
520
+ sourceAccount: input.sourceAccount,
521
+ networkPassphrase: NETWORK_PASSPHRASES[network],
522
+ ruleId: input.ruleId,
523
+ policyId: plan.policyId,
524
+ interpreterAddress: expectedInterpreter,
525
+ step: input.step,
526
+ encodedPredicate: encoded.encodedPredicate,
527
+ predicateHash: encoded.predicateHash,
528
+ installNonce,
529
+ ...(plan.oracleParams ? { oracleParams: plan.oracleParams } : {}),
530
+ rpc: rpcClientFromServer(server, NETWORK_PASSPHRASES[network]),
531
+ ...(input.baseFee !== undefined ? { baseFee: input.baseFee } : {}),
532
+ });
533
+ return {
534
+ ok: true,
535
+ data: {
536
+ ...built,
537
+ mergedPredicateHash: encoded.predicateHash,
538
+ mergedPredicateBlobBase64: encoded.encodedPredicate,
539
+ warnings: [...plan.warnings, ...nonceWarnings],
540
+ followUp: plan.followUp,
541
+ },
542
+ };
543
+ }
544
+ catch (e) {
545
+ return { ok: false, error: caughtError('install_policy', 'INSTALL_BUILD_FAILED', e) };
546
+ }
547
+ }
277
548
  /** `revoke_policy` body - thin wrapper over `buildRevokePolicyXdr`.
278
549
  * Emits an unsigned XDR for `account.remove_context_rule(ruleId)`; the
279
550
  * smart account itself handles uninstalling each attached policy. Auth
@@ -333,12 +604,12 @@ export async function runRevokePolicy(raw) {
333
604
  * fabricating it would be a lie on a security surface; the live
334
605
  * mismatch check is worth MORE).
335
606
  *
336
- * Network-aware: `input.network` selects which interpreter pin and RPC
337
- * to use. Mainnet was rolled out 2026-08-04 - the same wasm hash was
338
- * uploaded to mainnet as was exercised on testnet, so a single
339
- * `PINNED_INTERPRETER_WASM_SHA256` constant backs both networks.
340
- * The address differs because instance ids are network-scoped.
341
- * UNAUDITED at the time of writing.
607
+ * Network-aware: `input.network` selects the interpreter address, the RPC
608
+ * and the wasm hash. The networks run different binaries - testnet carries
609
+ * the selector-leaf minimum and the signer-set cap, mainnet predates both -
610
+ * so the hash is read through
611
+ * `PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK`. UNAUDITED at the time of
612
+ * writing.
342
613
  *
343
614
  * Same RPC pin as install/revoke: when `verifyLive` triggers an outbound
344
615
  * call, the auth-digest + the answer bind to whichever RPC answered, so
@@ -378,7 +649,7 @@ export async function runGetInterpreterInfo(raw) {
378
649
  const info = getInterpreterInfo({
379
650
  pinnedAddress,
380
651
  pinnedGrammarVersion: PINNED_INTERPRETER_GRAMMAR_VERSION,
381
- pinnedWasmHash: PINNED_INTERPRETER_WASM_SHA256,
652
+ pinnedWasmHash: PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK[network],
382
653
  network,
383
654
  ...(deployedGrammarVersion !== undefined ? { deployedGrammarVersion } : {}),
384
655
  });