mishmar 0.0.0-stage → 0.3.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/LICENSE +174 -0
- package/README.md +89 -2
- package/dist/agentkey.d.ts +63 -0
- package/dist/agentkey.js +118 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +4 -0
- package/dist/canon.d.ts +14 -0
- package/dist/canon.js +64 -0
- package/dist/client.d.ts +119 -0
- package/dist/client.js +188 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/proposal.d.ts +108 -0
- package/dist/proposal.js +159 -0
- package/dist/signer.d.ts +148 -0
- package/dist/signer.js +416 -0
- package/dist/time.d.ts +5 -0
- package/dist/time.js +17 -0
- package/dist/wrapper.d.ts +17 -0
- package/dist/wrapper.js +58 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mishmar (TypeScript)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Mishmar](https://mishmar.io) is a risk management layer for trading bots
|
|
4
|
+
and AI agents: every order is checked against your limits before it reaches
|
|
5
|
+
the exchange, large orders wait for your approval, and no key can trade
|
|
6
|
+
alone.
|
|
7
|
+
|
|
8
|
+
This is the TypeScript client: build a proposal, sign it with the agent's
|
|
9
|
+
key, send it to the engine, read the decision. No runtime dependencies; Node
|
|
10
|
+
20 or later.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install mishmar
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The package also puts `mishmar` on the path, so `npx -y mishmar mcp` runs
|
|
17
|
+
the MCP server and `npx -y mishmar signer run` the signer without the CLI
|
|
18
|
+
installed: the command runs the binary found through `MISHMAR_BIN`, the
|
|
19
|
+
PATH or `~/.mishmar/bin`, and when there is none fetches the pinned release
|
|
20
|
+
(v0.2.2) into `~/.mishmar/bin` first, checked against the release's
|
|
21
|
+
checksums.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { AgentKey, Client } from "mishmar";
|
|
25
|
+
|
|
26
|
+
const key = AgentKey.parse("msk_…"); // shown once when the engine issued the key
|
|
27
|
+
const client = new Client("http://localhost:8080/v1", key, "key_…");
|
|
28
|
+
|
|
29
|
+
const decision = await client.propose({
|
|
30
|
+
tradingAccountId: "ta_…", symbol: "BTC", side: "buy", size: "0.25",
|
|
31
|
+
orderType: "market", validForMs: 5 * 60_000,
|
|
32
|
+
});
|
|
33
|
+
console.log(decision.verdict); // allow | require_approval | block
|
|
34
|
+
|
|
35
|
+
// Pull a resting order this agent placed through Mishmar: a cancel names the
|
|
36
|
+
// order by the clientOrderId its decision carries, and has no side or size.
|
|
37
|
+
const { clientOrderId } = decision.proposal as { clientOrderId: string };
|
|
38
|
+
await client.propose({
|
|
39
|
+
tradingAccountId: "ta_…", symbol: "BTC", kind: "cancel",
|
|
40
|
+
targetClientOrderId: clientOrderId,
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Sizes, prices and leverage are decimal **strings** and are signed exactly as
|
|
45
|
+
written: `"0.5"` and `"0.50"` are the same quantity but different signatures.
|
|
46
|
+
Never pass a number.
|
|
47
|
+
|
|
48
|
+
A call the engine did nothing with goes again by itself: `503 unavailable`
|
|
49
|
+
while the engine restarts and `429 rate_limited` (after its `Retry-After`),
|
|
50
|
+
for up to 45 s, then the last answer is thrown as `EngineError`. Nothing else
|
|
51
|
+
is retried. `new Client(url, key, keyId, { retries: false })` turns that off;
|
|
52
|
+
`{ retries: { budgetMs: 90_000 } }` tunes it.
|
|
53
|
+
|
|
54
|
+
Run the tests, which include the cross-language vectors in `../spec/vectors`:
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
npm install
|
|
58
|
+
npm test
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## The signer as a child process
|
|
62
|
+
|
|
63
|
+
With the `mishmar` binary installed (or fetched with `downloadBinary`),
|
|
64
|
+
`Signer` runs it as a child process and the bot holds no secret: the child
|
|
65
|
+
has the agent's key and shares, signs each proposal, and sends it one-shot
|
|
66
|
+
where it can. Reads go through the child too.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { Signer } from "mishmar";
|
|
70
|
+
|
|
71
|
+
const s = await new Signer().start(); // ~/.mishmar/agent.json
|
|
72
|
+
try {
|
|
73
|
+
let d = await s.order({ tradingAccountId: "ta_…", symbol: "BTC", side: "buy", size: "0.001", price: "79500" });
|
|
74
|
+
if (d.verdict === "require_approval") d = await s.wait(d.id);
|
|
75
|
+
const { clientOrderId } = d.proposal as { clientOrderId: string };
|
|
76
|
+
await s.cancel("ta_…", "BTC", clientOrderId);
|
|
77
|
+
} finally {
|
|
78
|
+
await s.stop();
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The child stops when this process ends, however it ends. To share one signer
|
|
83
|
+
among several processes, or keep it connected across restarts, run it on its
|
|
84
|
+
own (`mishmar signer run --local unix:/run/mishmar/signer.sock`) and attach
|
|
85
|
+
with `await Signer.connect("unix:/run/mishmar/signer.sock")`; `stop()` then
|
|
86
|
+
leaves it running. One signer runs per config, so a second `Signer` on a
|
|
87
|
+
config in use fails and names the process that holds it.
|
|
88
|
+
|
|
89
|
+
The guides at [docs.mishmar.io](https://docs.mishmar.io) set up the agent,
|
|
90
|
+
its trading keys and the signer.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent's identity: an Ed25519 key whose public half the engine stores.
|
|
3
|
+
*
|
|
4
|
+
* The engine shows the secret once, as `msk_<prefix>_<seed>`: a label, then
|
|
5
|
+
* the 32-byte seed in base64url without padding. The key id (`key_…`) is
|
|
6
|
+
* separate and public.
|
|
7
|
+
*
|
|
8
|
+
* The key signs two things: proposals (proposal.ts) and, under the
|
|
9
|
+
* contract's agentAuth scheme, every other agent-facing request: four headers
|
|
10
|
+
* carry the key id, the time, a nonce and an Ed25519 signature over the
|
|
11
|
+
* canonical JSON of `{bodySha256, keyId, method, nonce, path, query,
|
|
12
|
+
* signedAt}`. The bytes are pinned in spec/vectors/agent-request-signing.json.
|
|
13
|
+
*/
|
|
14
|
+
export declare const HEADER_KEY_ID = "X-Mishmar-Key-Id";
|
|
15
|
+
export declare const HEADER_SIGNED_AT = "X-Mishmar-Signed-At";
|
|
16
|
+
export declare const HEADER_NONCE = "X-Mishmar-Nonce";
|
|
17
|
+
export declare const HEADER_SIGNATURE = "X-Mishmar-Signature";
|
|
18
|
+
/** A fresh nonce: 16 random bytes, hex. */
|
|
19
|
+
export declare function newNonce(): string;
|
|
20
|
+
/** One HTTP request as the agentAuth scheme sees it. */
|
|
21
|
+
export interface RequestToSign {
|
|
22
|
+
/** In any case; signed upper case. */
|
|
23
|
+
method: string;
|
|
24
|
+
/** Without the server prefix: "/agent/decisions", not "/v1/agent/decisions". */
|
|
25
|
+
path: string;
|
|
26
|
+
/** The raw query string without the "?"; empty or absent when none. */
|
|
27
|
+
query?: string;
|
|
28
|
+
/** The request body; absent when none. */
|
|
29
|
+
body?: Uint8Array | string;
|
|
30
|
+
keyId: string;
|
|
31
|
+
nonce: string;
|
|
32
|
+
/** Exactly as sent in X-Mishmar-Signed-At. */
|
|
33
|
+
signedAt: string;
|
|
34
|
+
}
|
|
35
|
+
/** What the agent signs for a request. */
|
|
36
|
+
export declare function requestSigningBytes(r: RequestToSign): Uint8Array;
|
|
37
|
+
/** The agent's private key. */
|
|
38
|
+
export declare class AgentKey {
|
|
39
|
+
#private;
|
|
40
|
+
private constructor();
|
|
41
|
+
/** Read the secret the engine showed when the key was issued. */
|
|
42
|
+
static parse(secret: string): AgentKey;
|
|
43
|
+
static fromSeed(seed: Uint8Array): AgentKey;
|
|
44
|
+
/** A fresh key, for tests and tools; the engine issues the real ones. */
|
|
45
|
+
static generate(): AgentKey;
|
|
46
|
+
/** The base64 (standard, padded) Ed25519 signature of message. */
|
|
47
|
+
sign(message: Uint8Array): string;
|
|
48
|
+
/** The four agentAuth headers for a request; the nonce and the time are made here when not given. */
|
|
49
|
+
signRequest(r: Omit<RequestToSign, "nonce" | "signedAt"> & {
|
|
50
|
+
nonce?: string;
|
|
51
|
+
signedAt?: Date;
|
|
52
|
+
}): Record<string, string>;
|
|
53
|
+
/** The public half, raw 32 bytes. */
|
|
54
|
+
get publicKey(): Uint8Array;
|
|
55
|
+
/** The public half as the API stores and returns it. */
|
|
56
|
+
get publicKeyB64(): string;
|
|
57
|
+
}
|
|
58
|
+
/** Render a seed the way the engine shows it, with the given prefix. */
|
|
59
|
+
export declare function secret(prefix: string, seed: Uint8Array): string;
|
|
60
|
+
/** Check a base64 signature over message with a public key in the API's form. */
|
|
61
|
+
export declare function verify(publicKeyB64: string, message: Uint8Array, signatureB64: string): boolean;
|
|
62
|
+
/** The engine's side of agentAuth. Freshness and nonce replay are the caller's checks. */
|
|
63
|
+
export declare function verifyRequest(publicKeyB64: string, r: RequestToSign, signatureB64: string): boolean;
|
package/dist/agentkey.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent's identity: an Ed25519 key whose public half the engine stores.
|
|
3
|
+
*
|
|
4
|
+
* The engine shows the secret once, as `msk_<prefix>_<seed>`: a label, then
|
|
5
|
+
* the 32-byte seed in base64url without padding. The key id (`key_…`) is
|
|
6
|
+
* separate and public.
|
|
7
|
+
*
|
|
8
|
+
* The key signs two things: proposals (proposal.ts) and, under the
|
|
9
|
+
* contract's agentAuth scheme, every other agent-facing request: four headers
|
|
10
|
+
* carry the key id, the time, a nonce and an Ed25519 signature over the
|
|
11
|
+
* canonical JSON of `{bodySha256, keyId, method, nonce, path, query,
|
|
12
|
+
* signedAt}`. The bytes are pinned in spec/vectors/agent-request-signing.json.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as edSign, verify as edVerify } from "node:crypto";
|
|
15
|
+
import { canonicalBytes } from "./canon.js";
|
|
16
|
+
import { rfc3339 } from "./time.js";
|
|
17
|
+
const SEED_SIZE = 32;
|
|
18
|
+
// DER wrappers for a raw Ed25519 seed and public key, so node:crypto can load them.
|
|
19
|
+
const PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
20
|
+
const SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
|
|
21
|
+
export const HEADER_KEY_ID = "X-Mishmar-Key-Id";
|
|
22
|
+
export const HEADER_SIGNED_AT = "X-Mishmar-Signed-At";
|
|
23
|
+
export const HEADER_NONCE = "X-Mishmar-Nonce";
|
|
24
|
+
export const HEADER_SIGNATURE = "X-Mishmar-Signature";
|
|
25
|
+
/** A fresh nonce: 16 random bytes, hex. */
|
|
26
|
+
export function newNonce() {
|
|
27
|
+
return randomBytes(16).toString("hex");
|
|
28
|
+
}
|
|
29
|
+
/** What the agent signs for a request. */
|
|
30
|
+
export function requestSigningBytes(r) {
|
|
31
|
+
const fields = {
|
|
32
|
+
keyId: r.keyId,
|
|
33
|
+
method: r.method.toUpperCase(),
|
|
34
|
+
nonce: r.nonce,
|
|
35
|
+
path: r.path,
|
|
36
|
+
signedAt: r.signedAt,
|
|
37
|
+
};
|
|
38
|
+
if (r.query)
|
|
39
|
+
fields.query = r.query;
|
|
40
|
+
const body = typeof r.body === "string" ? Buffer.from(r.body, "utf8") : r.body;
|
|
41
|
+
if (body && body.length > 0)
|
|
42
|
+
fields.bodySha256 = createHash("sha256").update(body).digest("hex");
|
|
43
|
+
return canonicalBytes(fields);
|
|
44
|
+
}
|
|
45
|
+
/** The agent's private key. */
|
|
46
|
+
export class AgentKey {
|
|
47
|
+
#key;
|
|
48
|
+
constructor(key) {
|
|
49
|
+
this.#key = key;
|
|
50
|
+
}
|
|
51
|
+
/** Read the secret the engine showed when the key was issued. */
|
|
52
|
+
static parse(secret) {
|
|
53
|
+
// msk_<prefix>_<seed>: the seed is base64url and may itself contain '_',
|
|
54
|
+
// so split on the first two underscores only.
|
|
55
|
+
const s = secret.trim();
|
|
56
|
+
const first = s.indexOf("_");
|
|
57
|
+
const second = first < 0 ? -1 : s.indexOf("_", first + 1);
|
|
58
|
+
if (first < 0 || second < 0 || s.slice(0, first) !== "msk") {
|
|
59
|
+
throw new Error("malformed agent secret: expected msk_<prefix>_<seed>");
|
|
60
|
+
}
|
|
61
|
+
const seed = Buffer.from(s.slice(second + 1), "base64url");
|
|
62
|
+
if (seed.length !== SEED_SIZE || seed.toString("base64url") !== s.slice(second + 1)) {
|
|
63
|
+
throw new Error("malformed agent secret: the seed is not 32 base64url bytes");
|
|
64
|
+
}
|
|
65
|
+
return AgentKey.fromSeed(seed);
|
|
66
|
+
}
|
|
67
|
+
static fromSeed(seed) {
|
|
68
|
+
if (seed.length !== SEED_SIZE)
|
|
69
|
+
throw new Error("an Ed25519 seed is 32 bytes");
|
|
70
|
+
const der = Buffer.concat([PKCS8_PREFIX, Buffer.from(seed)]);
|
|
71
|
+
return new AgentKey(createPrivateKey({ key: der, format: "der", type: "pkcs8" }));
|
|
72
|
+
}
|
|
73
|
+
/** A fresh key, for tests and tools; the engine issues the real ones. */
|
|
74
|
+
static generate() {
|
|
75
|
+
return AgentKey.fromSeed(randomBytes(SEED_SIZE));
|
|
76
|
+
}
|
|
77
|
+
/** The base64 (standard, padded) Ed25519 signature of message. */
|
|
78
|
+
sign(message) {
|
|
79
|
+
return edSign(null, message, this.#key).toString("base64");
|
|
80
|
+
}
|
|
81
|
+
/** The four agentAuth headers for a request; the nonce and the time are made here when not given. */
|
|
82
|
+
signRequest(r) {
|
|
83
|
+
const nonce = r.nonce ?? newNonce();
|
|
84
|
+
const signedAt = rfc3339(r.signedAt ?? new Date());
|
|
85
|
+
const signature = this.sign(requestSigningBytes({ ...r, nonce, signedAt }));
|
|
86
|
+
return { [HEADER_KEY_ID]: r.keyId, [HEADER_SIGNED_AT]: signedAt, [HEADER_NONCE]: nonce, [HEADER_SIGNATURE]: signature };
|
|
87
|
+
}
|
|
88
|
+
/** The public half, raw 32 bytes. */
|
|
89
|
+
get publicKey() {
|
|
90
|
+
const spki = createPublicKey(this.#key).export({ format: "der", type: "spki" });
|
|
91
|
+
return new Uint8Array(spki.subarray(spki.length - SEED_SIZE));
|
|
92
|
+
}
|
|
93
|
+
/** The public half as the API stores and returns it. */
|
|
94
|
+
get publicKeyB64() {
|
|
95
|
+
return Buffer.from(this.publicKey).toString("base64");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Render a seed the way the engine shows it, with the given prefix. */
|
|
99
|
+
export function secret(prefix, seed) {
|
|
100
|
+
return prefix + "_" + Buffer.from(seed).toString("base64url");
|
|
101
|
+
}
|
|
102
|
+
/** Check a base64 signature over message with a public key in the API's form. */
|
|
103
|
+
export function verify(publicKeyB64, message, signatureB64) {
|
|
104
|
+
try {
|
|
105
|
+
const raw = Buffer.from(publicKeyB64, "base64");
|
|
106
|
+
if (raw.length !== SEED_SIZE)
|
|
107
|
+
return false;
|
|
108
|
+
const key = createPublicKey({ key: Buffer.concat([SPKI_PREFIX, raw]), format: "der", type: "spki" });
|
|
109
|
+
return edVerify(null, message, key, Buffer.from(signatureB64, "base64"));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** The engine's side of agentAuth. Freshness and nonce replay are the caller's checks. */
|
|
116
|
+
export function verifyRequest(publicKeyB64, r, signatureB64) {
|
|
117
|
+
return verify(publicKeyB64, requestSigningBytes(r), signatureB64);
|
|
118
|
+
}
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
package/dist/canon.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical JSON: the bytes an agent signs and the engine verifies.
|
|
3
|
+
*
|
|
4
|
+
* The rules match Go's encoding/json, which the engine uses (see canon/ in
|
|
5
|
+
* the repo root and spec/vectors): one object, keys sorted by code point, no
|
|
6
|
+
* whitespace, keys whose value is null or undefined left out at every depth,
|
|
7
|
+
* strings with Go's escapes. JSON.stringify agrees on everything but the
|
|
8
|
+
* HTML-safe escapes, which are added here. Numbers never appear in what
|
|
9
|
+
* Mishmar signs, so they are refused rather than formatted differently.
|
|
10
|
+
*/
|
|
11
|
+
/** The canonical encoding of value, as a string (UTF-8 it before signing). */
|
|
12
|
+
export declare function canonicalJson(value: unknown): string;
|
|
13
|
+
/** The canonical encoding of value as the bytes to sign. */
|
|
14
|
+
export declare function canonicalBytes(value: unknown): Uint8Array;
|
package/dist/canon.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical JSON: the bytes an agent signs and the engine verifies.
|
|
3
|
+
*
|
|
4
|
+
* The rules match Go's encoding/json, which the engine uses (see canon/ in
|
|
5
|
+
* the repo root and spec/vectors): one object, keys sorted by code point, no
|
|
6
|
+
* whitespace, keys whose value is null or undefined left out at every depth,
|
|
7
|
+
* strings with Go's escapes. JSON.stringify agrees on everything but the
|
|
8
|
+
* HTML-safe escapes, which are added here. Numbers never appear in what
|
|
9
|
+
* Mishmar signs, so they are refused rather than formatted differently.
|
|
10
|
+
*/
|
|
11
|
+
const GO_ESCAPES = [
|
|
12
|
+
[/</g, "\\u003c"],
|
|
13
|
+
[/>/g, "\\u003e"],
|
|
14
|
+
[/&/g, "\\u0026"],
|
|
15
|
+
// Built from char codes: a literal U+2028/9 in a regex is a line break to JavaScript.
|
|
16
|
+
[new RegExp(String.fromCharCode(0x2028), "g"), "\\u2028"],
|
|
17
|
+
[new RegExp(String.fromCharCode(0x2029), "g"), "\\u2029"],
|
|
18
|
+
];
|
|
19
|
+
function quote(s) {
|
|
20
|
+
let out = JSON.stringify(s);
|
|
21
|
+
for (const [re, esc] of GO_ESCAPES)
|
|
22
|
+
out = out.replace(re, esc);
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** Go sorts keys as bytes, which for UTF-8 is code-point order; JS's default sort is UTF-16 order. */
|
|
26
|
+
function byCodePoint(a, b) {
|
|
27
|
+
const x = Array.from(a, (c) => c.codePointAt(0) ?? 0);
|
|
28
|
+
const y = Array.from(b, (c) => c.codePointAt(0) ?? 0);
|
|
29
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
30
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
31
|
+
if (d !== 0)
|
|
32
|
+
return d;
|
|
33
|
+
}
|
|
34
|
+
return x.length - y.length;
|
|
35
|
+
}
|
|
36
|
+
function encode(v) {
|
|
37
|
+
if (v === null || v === undefined)
|
|
38
|
+
return "null";
|
|
39
|
+
if (typeof v === "string")
|
|
40
|
+
return quote(v);
|
|
41
|
+
if (typeof v === "boolean")
|
|
42
|
+
return v ? "true" : "false";
|
|
43
|
+
if (typeof v === "number" || typeof v === "bigint") {
|
|
44
|
+
throw new TypeError(`canonicalJson: numbers are not signed by Mishmar; send ${String(v)} as a decimal string`);
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(v))
|
|
47
|
+
return "[" + v.map(encode).join(",") + "]";
|
|
48
|
+
if (typeof v === "object") {
|
|
49
|
+
const o = v;
|
|
50
|
+
const keys = Object.keys(o)
|
|
51
|
+
.filter((k) => o[k] !== null && o[k] !== undefined)
|
|
52
|
+
.sort(byCodePoint);
|
|
53
|
+
return "{" + keys.map((k) => quote(k) + ":" + encode(o[k])).join(",") + "}";
|
|
54
|
+
}
|
|
55
|
+
throw new TypeError(`canonicalJson: cannot encode a ${typeof v}`);
|
|
56
|
+
}
|
|
57
|
+
/** The canonical encoding of value, as a string (UTF-8 it before signing). */
|
|
58
|
+
export function canonicalJson(value) {
|
|
59
|
+
return encode(value);
|
|
60
|
+
}
|
|
61
|
+
/** The canonical encoding of value as the bytes to sign. */
|
|
62
|
+
export function canonicalBytes(value) {
|
|
63
|
+
return new TextEncoder().encode(encode(value));
|
|
64
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small client for the engine, on fetch.
|
|
3
|
+
*
|
|
4
|
+
* Proposals go to POST /proposals with the signature in the body. Everything
|
|
5
|
+
* else an agent may call (its own decisions, approvals, positions, PnL,
|
|
6
|
+
* trading accounts, and the signer channel) is under /agent and signed with the
|
|
7
|
+
* agentAuth headers, so a bot can function without an operator token and
|
|
8
|
+
* cannot act on the account.
|
|
9
|
+
*/
|
|
10
|
+
import type { AgentKey } from "./agentkey.ts";
|
|
11
|
+
import type { Proposal } from "./proposal.ts";
|
|
12
|
+
/** A decision as the engine returns it; the contract (spec/openapi.yaml) has the full shape. */
|
|
13
|
+
export type Decision = {
|
|
14
|
+
id: string;
|
|
15
|
+
verdict: "allow" | "require_approval" | "block";
|
|
16
|
+
approval?: {
|
|
17
|
+
status?: string;
|
|
18
|
+
} & Record<string, unknown>;
|
|
19
|
+
} & Record<string, unknown>;
|
|
20
|
+
/** A page of decisions. */
|
|
21
|
+
export type DecisionPage = {
|
|
22
|
+
items: Decision[];
|
|
23
|
+
nextCursor?: string | null;
|
|
24
|
+
} & Record<string, unknown>;
|
|
25
|
+
/** A request the agent's signer must answer (SignRequest in the contract). */
|
|
26
|
+
export type SignRequest = {
|
|
27
|
+
id: string;
|
|
28
|
+
scheme: string;
|
|
29
|
+
} & Record<string, unknown>;
|
|
30
|
+
/** The signer's answer (SignerAnswer in the contract). */
|
|
31
|
+
export type SignerAnswer = {
|
|
32
|
+
kind: "share" | "signature" | "venue_response" | "refusal";
|
|
33
|
+
} & Record<string, unknown>;
|
|
34
|
+
/** The engine answered with an error: the HTTP status and the code and message from its body. */
|
|
35
|
+
export declare class EngineError extends Error {
|
|
36
|
+
readonly status: number;
|
|
37
|
+
readonly code: string;
|
|
38
|
+
/** The `Retry-After` header of a 429, when the engine sent one. */
|
|
39
|
+
readonly retryAfter?: string;
|
|
40
|
+
constructor(status: number, code: string, message: string, retryAfter?: string);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* How a call the engine did nothing with goes again: 503 `unavailable` while
|
|
44
|
+
* the engine restarts (its drain is 28 s) and 429 `rate_limited`. The same
|
|
45
|
+
* request is sent again after the seconds in `Retry-After` when the engine
|
|
46
|
+
* names them, otherwise after a wait that doubles from `minWaitMs` to
|
|
47
|
+
* `maxWaitMs` with jitter, until `budgetMs` have passed since the first
|
|
48
|
+
* attempt; then the last answer is thrown. Nothing else is retried: a 413
|
|
49
|
+
* `too_large` would come back the same, and any other answer means the
|
|
50
|
+
* request was taken. The defaults cover a restart.
|
|
51
|
+
*/
|
|
52
|
+
export interface Retries {
|
|
53
|
+
budgetMs?: number;
|
|
54
|
+
minWaitMs?: number;
|
|
55
|
+
maxWaitMs?: number;
|
|
56
|
+
}
|
|
57
|
+
export declare const DEFAULT_RETRIES: Required<Retries>;
|
|
58
|
+
export interface ClientOptions {
|
|
59
|
+
timeoutMs?: number;
|
|
60
|
+
/** Retries of a call the engine did nothing with; on by default, `false` turns them off. */
|
|
61
|
+
retries?: Retries | false;
|
|
62
|
+
/** For tests: a fetch to use instead of the global one. */
|
|
63
|
+
fetch?: typeof fetch;
|
|
64
|
+
/** For tests: how to wait between attempts instead of a timer. */
|
|
65
|
+
sleep?: (ms: number) => Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Milliseconds to wait before attempt `attempt + 1` (from 0) after an answer
|
|
69
|
+
* with the status and Retry-After header, `elapsedMs` after the first attempt
|
|
70
|
+
* began; `undefined` means stop and throw the answer.
|
|
71
|
+
*/
|
|
72
|
+
export declare function retryWait(retries: Retries, attempt: number, status: number, retryAfter: string | null, elapsedMs: number): number | undefined;
|
|
73
|
+
/**
|
|
74
|
+
* Talks to one engine as one agent. The trading key's share lives in the
|
|
75
|
+
* agent's signer, never here: this client proposes, reads, and relays the
|
|
76
|
+
* signer channel.
|
|
77
|
+
*/
|
|
78
|
+
export declare class Client {
|
|
79
|
+
#private;
|
|
80
|
+
readonly engineUrl: string;
|
|
81
|
+
readonly agentKey: AgentKey;
|
|
82
|
+
readonly keyId: string;
|
|
83
|
+
constructor(engineUrl: string, agentKey: AgentKey, keyId: string, options?: ClientOptions);
|
|
84
|
+
/** Sign the proposal with the agent's key (unless already signed) and submit it. */
|
|
85
|
+
propose(proposal: Proposal): Promise<Decision>;
|
|
86
|
+
/** A page of this agent's decisions, newest first. */
|
|
87
|
+
decisions(query?: {
|
|
88
|
+
tradingAccountId?: string;
|
|
89
|
+
verdict?: string;
|
|
90
|
+
from?: string;
|
|
91
|
+
to?: string;
|
|
92
|
+
cursor?: string;
|
|
93
|
+
limit?: number;
|
|
94
|
+
}): Promise<DecisionPage>;
|
|
95
|
+
decision(decisionId: string): Promise<Decision>;
|
|
96
|
+
approvals(status?: string): Promise<Record<string, unknown>[]>;
|
|
97
|
+
positions(): Promise<Record<string, unknown>[]>;
|
|
98
|
+
/** Daily PnL of this agent; `from` and `to` are dates (YYYY-MM-DD). */
|
|
99
|
+
pnl(query?: {
|
|
100
|
+
from?: string;
|
|
101
|
+
to?: string;
|
|
102
|
+
}): Promise<Record<string, unknown>>;
|
|
103
|
+
tradingAccount(tradingAccountId: string): Promise<Record<string, unknown>>;
|
|
104
|
+
/** Poll a decision until it no longer waits for a person, or until timeoutMs; returns the last read. */
|
|
105
|
+
/** What the trading account's venue accepts per symbol (tick, step, minimums), as the engine last read it. */
|
|
106
|
+
venueRules(tradingAccountId: string, symbol?: string): Promise<Record<string, unknown>>;
|
|
107
|
+
wait(decisionId: string, { timeoutMs, intervalMs }?: {
|
|
108
|
+
timeoutMs?: number | undefined;
|
|
109
|
+
intervalMs?: number | undefined;
|
|
110
|
+
}): Promise<Decision>;
|
|
111
|
+
/** Wait up to waitSeconds for requests this agent's signer must sign. */
|
|
112
|
+
signerPoll(waitSeconds?: number): Promise<SignRequest[]>;
|
|
113
|
+
/** Answer a sign request: a share, a signature, a venue response or a refusal. */
|
|
114
|
+
/** Take up to `count` of the engine's single-use FROST commitments for one-shot signing with a venue key (CommitmentBatch). */
|
|
115
|
+
signerCommitments(venueKeyId: string, count?: number): Promise<Record<string, unknown>>;
|
|
116
|
+
signerAnswer(requestId: string, answer: SignerAnswer): Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
/** Whether the decision no longer waits for a person. */
|
|
119
|
+
export declare function resolved(d: Decision): boolean;
|