@crediolabs/policy-synth 0.1.12 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/install/build-install-policy.d.ts +218 -0
- package/dist/install/build-install-policy.js +458 -0
- package/dist/install/get-interpreter-info.d.ts +29 -0
- package/dist/install/get-interpreter-info.js +41 -0
- package/dist/install/oz-auth.d.ts +27 -0
- package/dist/install/oz-auth.js +105 -0
- package/dist/run/index.d.ts +49 -4
- package/dist/run/index.js +324 -4
- package/dist/run/schemas.d.ts +1500 -4
- package/dist/run/schemas.js +288 -0
- package/dist-cjs/install/build-install-policy.d.ts +218 -0
- package/dist-cjs/install/build-install-policy.js +462 -0
- package/dist-cjs/install/get-interpreter-info.d.ts +29 -0
- package/dist-cjs/install/get-interpreter-info.js +44 -0
- package/dist-cjs/install/oz-auth.d.ts +27 -0
- package/dist-cjs/install/oz-auth.js +114 -0
- package/dist-cjs/run/index.d.ts +49 -4
- package/dist-cjs/run/index.js +339 -3
- package/dist-cjs/run/schemas.d.ts +1500 -4
- package/dist-cjs/run/schemas.js +289 -1
- package/package.json +1 -1
- package/src/install/build-install-policy.ts +753 -0
- package/src/install/get-interpreter-info.ts +68 -0
- package/src/install/oz-auth.ts +140 -0
- package/src/run/index.ts +405 -5
- package/src/run/schemas.ts +326 -0
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// src/install/build-install-policy.ts - builds the unsigned Soroban
|
|
3
|
+
// transaction XDR for `account.add_context_rule(...)` and
|
|
4
|
+
// `account.remove_context_rule(...)`.
|
|
5
|
+
//
|
|
6
|
+
// The MCP server is stateless and holds no key material (server.ts:10-12),
|
|
7
|
+
// so this module NEVER signs. The caller (the wallet / CLI / SDK consumer)
|
|
8
|
+
// wraps the returned XDR in a transaction envelope and signs that envelope
|
|
9
|
+
// with their wallet; the wallet signature IS the user-confirmation step.
|
|
10
|
+
//
|
|
11
|
+
// We deliberately depart from the spec in plans/phase-04 which calls for a
|
|
12
|
+
// two-call `install_policy`/`confirm_install` pair backed by a host-signed
|
|
13
|
+
// short-TTL `action_id`. That contract requires (a) a stateful store and
|
|
14
|
+
// (b) key material the server does not have, so we ship the simpler ONE-CALL
|
|
15
|
+
// shape. The wallet signature covers the change.
|
|
16
|
+
//
|
|
17
|
+
// `buildInstallPolicyXdr` returns CALL 1 ONLY. Call 2 (interpreter.install)
|
|
18
|
+
// needs the rule id the account assigns in call 1, so it cannot be pre-built
|
|
19
|
+
// and is documented in the response envelope under `followUp`.
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.DEFAULT_GRAMMAR_VERSION = exports.Contract = void 0;
|
|
22
|
+
exports.rpcClientFromServer = rpcClientFromServer;
|
|
23
|
+
exports.buildInstallPolicyXdr = buildInstallPolicyXdr;
|
|
24
|
+
exports.buildRevokePolicyXdr = buildRevokePolicyXdr;
|
|
25
|
+
const node_crypto_1 = require("node:crypto");
|
|
26
|
+
const stellar_sdk_1 = require("@stellar/stellar-sdk");
|
|
27
|
+
Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return stellar_sdk_1.Contract; } });
|
|
28
|
+
const build_add_context_rule_ts_1 = require("./build-add-context-rule.js");
|
|
29
|
+
Object.defineProperty(exports, "DEFAULT_GRAMMAR_VERSION", { enumerable: true, get: function () { return build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION; } });
|
|
30
|
+
const oz_auth_ts_1 = require("./oz-auth.js");
|
|
31
|
+
/** Convert a real rpc.Server into the InstallRpcClient surface. The
|
|
32
|
+
* `getContractVersion` lookup uses `simulateTransaction` against
|
|
33
|
+
* `contract.call('grammar_version')` and decodes the returned u32.
|
|
34
|
+
*
|
|
35
|
+
* The passphrase is a REQUIRED argument rather than something read off the
|
|
36
|
+
* server: `rpc.Server` does not carry one, so reaching for
|
|
37
|
+
* `server.networkPassphrase` yielded a non-string and every version probe
|
|
38
|
+
* died with "Invalid passphrase provided to Transaction". The caller knows
|
|
39
|
+
* which network it dialled; make it say so. */
|
|
40
|
+
function rpcClientFromServer(server, networkPassphrase) {
|
|
41
|
+
return {
|
|
42
|
+
getAccount: (address) => server.getAccount(address),
|
|
43
|
+
simulateTransaction: (tx) => server.simulateTransaction(tx),
|
|
44
|
+
getLatestLedger: () => server.getLatestLedger(),
|
|
45
|
+
async getContractVersion(address) {
|
|
46
|
+
// The source account is constructed locally rather than fetched. This is
|
|
47
|
+
// a read-only simulation, so the sequence number is never checked, and a
|
|
48
|
+
// random key does NOT exist on chain - asking the network for it returns
|
|
49
|
+
// 404 and the version probe fails for a reason that has nothing to do
|
|
50
|
+
// with the contract being probed.
|
|
51
|
+
const account = new stellar_sdk_2.Account(stellar_sdk_1.Keypair.random().publicKey(), '0');
|
|
52
|
+
const tx = new stellar_sdk_1.TransactionBuilder(account, {
|
|
53
|
+
fee: stellar_sdk_1.BASE_FEE,
|
|
54
|
+
networkPassphrase,
|
|
55
|
+
})
|
|
56
|
+
.addOperation(new stellar_sdk_1.Contract(address).call('grammar_version'))
|
|
57
|
+
.setTimeout(30)
|
|
58
|
+
.build();
|
|
59
|
+
const sim = await server.simulateTransaction(tx);
|
|
60
|
+
if (stellar_sdk_1.rpc.Api.isSimulationError(sim)) {
|
|
61
|
+
throw new Error(`getContractVersion: simulateTransaction failed: ${sim.error}`);
|
|
62
|
+
}
|
|
63
|
+
if (!sim.result?.retval) {
|
|
64
|
+
throw new Error('getContractVersion: grammar_version() returned no value');
|
|
65
|
+
}
|
|
66
|
+
const native = (0, stellar_sdk_1.scValToBigInt)(sim.result.retval);
|
|
67
|
+
if (typeof native !== 'bigint') {
|
|
68
|
+
throw new Error('getContractVersion: grammar_version() did not return an integer');
|
|
69
|
+
}
|
|
70
|
+
return Number(native);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const FOLLOWUP_HINT = 'after this tx confirms, read the rule id via account.get_context_rules_count()-1 (or get the receipt events), then call runInstallPolicy a second time with the interpreter as the target and the rule id in context_rule_ids - OR hand-build the install() call directly with the OZ auth pattern.';
|
|
75
|
+
/** Build the unsigned transaction envelope for `account.add_context_rule(...)`.
|
|
76
|
+
* The output XDR is signed by the wallet, not by us. */
|
|
77
|
+
async function buildInstallPolicyXdr(args) {
|
|
78
|
+
// 1. Pure arg encoding first - fail closed on any limit / shape problem
|
|
79
|
+
// BEFORE we burn a network round-trip on a malformed call.
|
|
80
|
+
const callArgs = (0, build_add_context_rule_ts_1.buildAddContextRuleArgs)({
|
|
81
|
+
contextRuleType: args.rule.contextRuleType,
|
|
82
|
+
name: args.rule.name,
|
|
83
|
+
validUntilLedger: args.rule.validUntilLedger,
|
|
84
|
+
signers: args.rule.signers,
|
|
85
|
+
policies: args.rule.policies.map(adaptPolicyRef),
|
|
86
|
+
}, {
|
|
87
|
+
signers: args.rule.signers,
|
|
88
|
+
policies: args.rule.policies.map(adaptPolicyRef),
|
|
89
|
+
installNonce: args.installNonce,
|
|
90
|
+
encodedPredicate: args.encodedPredicate,
|
|
91
|
+
predicateHash: args.predicateHash,
|
|
92
|
+
...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
|
|
93
|
+
...(args.grammarVersion !== undefined ? { grammarVersion: args.grammarVersion } : {}),
|
|
94
|
+
});
|
|
95
|
+
// 2. Fetch the source sequence, then build the recording transaction with a
|
|
96
|
+
// bare host call. The recording pass assigns the smart-account auth nonce
|
|
97
|
+
// and root invocation needed to construct OZ's AuthPayload.
|
|
98
|
+
const source = await args.rpc.getAccount(args.sourceAccount);
|
|
99
|
+
const hostFunction = stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
|
|
100
|
+
contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
|
|
101
|
+
functionName: 'add_context_rule',
|
|
102
|
+
args: [...callArgs],
|
|
103
|
+
}));
|
|
104
|
+
const makeOperation = (auth = []) => stellar_sdk_1.Operation.invokeHostFunction({ func: hostFunction, auth });
|
|
105
|
+
const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
|
|
106
|
+
const buildTx = (op) => buildUnsignedTx({
|
|
107
|
+
sourceAccount: args.sourceAccount,
|
|
108
|
+
sequence: source.sequenceNumber(),
|
|
109
|
+
fee: baseFee,
|
|
110
|
+
networkPassphrase: args.networkPassphrase,
|
|
111
|
+
op,
|
|
112
|
+
});
|
|
113
|
+
const recordingTx = buildTx(makeOperation());
|
|
114
|
+
// 3. Recording simulation: capture the smart account's nonce and invocation
|
|
115
|
+
// tree. Nothing is signed here.
|
|
116
|
+
const recorded = await args.rpc.simulateTransaction(recordingTx);
|
|
117
|
+
if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
|
|
118
|
+
// Short, stable reason. The full `simulateTransaction` error (which
|
|
119
|
+
// carries host + URL detail) stays in the SDK's own logs - never
|
|
120
|
+
// reflected back into a user-facing message where it would
|
|
121
|
+
// reconnoitre the RPC.
|
|
122
|
+
throw new Error('install_policy: simulateTransaction failed');
|
|
123
|
+
}
|
|
124
|
+
const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
|
|
125
|
+
stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
|
|
126
|
+
args.smartAccount);
|
|
127
|
+
if (!original) {
|
|
128
|
+
throw new Error(`install_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
|
|
129
|
+
}
|
|
130
|
+
// 4. `add_context_rule` is authorised by the deploy-time admin rule (rule 0).
|
|
131
|
+
// The delegated signer uses source-account credentials, so its signature
|
|
132
|
+
// bytes stay empty and the ordinary transaction-envelope signature covers
|
|
133
|
+
// the call when the consumer signs it.
|
|
134
|
+
const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
|
|
135
|
+
(args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
|
|
136
|
+
const contextRuleIds = [0];
|
|
137
|
+
const digest = (0, oz_auth_ts_1.authDigest)((0, oz_auth_ts_1.signaturePayload)(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
|
|
138
|
+
const authEntries = [
|
|
139
|
+
(0, oz_auth_ts_1.accountEntry)(original, validUntilLedger, (0, oz_auth_ts_1.authPayload)([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
|
|
140
|
+
...contextRuleIds.map(() => (0, oz_auth_ts_1.delegatedSignerEntry)(args.smartAccount, digest)),
|
|
141
|
+
];
|
|
142
|
+
// 5. Simulate again with the OZ entries already attached. The SDK preserves
|
|
143
|
+
// existing auth during assembly and adds the simulated Soroban footprint +
|
|
144
|
+
// resource fee, yielding a complete unsigned envelope.
|
|
145
|
+
const txWithAuth = buildTx(makeOperation(authEntries));
|
|
146
|
+
const enforcing = await args.rpc.simulateTransaction(txWithAuth);
|
|
147
|
+
if (stellar_sdk_1.rpc.Api.isSimulationError(enforcing)) {
|
|
148
|
+
throw new Error('install_policy: auth simulateTransaction failed');
|
|
149
|
+
}
|
|
150
|
+
const finalTx = stellar_sdk_1.rpc.assembleTransaction(txWithAuth, enforcing).build();
|
|
151
|
+
// 6. Decode the structured description FROM the final assembled transaction.
|
|
152
|
+
// The human approval binds to the exact bytes the wallet will sign.
|
|
153
|
+
const describes = decodeInstallCallDescribes(finalTx, args.installNonce);
|
|
154
|
+
return {
|
|
155
|
+
unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
|
|
156
|
+
smartAccount: args.smartAccount,
|
|
157
|
+
sourceAccount: args.sourceAccount,
|
|
158
|
+
call: { contract: args.smartAccount, fn: 'add_context_rule' },
|
|
159
|
+
followUp: {
|
|
160
|
+
contract: 'interpreter',
|
|
161
|
+
fn: 'install',
|
|
162
|
+
requiresRuleIdFromCallOne: true,
|
|
163
|
+
hint: FOLLOWUP_HINT,
|
|
164
|
+
},
|
|
165
|
+
describes,
|
|
166
|
+
authNonce: original.credentials().address().nonce().toString(),
|
|
167
|
+
authValidUntilLedger: validUntilLedger,
|
|
168
|
+
rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/** Build an unsigned XDR for `account.remove_context_rule(ruleId)`. The
|
|
172
|
+
* smart account itself handles uninstalling each attached policy (calling
|
|
173
|
+
* `interpreter.uninstall` for the interpreter policy); this builder only
|
|
174
|
+
* emits the account-side removal call.
|
|
175
|
+
*
|
|
176
|
+
* Who may authorise it is the ACCOUNT's decision, and the account's source is
|
|
177
|
+
* not in this repo. The interpreter's own `uninstall` is master-gated, but
|
|
178
|
+
* that is a different entry point from this one, so do not restate it as the
|
|
179
|
+
* rule for this call. What is proven on testnet is that the account's
|
|
180
|
+
* deployer can revoke. This builder does not pre-check the signer: it would
|
|
181
|
+
* be guessing at a contract it cannot read, and the chain is the authority. */
|
|
182
|
+
async function buildRevokePolicyXdr(args) {
|
|
183
|
+
const source = await args.rpc.getAccount(args.sourceAccount);
|
|
184
|
+
const hostFunction = stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
|
|
185
|
+
contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
|
|
186
|
+
functionName: 'remove_context_rule',
|
|
187
|
+
args: [stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId)],
|
|
188
|
+
}));
|
|
189
|
+
const makeOperation = (auth = []) => stellar_sdk_1.Operation.invokeHostFunction({ func: hostFunction, auth });
|
|
190
|
+
const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
|
|
191
|
+
const buildTx = (op) => buildUnsignedTx({
|
|
192
|
+
sourceAccount: args.sourceAccount,
|
|
193
|
+
sequence: source.sequenceNumber(),
|
|
194
|
+
fee: baseFee,
|
|
195
|
+
networkPassphrase: args.networkPassphrase,
|
|
196
|
+
op,
|
|
197
|
+
});
|
|
198
|
+
const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()));
|
|
199
|
+
if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
|
|
200
|
+
// Short, stable reason. The full `simulateTransaction` error (which
|
|
201
|
+
// carries host + URL detail) stays in the SDK's own logs - never
|
|
202
|
+
// reflected back into a user-facing message where it would
|
|
203
|
+
// reconnoitre the RPC.
|
|
204
|
+
throw new Error('revoke_policy: simulateTransaction failed');
|
|
205
|
+
}
|
|
206
|
+
const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
|
|
207
|
+
stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
|
|
208
|
+
args.smartAccount);
|
|
209
|
+
if (!original) {
|
|
210
|
+
throw new Error(`revoke_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
|
|
211
|
+
}
|
|
212
|
+
// Removal is master-only, so the deploy-time admin rule authorises it. The
|
|
213
|
+
// recorded rootInvocation still includes remove_context_rule(ruleId), binding
|
|
214
|
+
// the auth payload to the exact rule being removed. As with install,
|
|
215
|
+
// source-account credentials carry the delegated signer entry and the
|
|
216
|
+
// consumer supplies only the ordinary envelope signature.
|
|
217
|
+
const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
|
|
218
|
+
(args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
|
|
219
|
+
const contextRuleIds = [0];
|
|
220
|
+
const digest = (0, oz_auth_ts_1.authDigest)((0, oz_auth_ts_1.signaturePayload)(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
|
|
221
|
+
const authEntries = [
|
|
222
|
+
(0, oz_auth_ts_1.accountEntry)(original, validUntilLedger, (0, oz_auth_ts_1.authPayload)([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
|
|
223
|
+
...contextRuleIds.map(() => (0, oz_auth_ts_1.delegatedSignerEntry)(args.smartAccount, digest)),
|
|
224
|
+
];
|
|
225
|
+
const txWithAuth = buildTx(makeOperation(authEntries));
|
|
226
|
+
const enforcing = await args.rpc.simulateTransaction(txWithAuth);
|
|
227
|
+
if (stellar_sdk_1.rpc.Api.isSimulationError(enforcing)) {
|
|
228
|
+
throw new Error('revoke_policy: auth simulateTransaction failed');
|
|
229
|
+
}
|
|
230
|
+
const finalTx = stellar_sdk_1.rpc.assembleTransaction(txWithAuth, enforcing).build();
|
|
231
|
+
return {
|
|
232
|
+
unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
|
|
233
|
+
smartAccount: args.smartAccount,
|
|
234
|
+
sourceAccount: args.sourceAccount,
|
|
235
|
+
call: { contract: args.smartAccount, fn: 'remove_context_rule', ruleId: args.ruleId },
|
|
236
|
+
authNonce: original.credentials().address().nonce().toString(),
|
|
237
|
+
authValidUntilLedger: validUntilLedger,
|
|
238
|
+
rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/** ~25 minutes at 5s/ledger. */
|
|
242
|
+
const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 300;
|
|
243
|
+
// ---- internals ----
|
|
244
|
+
/** Adapter: turn the install-policy wire `PolicyRef` shape into the core
|
|
245
|
+
* `PolicyRef` shape `buildAddContextRuleArgs` expects. Keeps the wire
|
|
246
|
+
* schema hand-rolled + flat (the strict union would need a recursive
|
|
247
|
+
* schema) while delegating to the proven encoder for the actual bytes. */
|
|
248
|
+
function adaptPolicyRef(p) {
|
|
249
|
+
if (p.kind === 'interpreter') {
|
|
250
|
+
return {
|
|
251
|
+
kind: 'interpreter',
|
|
252
|
+
interpreterAddress: p.interpreterAddress,
|
|
253
|
+
predicateBlobBase64: p.predicateBlobBase64,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
kind: 'oz_builtin',
|
|
258
|
+
instanceAddress: p.instanceAddress,
|
|
259
|
+
primitive: p.primitive,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/** Build an unsigned Soroban transaction envelope. The `sequence` is
|
|
263
|
+
* whatever `getAccount().sequenceNumber()` returned (a string of digits
|
|
264
|
+
* the SDK accepts). No signing. The returned Transaction is what
|
|
265
|
+
* `simulateTransaction` accepts. */
|
|
266
|
+
function buildUnsignedTx(args) {
|
|
267
|
+
const account = new stellar_sdk_2.Account(args.sourceAccount, args.sequence);
|
|
268
|
+
const tx = new stellar_sdk_1.TransactionBuilder(account, {
|
|
269
|
+
fee: args.fee,
|
|
270
|
+
networkPassphrase: args.networkPassphrase,
|
|
271
|
+
})
|
|
272
|
+
.addOperation(args.op)
|
|
273
|
+
.setTimeout(0)
|
|
274
|
+
.build();
|
|
275
|
+
// `TransactionBuilder.build()` returns a Transaction whose envelope
|
|
276
|
+
// has empty signatures. The wallet re-reads the unsigned XDR, appends
|
|
277
|
+
// its signature, and broadcasts. We do NOT sign here.
|
|
278
|
+
return tx;
|
|
279
|
+
}
|
|
280
|
+
/** Decode the install call's structured fields directly out of the final
|
|
281
|
+
* assembled transaction. The bytes are the source of truth: a human reviewing
|
|
282
|
+
* the install wants to see what the wallet will actually sign, not what we
|
|
283
|
+
* think it will. The decode is deliberately strict - any shape we did not
|
|
284
|
+
* build ourselves throws, since that would mean the XDR was tampered with (or
|
|
285
|
+
* the encoder changed and this descriptor lags).
|
|
286
|
+
*
|
|
287
|
+
* `expectedInstallNonce` is a fallback for the rare case where the
|
|
288
|
+
* install has no interpreter policy (no `install_nonce` to read); the
|
|
289
|
+
* caller already knows it. */
|
|
290
|
+
function decodeInstallCallDescribes(tx, expectedInstallNonce) {
|
|
291
|
+
const operations = tx.toEnvelope().v1().tx().operations();
|
|
292
|
+
if (operations.length !== 1 || !operations[0]) {
|
|
293
|
+
throw new Error(`install_policy: final transaction has ${operations.length} operations, expected 1`);
|
|
294
|
+
}
|
|
295
|
+
const op = operations[0];
|
|
296
|
+
const hostFn = op.body().invokeHostFunctionOp()?.hostFunction();
|
|
297
|
+
if (hostFn?.switch().name !== 'hostFunctionTypeInvokeContract') {
|
|
298
|
+
throw new Error('install_policy: built op is not an invokeHostFunction(invokeContract(...)) call');
|
|
299
|
+
}
|
|
300
|
+
const invokeArgs = hostFn.invokeContract();
|
|
301
|
+
if (!invokeArgs) {
|
|
302
|
+
throw new Error('install_policy: built op has no InvokeContractArgs payload');
|
|
303
|
+
}
|
|
304
|
+
const targetContract = stellar_sdk_1.Address.fromScAddress(invokeArgs.contractAddress()).toString();
|
|
305
|
+
const fnName = invokeArgs.functionName().toString();
|
|
306
|
+
if (fnName !== 'add_context_rule') {
|
|
307
|
+
throw new Error(`install_policy: built op fn name is "${fnName}", expected "add_context_rule"`);
|
|
308
|
+
}
|
|
309
|
+
const scvArgs = invokeArgs.args();
|
|
310
|
+
if (scvArgs.length !== 5) {
|
|
311
|
+
throw new Error(`install_policy: built op has ${scvArgs.length} args, expected 5 (context_type, name, valid_until, signers, policies)`);
|
|
312
|
+
}
|
|
313
|
+
const contextType = scvArgs[0];
|
|
314
|
+
const nameScv = scvArgs[1];
|
|
315
|
+
const validUntilScv = scvArgs[2];
|
|
316
|
+
const signersScv = scvArgs[3];
|
|
317
|
+
const policiesScv = scvArgs[4];
|
|
318
|
+
// The length check above pins these as defined; the local references
|
|
319
|
+
// satisfy noUncheckedIndexedAccess on the accessors below.
|
|
320
|
+
if (!nameScv || !validUntilScv || !signersScv || !policiesScv || !contextType) {
|
|
321
|
+
throw new Error('install_policy: built op args include an undefined slot despite length check');
|
|
322
|
+
}
|
|
323
|
+
// name
|
|
324
|
+
if (nameScv.switch().name !== 'scvString') {
|
|
325
|
+
throw new Error('install_policy: args[1] (name) is not an ScVal::String');
|
|
326
|
+
}
|
|
327
|
+
const ruleName = nameScv.str().toString();
|
|
328
|
+
// valid_until (Option<u32> -> void when absent)
|
|
329
|
+
let validUntilLedger;
|
|
330
|
+
if (validUntilScv.switch().name === 'scvVoid') {
|
|
331
|
+
validUntilLedger = null;
|
|
332
|
+
}
|
|
333
|
+
else if (validUntilScv.switch().name === 'scvU32') {
|
|
334
|
+
validUntilLedger = validUntilScv.u32();
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
throw new Error('install_policy: args[2] (valid_until) is neither void nor u32');
|
|
338
|
+
}
|
|
339
|
+
// signers (Vec<Vec<Symbol, Address[, Bytes]>>)
|
|
340
|
+
if (signersScv.switch().name !== 'scvVec') {
|
|
341
|
+
throw new Error('install_policy: args[3] (signers) is not an ScVal::Vec');
|
|
342
|
+
}
|
|
343
|
+
const signers = [];
|
|
344
|
+
for (const signerScv of signersScv.vec() ?? []) {
|
|
345
|
+
if (signerScv.switch().name !== 'scvVec') {
|
|
346
|
+
throw new Error('install_policy: a signer entry is not an ScVal::Vec');
|
|
347
|
+
}
|
|
348
|
+
const tuple = signerScv.vec() ?? [];
|
|
349
|
+
const tag = tuple[0]?.sym().toString();
|
|
350
|
+
const inner = tuple[1];
|
|
351
|
+
if (tag === 'Delegated') {
|
|
352
|
+
if (!inner || inner.switch().name !== 'scvAddress') {
|
|
353
|
+
throw new Error('install_policy: a Delegated signer is missing its Address');
|
|
354
|
+
}
|
|
355
|
+
signers.push({
|
|
356
|
+
kind: 'delegated',
|
|
357
|
+
address: stellar_sdk_1.Address.fromScAddress(inner.address()).toString(),
|
|
358
|
+
});
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (tag === 'External') {
|
|
362
|
+
if (!inner || inner.switch().name !== 'scvAddress') {
|
|
363
|
+
throw new Error('install_policy: an External signer is missing its verifier Address');
|
|
364
|
+
}
|
|
365
|
+
signers.push({
|
|
366
|
+
kind: 'external',
|
|
367
|
+
verifier: stellar_sdk_1.Address.fromScAddress(inner.address()).toString(),
|
|
368
|
+
});
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
throw new Error(`install_policy: signer tag "${tag ?? '<missing>'}" is not Delegated|External`);
|
|
372
|
+
}
|
|
373
|
+
// policies (Map<Address, Val>). Re-derive an interpreter-vs-OZ primitive
|
|
374
|
+
// classification by inspecting the value's map keys (PolicyInstallParams
|
|
375
|
+
// starts with `grammar_version`/`install_nonce`/`predicate`; OZ primitive
|
|
376
|
+
// params start with `spending_limit`/`threshold`/`period_ledgers`).
|
|
377
|
+
if (policiesScv.switch().name !== 'scvMap') {
|
|
378
|
+
throw new Error('install_policy: args[4] (policies) is not an ScVal::Map');
|
|
379
|
+
}
|
|
380
|
+
const policies = [];
|
|
381
|
+
let observedInstallNonce = null;
|
|
382
|
+
for (const entry of policiesScv.map() ?? []) {
|
|
383
|
+
const key = entry.key();
|
|
384
|
+
if (key.switch().name !== 'scvAddress') {
|
|
385
|
+
throw new Error('install_policy: a policies map entry has a non-Address key');
|
|
386
|
+
}
|
|
387
|
+
const address = stellar_sdk_1.Address.fromScAddress(key.address()).toString();
|
|
388
|
+
const val = entry.val();
|
|
389
|
+
if (val.switch().name !== 'scvMap') {
|
|
390
|
+
throw new Error(`install_policy: policies[${address}] value is not an ScVal::Map (got ${val.switch().name})`);
|
|
391
|
+
}
|
|
392
|
+
const fields = new Map();
|
|
393
|
+
for (const inner of val.map() ?? []) {
|
|
394
|
+
const fk = inner.key();
|
|
395
|
+
if (fk.switch().name !== 'scvSymbol') {
|
|
396
|
+
throw new Error(`install_policy: policies[${address}] field key is not an ScVal::Symbol`);
|
|
397
|
+
}
|
|
398
|
+
fields.set(fk.sym().toString(), inner.val());
|
|
399
|
+
}
|
|
400
|
+
// Interpreter policy fields carry grammar_version/install_nonce/predicate.
|
|
401
|
+
// OZ primitives carry spending_limit/period_ledgers/threshold/signers.
|
|
402
|
+
if (fields.has('predicate') || fields.has('grammar_version') || fields.has('install_nonce')) {
|
|
403
|
+
const installNonceScv = fields.get('install_nonce');
|
|
404
|
+
if (!installNonceScv || installNonceScv.switch().name !== 'scvU32') {
|
|
405
|
+
throw new Error(`install_policy: interpreter policy ${address} is missing a u32 install_nonce`);
|
|
406
|
+
}
|
|
407
|
+
const installNonce = installNonceScv.u32();
|
|
408
|
+
const predicateScv = fields.get('predicate');
|
|
409
|
+
if (!predicateScv || predicateScv.switch().name !== 'scvBytes') {
|
|
410
|
+
throw new Error(`install_policy: interpreter policy ${address} is missing its bytes predicate`);
|
|
411
|
+
}
|
|
412
|
+
const predicateBytes = Buffer.from(predicateScv.bytes());
|
|
413
|
+
const predicateSha256OfEmbeddedBytes = (0, node_crypto_1.createHash)('sha256')
|
|
414
|
+
.update(predicateBytes)
|
|
415
|
+
.digest('hex');
|
|
416
|
+
const predicateHashScv = fields.get('predicate_hash');
|
|
417
|
+
const predicateHash = predicateHashScv && predicateHashScv.switch().name === 'scvBytes'
|
|
418
|
+
? Buffer.from(predicateHashScv.bytes()).toString('hex')
|
|
419
|
+
: '';
|
|
420
|
+
policies.push({
|
|
421
|
+
kind: 'interpreter',
|
|
422
|
+
address,
|
|
423
|
+
installNonce,
|
|
424
|
+
predicateHash,
|
|
425
|
+
predicateSha256OfEmbeddedBytes,
|
|
426
|
+
});
|
|
427
|
+
observedInstallNonce = installNonce;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
// OZ built-in primitive. Distinguish by the parameter shape we
|
|
431
|
+
// emitted; matching one of the three primitives exactly pins the
|
|
432
|
+
// kind we built.
|
|
433
|
+
if (fields.has('spending_limit') && fields.has('period_ledgers')) {
|
|
434
|
+
policies.push({ kind: 'oz_builtin', address, primitive: 'spending_limit' });
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (fields.has('threshold') && fields.has('signer_weights')) {
|
|
438
|
+
policies.push({ kind: 'oz_builtin', address, primitive: 'weighted_threshold' });
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (fields.has('threshold')) {
|
|
442
|
+
policies.push({ kind: 'oz_builtin', address, primitive: 'simple_threshold' });
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
throw new Error(`install_policy: policies[${address}] value has an unknown field set; the encoder may have drifted`);
|
|
446
|
+
}
|
|
447
|
+
// `observedInstallNonce` is the nonce baked into whichever interpreter
|
|
448
|
+
// policy is present; when none, fall back to the caller-supplied value.
|
|
449
|
+
const installNonce = observedInstallNonce ?? expectedInstallNonce;
|
|
450
|
+
return {
|
|
451
|
+
targetContract,
|
|
452
|
+
fnName: 'add_context_rule',
|
|
453
|
+
ruleName,
|
|
454
|
+
validUntilLedger,
|
|
455
|
+
signers,
|
|
456
|
+
policies,
|
|
457
|
+
installNonce,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
// Local re-import to avoid pulling the class from the SDK module path
|
|
461
|
+
// at the top of the file (avoids the unused-import lint).
|
|
462
|
+
const stellar_sdk_2 = require("@stellar/stellar-sdk");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Network } from '../types.ts';
|
|
2
|
+
export interface InterpreterInfo {
|
|
3
|
+
/** Pinned interpreter contract address. */
|
|
4
|
+
pinnedAddress: string;
|
|
5
|
+
/** Pinned grammar version (matches SELF_VERSION in version.rs). */
|
|
6
|
+
pinnedGrammarVersion: number;
|
|
7
|
+
/** Pinned wasm sha256 (hex). */
|
|
8
|
+
pinnedWasmHash: string;
|
|
9
|
+
/** Network this pin applies to (the address + hash are network-scoped). */
|
|
10
|
+
network: Network;
|
|
11
|
+
/** Present only when the caller supplied a live `deployedGrammarVersion`. */
|
|
12
|
+
deployedGrammarVersion?: number;
|
|
13
|
+
/** True when `deployedGrammarVersion` matches `pinnedGrammarVersion`.
|
|
14
|
+
* Absent when no live verification was performed. */
|
|
15
|
+
liveMatchesPin?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** Build the interpreter-info response. When `deployedGrammarVersion` is
|
|
18
|
+
* supplied (after a live RPC `grammar_version()` call by the run layer),
|
|
19
|
+
* compares it to the pin and sets `liveMatchesPin`. When absent, returns
|
|
20
|
+
* the pin alone. */
|
|
21
|
+
export declare function getInterpreterInfo(args: {
|
|
22
|
+
pinnedAddress: string;
|
|
23
|
+
pinnedGrammarVersion: number;
|
|
24
|
+
pinnedWasmHash: string;
|
|
25
|
+
network: Network;
|
|
26
|
+
/** When supplied, the u32 returned by the live contract's
|
|
27
|
+
* `grammar_version()` RPC call. */
|
|
28
|
+
deployedGrammarVersion?: number;
|
|
29
|
+
}): InterpreterInfo;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// src/install/get-interpreter-info.ts - read-only fingerprint lookup for
|
|
3
|
+
// the interpreter contract.
|
|
4
|
+
//
|
|
5
|
+
// Returns the pinned deployment fingerprint + (optionally) compares a
|
|
6
|
+
// caller-supplied live `grammar_version` against the pin. No fabricated
|
|
7
|
+
// audit field; a real deployed-contract check is worth more than a fake
|
|
8
|
+
// reference.
|
|
9
|
+
//
|
|
10
|
+
// Per design decision 5: phase-04's "audit #44" is aspirational and has no
|
|
11
|
+
// source-of-truth in the repo. Returning a fabricated audit id would be a
|
|
12
|
+
// lie on a security surface. The honest outputs are:
|
|
13
|
+
// - the pinned address (DEPLOYMENTS.md)
|
|
14
|
+
// - the pinned grammar version (SELF_VERSION in version.rs)
|
|
15
|
+
// - the pinned wasm sha256 (DEPLOYMENTS.md)
|
|
16
|
+
// - an OPTIONAL `deployedGrammarVersion` returned by a live `grammar_version()`
|
|
17
|
+
// RPC call, with a `liveMatchesPin` boolean the caller can dispatch on. A
|
|
18
|
+
// mismatch means the deployed wasm is NOT the pinned artifact - the caller
|
|
19
|
+
// should refuse to install until they redeploy.
|
|
20
|
+
//
|
|
21
|
+
// The RPC plumbing lives in the run layer (`run/index.ts`); this module
|
|
22
|
+
// stays pure so it is testable without a network.
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.getInterpreterInfo = getInterpreterInfo;
|
|
25
|
+
/** Build the interpreter-info response. When `deployedGrammarVersion` is
|
|
26
|
+
* supplied (after a live RPC `grammar_version()` call by the run layer),
|
|
27
|
+
* compares it to the pin and sets `liveMatchesPin`. When absent, returns
|
|
28
|
+
* the pin alone. */
|
|
29
|
+
function getInterpreterInfo(args) {
|
|
30
|
+
const info = {
|
|
31
|
+
pinnedAddress: args.pinnedAddress,
|
|
32
|
+
pinnedGrammarVersion: args.pinnedGrammarVersion,
|
|
33
|
+
pinnedWasmHash: args.pinnedWasmHash,
|
|
34
|
+
network: args.network,
|
|
35
|
+
};
|
|
36
|
+
if (typeof args.deployedGrammarVersion === 'number') {
|
|
37
|
+
return {
|
|
38
|
+
...info,
|
|
39
|
+
deployedGrammarVersion: args.deployedGrammarVersion,
|
|
40
|
+
liveMatchesPin: args.deployedGrammarVersion === args.pinnedGrammarVersion,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return info;
|
|
44
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { xdr } from '@stellar/stellar-sdk';
|
|
2
|
+
/** `Signer::Delegated(addr)`. */
|
|
3
|
+
export declare const delegatedSigner: (a: string) => xdr.ScVal;
|
|
4
|
+
/** The standard Soroban authorization preimage hash for one entry. */
|
|
5
|
+
export declare function signaturePayload(networkPassphrase: string, nonce: xdr.Int64, signatureExpirationLedger: number, invocation: xdr.SorobanAuthorizedInvocation): Buffer;
|
|
6
|
+
/**
|
|
7
|
+
* `sha256(signature_payload || xdr(context_rule_ids))`.
|
|
8
|
+
*
|
|
9
|
+
* OZ binds the selected rule ids into the digest so a signature for one rule
|
|
10
|
+
* cannot be replayed against another.
|
|
11
|
+
*/
|
|
12
|
+
export declare function authDigest(payload: Buffer, contextRuleIds: number[]): Buffer;
|
|
13
|
+
/** `AuthPayload { signers, context_rule_ids }` - the account's "signature". */
|
|
14
|
+
export declare function authPayload(signerAddresses: string[], contextRuleIds: number[], signatureFor: (addr: string) => Buffer): xdr.ScVal;
|
|
15
|
+
/**
|
|
16
|
+
* The nested entry a `Delegated` signer needs.
|
|
17
|
+
*
|
|
18
|
+
* `require_auth_for_args` authorizes the CURRENT frame, which while
|
|
19
|
+
* `__check_auth` is running is the account contract executing `__check_auth`,
|
|
20
|
+
* with the digest as its single argument.
|
|
21
|
+
*
|
|
22
|
+
* The signer is the transaction source here, so source-account credentials
|
|
23
|
+
* carry it and no separate signature is required.
|
|
24
|
+
*/
|
|
25
|
+
export declare function delegatedSignerEntry(accountId: string, digest: Buffer): xdr.SorobanAuthorizationEntry;
|
|
26
|
+
/** Rebuild the account's entry with the AuthPayload in the signature slot. */
|
|
27
|
+
export declare function accountEntry(original: xdr.SorobanAuthorizationEntry, signatureExpirationLedger: number, payload: xdr.ScVal): xdr.SorobanAuthorizationEntry;
|