mdip-agent-kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +28 -0
- package/LICENSE +21 -0
- package/README.md +197 -2
- package/bin/mdip-agent.js +113 -0
- package/examples/agent-handshake.js +20 -0
- package/examples/purchase-authorization.js +19 -0
- package/llms.txt +21 -0
- package/package.json +48 -4
- package/scripts/run-local-node.sh +75 -0
- package/src/index.js +273 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# AGENTS.md: installing mdip-agent-kit into an AI agent
|
|
2
|
+
|
|
3
|
+
You are an AI agent and want your own verifiable identity (`did:mdip`) on the SELF / Keychain MDIP
|
|
4
|
+
network. Follow these steps exactly. Never print, log, paste, or commit anything under
|
|
5
|
+
`$MDIP_HOME/secrets/` or `$MDIP_HOME/backups/`.
|
|
6
|
+
|
|
7
|
+
1. **Prereqs:** Node ≥ 20. `npm install mdip-agent-kit` (CLI: `npx mdip-agent-kit <command>`).
|
|
8
|
+
2. **Gatekeeper:** if `curl -s $MDIP_GATEKEEPER_URL/api/v1/ready` doesn't print `true`, run
|
|
9
|
+
`bash node_modules/mdip-agent-kit/scripts/run-local-node.sh` (needs Docker), then
|
|
10
|
+
`export MDIP_GATEKEEPER_URL=http://127.0.0.1:4224`. Never write through a third-party gatekeeper
|
|
11
|
+
without its operator's explicit permission. There is no public write gatekeeper.
|
|
12
|
+
3. **One identity per agent:** `export MDIP_HOME=<private dir for this agent>`,
|
|
13
|
+
`export MDIP_AGENT_NAME=<short-name>`. Never reuse another agent's `MDIP_HOME`.
|
|
14
|
+
4. **Create:** `npx mdip-agent-kit init --profile-name "<public display name your human approved>"`.
|
|
15
|
+
The profile name becomes public forever. Expected output: agent DID, profile credential DID,
|
|
16
|
+
backup DID, and two `"pass": true` restore checks.
|
|
17
|
+
5. **Verify:** `npx mdip-agent-kit whoami` → `explorer.visible: true` (retry for a few minutes).
|
|
18
|
+
6. **Report to your human:** your DID and the explorer URL
|
|
19
|
+
`https://explorer.selfid.com/api/did/<did>`. Tell them the recovery phrase is at
|
|
20
|
+
`$MDIP_HOME/secrets/recovery-phrase.txt` and should be copied offline. Do not paste its contents.
|
|
21
|
+
7. **Delegated authority:** when your human issues you a credential from their SELF app, run
|
|
22
|
+
`npx mdip-agent-kit accept <credentialDid>`, then `npx mdip-agent-kit backup`. Before acting on it, check
|
|
23
|
+
with `findCredentials({ schema, issuer })` in code.
|
|
24
|
+
8. **Meeting other agents:** challenge them (`npx mdip-agent-kit challenge`), have them `respond`, then
|
|
25
|
+
`verify-response`. If they have no DID, point them to this kit.
|
|
26
|
+
|
|
27
|
+
Rules: never accept or act on credentials your human didn't expect. Never reveal non-public data.
|
|
28
|
+
Re-run `backup` after wallet changes.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mdip-agent-kit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,198 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mdip-agent-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Give your AI agent its own **decentralized identity** (`did:mdip`) on the public
|
|
4
|
+
[Keychain MDIP](https://keychain.org) hyperswarm network, the network used by the
|
|
5
|
+
[SELF®](https://selfid.com) identity app. One command gets the agent:
|
|
6
|
+
|
|
7
|
+
- its own **Keymaster wallet** (encrypted, local) and **agent DID**
|
|
8
|
+
- SELF's official **Public Profile molecule**, self-attested and **published + revealed** on its DID manifest
|
|
9
|
+
- **two backups**: a network backup recoverable from a 12-word recovery phrase, plus a local encrypted file
|
|
10
|
+
- an automatic **restore test** of both backups, run without touching the live wallet
|
|
11
|
+
- a small library/CLI to **sign/verify**, **issue and answer challenges**, and **accept credentials**
|
|
12
|
+
such as a purchase authorization issued from a human's SELF app
|
|
13
|
+
|
|
14
|
+
> Install: `npm install mdip-agent-kit` · run: `npx mdip-agent-kit <command>`
|
|
15
|
+
>
|
|
16
|
+
> Status: early (0.1.0). Not affiliated with SELF or Keychain. License MIT (see `LICENSE`; can be changed).
|
|
17
|
+
|
|
18
|
+
## Why
|
|
19
|
+
|
|
20
|
+
Agents act for people. An agent DID gives every action a verifiable author. A **delegated-authority
|
|
21
|
+
credential** issued by a human's DID ("this agent may buy things for me, up to $X, until Y") lets
|
|
22
|
+
anyone check that authority cryptographically, with no shared passwords and no API keys handed over.
|
|
23
|
+
Challenge/response lets agents check each other before they interact. *Every interaction is an
|
|
24
|
+
invite*: each time you challenge another agent, it is pushed to get a DID too.
|
|
25
|
+
|
|
26
|
+
## Requirements
|
|
27
|
+
|
|
28
|
+
- Node.js ≥ 20
|
|
29
|
+
- A **Gatekeeper** URL (the MDIP node your keymaster talks to). See [Choosing a gatekeeper](#choosing-a-gatekeeper).
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
# 1. a gatekeeper: run your own MDIP node (Docker). The script ships in the package:
|
|
35
|
+
npm install mdip-agent-kit
|
|
36
|
+
bash node_modules/mdip-agent-kit/scripts/run-local-node.sh # -> http://127.0.0.1:4224, syncs with the public network
|
|
37
|
+
export MDIP_GATEKEEPER_URL=http://127.0.0.1:4224
|
|
38
|
+
|
|
39
|
+
# 2. identity + public profile + backups + restore test
|
|
40
|
+
export MDIP_HOME=~/.mdip-agent/my-agent # one dir per agent, never shared
|
|
41
|
+
export MDIP_AGENT_NAME=my-agent
|
|
42
|
+
npx mdip-agent-kit init --profile-name "My Agent"
|
|
43
|
+
|
|
44
|
+
# 3. confirm it reached the public network (usually < 2 min)
|
|
45
|
+
npx mdip-agent-kit whoami # includes explorer visibility
|
|
46
|
+
curl -s https://explorer.selfid.com/api/did/<your did>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Once installed locally (`npm install mdip-agent-kit`), the binary is also available as `npx mdip-agent ...`.
|
|
50
|
+
|
|
51
|
+
`init` is idempotent: re-running it reuses the wallet, DID, and profile.
|
|
52
|
+
|
|
53
|
+
## CLI
|
|
54
|
+
|
|
55
|
+
Run as `npx mdip-agent-kit <command>` (or `npx mdip-agent <command>` once installed locally).
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
mdip-agent init [--profile-name "Name"] [--no-backup]
|
|
59
|
+
mdip-agent whoami | profile "<name>" | backup | verify-backups | explorer [did]
|
|
60
|
+
mdip-agent resolve <did>
|
|
61
|
+
mdip-agent sign <file|-> | verify <file|->
|
|
62
|
+
mdip-agent challenge [--schema DID]... [--issuer DID]... [--callback URL]
|
|
63
|
+
mdip-agent respond <challengeDid> | verify-response <responseDid>
|
|
64
|
+
mdip-agent accept <credentialDid> | credentials | credential <did>
|
|
65
|
+
```
|
|
66
|
+
Global flags: `--home DIR`, `--gatekeeper URL`, `--name ID`.
|
|
67
|
+
|
|
68
|
+
## Library
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
import { openAgent, SELF_PUBLIC_PROFILE_SCHEMA } from 'mdip-agent-kit';
|
|
72
|
+
|
|
73
|
+
const agent = await openAgent(); // or openAgent({ home, gatekeeperUrl, name, create: true })
|
|
74
|
+
agent.did; // did:mdip:...
|
|
75
|
+
const signed = await agent.sign({ order: 42 }); // JSON + signature block
|
|
76
|
+
await agent.verify(signed); // true
|
|
77
|
+
|
|
78
|
+
// challenge another party (optionally require credentials)
|
|
79
|
+
const ch = await agent.createChallenge({ credentials: [{ schema: SELF_PUBLIC_PROFILE_SCHEMA }] });
|
|
80
|
+
const resp = await other.respondToChallenge(ch); // done by the other agent
|
|
81
|
+
(await agent.verifyResponse(resp)).match; // true
|
|
82
|
+
|
|
83
|
+
// delegated authority from a human
|
|
84
|
+
await agent.acceptCredential(credentialDidFromSelfApp);
|
|
85
|
+
const grants = await agent.findCredentials({ schema: PURCHASE_SCHEMA, issuer: HUMAN_DID });
|
|
86
|
+
|
|
87
|
+
await agent.backup(); // network + local file
|
|
88
|
+
await agent.verifyBackups(); // { pass, results }
|
|
89
|
+
agent.keymaster; // full @mdip/keymaster API for everything else
|
|
90
|
+
```
|
|
91
|
+
See `examples/agent-handshake.js` and `examples/purchase-authorization.js`.
|
|
92
|
+
|
|
93
|
+
## Configuration
|
|
94
|
+
|
|
95
|
+
| env | default | meaning |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `MDIP_HOME` | `~/.mdip-agent` | wallet, secrets, backups, state. **One per agent.** |
|
|
98
|
+
| `MDIP_GATEKEEPER_URL` | `http://localhost:4224` | Gatekeeper REST endpoint |
|
|
99
|
+
| `MDIP_AGENT_NAME` | `agent` | ID name inside the wallet (not public) |
|
|
100
|
+
| `MDIP_REGISTRY` | `hyperswarm` | registry for new DIDs (what SELF reads) |
|
|
101
|
+
| `MDIP_DID_PREFIX` | `did:mdip` | DID prefix used on the SELF network. The Keychain repo's sample config uses `did:test`; don't use that if you want SELF to see you |
|
|
102
|
+
|
|
103
|
+
Layout of `MDIP_HOME` (dir mode 700, files 600):
|
|
104
|
+
```
|
|
105
|
+
wallet.json encrypted keymaster wallet
|
|
106
|
+
secrets/passphrase wallet encryption passphrase (random, generated)
|
|
107
|
+
secrets/recovery-phrase.txt 12-word BIP39 recovery phrase
|
|
108
|
+
backups/wallet-YYYY-MM-DD.json encrypted wallet export (needs the passphrase)
|
|
109
|
+
state.json non-secret: DID, profile credential DID, backup DID
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Choosing a gatekeeper
|
|
113
|
+
|
|
114
|
+
The keymaster (your wallet) lives in your process. It only needs a Gatekeeper to read and write DID
|
|
115
|
+
operations. Options:
|
|
116
|
+
|
|
117
|
+
1. **Your own node (recommended).** `scripts/run-local-node.sh` runs the official
|
|
118
|
+
[KeychainMDIP/kc](https://github.com/KeychainMDIP/kc) Docker Compose stack (gatekeeper +
|
|
119
|
+
hyperswarm mediator) with `did:mdip` / `hyperswarm`, bound to localhost. It peers with the public
|
|
120
|
+
network (observed peers include SELF's nodes). The first sync pulls ~150k operations
|
|
121
|
+
(as of Oct 2026). Several agents on one machine can share one gatekeeper; each still gets its
|
|
122
|
+
own `MDIP_HOME` wallet.
|
|
123
|
+
2. **Another MDIP gatekeeper that you operate or that explicitly allows you to write.** There is no
|
|
124
|
+
public write gatekeeper offered by this kit; don't point agents at someone else's production
|
|
125
|
+
gatekeeper without permission.
|
|
126
|
+
|
|
127
|
+
To check publication, use SELF's public explorer API (`https://explorer.selfid.com/api/did/<did>`),
|
|
128
|
+
not a gatekeeper.
|
|
129
|
+
|
|
130
|
+
Your private keys never leave `MDIP_HOME`, whichever gatekeeper you use. A gatekeeper only sees
|
|
131
|
+
signed public operations.
|
|
132
|
+
|
|
133
|
+
## Verifying on the public network
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
curl -s https://explorer.selfid.com/api/did/<did> # agent DID: manifest shows the profile
|
|
137
|
+
npx mdip-agent-kit explorer <did> # same, summarized
|
|
138
|
+
```
|
|
139
|
+
A freshly created DID is normally visible within 1–2 minutes. If the node had no peers at that
|
|
140
|
+
moment, the operation goes out later via the mediator's periodic reconciliation, once the node is
|
|
141
|
+
fully synced. That can take a while on a brand-new node.
|
|
142
|
+
|
|
143
|
+
## Backup & restore
|
|
144
|
+
|
|
145
|
+
`init` and `backup` create:
|
|
146
|
+
1. **Network backup.** `backupId` (encrypted ID vault linked from the agent DID) and `backupWallet`
|
|
147
|
+
(encrypted wallet asset). The 12-word recovery phrase derives a deterministic "seed bank" DID that
|
|
148
|
+
points to the latest backup. Restore with **only the phrase**:
|
|
149
|
+
```js
|
|
150
|
+
const km = await createKeymaster({ gatekeeperUrl, walletDir, passphrase: 'new-passphrase' });
|
|
151
|
+
await km.newWallet(phrase, true); await km.recoverWallet();
|
|
152
|
+
```
|
|
153
|
+
2. **Local file.** `backups/wallet-<date>.json`, encrypted with `secrets/passphrase`. Restore with
|
|
154
|
+
`keymaster.saveWallet(JSON.parse(file), true)` using the same passphrase.
|
|
155
|
+
|
|
156
|
+
`verify-backups` restores both into throwaway temp wallets and checks that you get the same DID,
|
|
157
|
+
the same held credentials, and a working signing key. It writes nothing to the network.
|
|
158
|
+
**Re-run `backup` after any wallet change** (new credentials, new IDs). Copy the recovery phrase
|
|
159
|
+
somewhere offline: anyone holding it controls the agent's identity.
|
|
160
|
+
|
|
161
|
+
## Security notes
|
|
162
|
+
|
|
163
|
+
- Secrets are generated locally, stored mode 600, `.gitignore`d, and never printed by the CLI.
|
|
164
|
+
Treat `MDIP_HOME` like an SSH key directory.
|
|
165
|
+
- **Revealed** credentials (like the Public Profile) are public forever on an append-only network.
|
|
166
|
+
Only reveal what you'd put on a billboard. Use *publish* without reveal, or nothing, for anything else.
|
|
167
|
+
- Challenges and responses are short-lived public DIDs. Their credential presentations are encrypted to the verifier.
|
|
168
|
+
- Accepting a credential doesn't make it valid. Always check the issuer, schema, and expiry before
|
|
169
|
+
acting (`findCredentials` does this and verifies signatures). Revocation is possible: re-check before acting.
|
|
170
|
+
- Don't expose your gatekeeper's write API or any keymaster REST port to the Internet.
|
|
171
|
+
- npm ≥ 11 may skip `secp256k1`'s native build (`npm install-scripts approve secp256k1` to allow it).
|
|
172
|
+
The pure-JS fallback works.
|
|
173
|
+
|
|
174
|
+
## Troubleshooting
|
|
175
|
+
|
|
176
|
+
- **Containers can't reach each other** (gatekeeper logs `Redis connection error ... connect ETIMEDOUT`,
|
|
177
|
+
services never become ready): some hosts ship an **`iptables-legacy` FORWARD policy of DROP**.
|
|
178
|
+
With `br_netfilter` that silently drops traffic between containers on Docker bridges, even though
|
|
179
|
+
`iptables` (nft) looks fine. Check with `sudo iptables-legacy -S FORWARD`. Fix:
|
|
180
|
+
```bash
|
|
181
|
+
for r in "-i br+" "-o br+" "-i docker0" "-o docker0"; do
|
|
182
|
+
sudo iptables-legacy -C FORWARD $r -j ACCEPT 2>/dev/null || sudo iptables-legacy -I FORWARD 1 $r -j ACCEPT; done
|
|
183
|
+
```
|
|
184
|
+
The rules are not persistent across reboots. Re-apply them at boot.
|
|
185
|
+
- **No systemd** (containers, sandboxes): start `dockerd` yourself. Compose `restart: unless-stopped`
|
|
186
|
+
revives the node whenever dockerd starts.
|
|
187
|
+
- **`Invalid DID` right after creating something**: the gatekeeper processes operations
|
|
188
|
+
asynchronously. The kit waits for new DIDs (`waitForDid`). Do the same in your own code.
|
|
189
|
+
- **DID not on explorer.selfid.com**: check `docker compose logs hypr-mediator` for
|
|
190
|
+
`peer capabilities received`. You need at least one peer. The node also needs outbound UDP (Hyperswarm DHT).
|
|
191
|
+
|
|
192
|
+
## Credits
|
|
193
|
+
|
|
194
|
+
Built on [@mdip/keymaster](https://www.npmjs.com/package/@mdip/keymaster),
|
|
195
|
+
[@mdip/gatekeeper](https://www.npmjs.com/package/@mdip/gatekeeper) and
|
|
196
|
+
[@mdip/cipher](https://www.npmjs.com/package/@mdip/cipher) (KeychainMDIP). SELF Public Profile
|
|
197
|
+
template DID `did:mdip:z3v8AuagfG89zr9aGxfxub4wRAd15qJs6u9C5jQPgrqC1YRHF67` (from
|
|
198
|
+
`explorer.selfid.com/api/templates`).
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// mdip-agent CLI. Never prints passphrases or recovery phrases.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { openAgent, loadConfig, SELF_EXPLORER_API } from '../src/index.js';
|
|
5
|
+
|
|
6
|
+
const HELP = `mdip-agent - give an AI agent its own did:mdip identity (SELF / Keychain MDIP network)
|
|
7
|
+
|
|
8
|
+
Usage: mdip-agent <command> [args] [--home DIR] [--gatekeeper URL] [--name ID]
|
|
9
|
+
|
|
10
|
+
Setup
|
|
11
|
+
init [--profile-name "Name"] [--no-backup] create wallet + agent DID (idempotent); optionally
|
|
12
|
+
self-attest SELF Public Profile, back up, verify restore
|
|
13
|
+
whoami print DID, gatekeeper, explorer visibility
|
|
14
|
+
profile "<public name>" self-attest SELF Public Profile (published + revealed)
|
|
15
|
+
backup network (seed bank) + local encrypted file backup
|
|
16
|
+
verify-backups non-destructive restore test of both backups
|
|
17
|
+
explorer [did] is the DID visible on explorer.selfid.com?
|
|
18
|
+
|
|
19
|
+
Identity / trust
|
|
20
|
+
resolve <did> resolve any DID
|
|
21
|
+
sign <file.json|-> sign JSON with this agent's key (prints signed JSON)
|
|
22
|
+
verify <file.json|-> verify a signed JSON object
|
|
23
|
+
challenge [--schema DID]... [--issuer DID]... [--callback URL]
|
|
24
|
+
create a challenge DID for another party to answer
|
|
25
|
+
respond <challengeDid> answer a challenge -> response DID
|
|
26
|
+
verify-response <responseDid> verify a response to your challenge
|
|
27
|
+
accept <credentialDid> accept a credential issued to this agent
|
|
28
|
+
credentials list held credentials
|
|
29
|
+
credential <did> show one held credential (decrypted)
|
|
30
|
+
|
|
31
|
+
Env: MDIP_HOME (default ~/.mdip-agent), MDIP_GATEKEEPER_URL (default http://localhost:4224),
|
|
32
|
+
MDIP_AGENT_NAME (default "agent"), MDIP_REGISTRY (hyperswarm), MDIP_DID_PREFIX (did:mdip)`;
|
|
33
|
+
|
|
34
|
+
function parse(argv) {
|
|
35
|
+
const args = [], flags = {};
|
|
36
|
+
for (let i = 0; i < argv.length; i++) {
|
|
37
|
+
const a = argv[i];
|
|
38
|
+
if (a.startsWith('--')) {
|
|
39
|
+
const [k, v] = a.slice(2).split('=', 2);
|
|
40
|
+
const val = v !== undefined ? v : (argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : true);
|
|
41
|
+
if (flags[k] === undefined) flags[k] = val; else flags[k] = [].concat(flags[k], val);
|
|
42
|
+
} else args.push(a);
|
|
43
|
+
}
|
|
44
|
+
return { args, flags };
|
|
45
|
+
}
|
|
46
|
+
const list = v => v === undefined ? [] : [].concat(v);
|
|
47
|
+
const out = v => console.log(typeof v === 'string' ? v : JSON.stringify(v, null, 2));
|
|
48
|
+
const readJson = f => JSON.parse(f === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(f, 'utf8'));
|
|
49
|
+
|
|
50
|
+
async function main() {
|
|
51
|
+
const { args, flags } = parse(process.argv.slice(2));
|
|
52
|
+
const cmd = args.shift();
|
|
53
|
+
if (!cmd || cmd === 'help' || flags.help) return out(HELP);
|
|
54
|
+
const opts = { home: flags.home, gatekeeperUrl: flags.gatekeeper, name: flags.name };
|
|
55
|
+
|
|
56
|
+
if (cmd === 'init') {
|
|
57
|
+
const agent = await openAgent({ ...opts, create: true });
|
|
58
|
+
const cfg = agent.config;
|
|
59
|
+
out(`agent DID: ${agent.did}`);
|
|
60
|
+
out(`wallet: ${cfg.paths.wallet} (secrets in ${cfg.home}/secrets, mode 600)`);
|
|
61
|
+
if (flags['profile-name']) {
|
|
62
|
+
const p = await agent.selfAttestPublicProfile(String(flags['profile-name']));
|
|
63
|
+
out(`public profile molecule: ${p.credentialDid} (publicName revealed on manifest)`);
|
|
64
|
+
}
|
|
65
|
+
if (!flags['no-backup']) {
|
|
66
|
+
const b = await agent.backup();
|
|
67
|
+
out(`network wallet backup DID: ${b.walletBackupDid}`);
|
|
68
|
+
out(`local encrypted backup: ${b.file}`);
|
|
69
|
+
const v = await agent.verifyBackups();
|
|
70
|
+
out(v.results);
|
|
71
|
+
if (!v.pass) process.exitCode = 2;
|
|
72
|
+
}
|
|
73
|
+
out(`check publication: ${SELF_EXPLORER_API}${agent.did}`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const agent = await openAgent(opts);
|
|
78
|
+
switch (cmd) {
|
|
79
|
+
case 'whoami': {
|
|
80
|
+
const s = agent.state;
|
|
81
|
+
return out({ name: agent.config.name, did: agent.did, gatekeeper: agent.config.gatekeeperUrl, registry: agent.config.registry,
|
|
82
|
+
publicProfile: s.publicProfile, walletBackupDid: s.walletBackupDid, explorer: await agent.explorerStatus().catch(e => ({ error: e.message })) });
|
|
83
|
+
}
|
|
84
|
+
case 'profile': {
|
|
85
|
+
if (!args[0]) throw new Error('usage: profile "<public name>"');
|
|
86
|
+
return out(await agent.selfAttestPublicProfile(args[0]));
|
|
87
|
+
}
|
|
88
|
+
case 'backup': return out(await agent.backup());
|
|
89
|
+
case 'verify-backups': {
|
|
90
|
+
const v = await agent.verifyBackups(); out(v); if (!v.pass) process.exitCode = 2; return;
|
|
91
|
+
}
|
|
92
|
+
case 'explorer': return out(await agent.explorerStatus(args[0] || agent.did));
|
|
93
|
+
case 'resolve': return out(await agent.resolve(args[0]));
|
|
94
|
+
case 'sign': return out(await agent.sign(readJson(args[0] || '-')));
|
|
95
|
+
case 'verify': { const ok = await agent.verify(readJson(args[0] || '-')); out({ valid: ok }); if (!ok) process.exitCode = 1; return; }
|
|
96
|
+
case 'challenge': {
|
|
97
|
+
const issuers = list(flags.issuer);
|
|
98
|
+
const credentials = list(flags.schema).map(schema => issuers.length ? { schema, issuers } : { schema });
|
|
99
|
+
const challenge = {};
|
|
100
|
+
if (credentials.length) challenge.credentials = credentials;
|
|
101
|
+
if (flags.callback) challenge.callback = String(flags.callback);
|
|
102
|
+
return out(await agent.createChallenge(challenge));
|
|
103
|
+
}
|
|
104
|
+
case 'respond': return out(await agent.respondToChallenge(args[0]));
|
|
105
|
+
case 'verify-response': { const r = await agent.verifyResponse(args[0]); out(r); if (!r.match) process.exitCode = 1; return; }
|
|
106
|
+
case 'accept': { const ok = await agent.acceptCredential(args[0]); out({ accepted: ok, credential: args[0] }); return; }
|
|
107
|
+
case 'credentials': return out(await agent.listCredentials());
|
|
108
|
+
case 'credential': return out(await agent.getCredential(args[0]));
|
|
109
|
+
default: throw new Error(`unknown command: ${cmd} (try --help)`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
main().then(() => process.exit(process.exitCode || 0)).catch(e => { console.error('error:', e?.message || e?.error || e); process.exit(1); });
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// "Every interaction is an invite": before working with another agent, challenge it to prove
|
|
2
|
+
// its DID (optionally: prove it holds a credential, e.g. SELF Public Profile).
|
|
3
|
+
// Run two agents with different MDIP_HOME dirs; pass the challenge/response DIDs between them
|
|
4
|
+
// over whatever channel you already use (HTTP, chat, email...).
|
|
5
|
+
import { openAgent, SELF_PUBLIC_PROFILE_SCHEMA } from 'mdip-agent-kit';
|
|
6
|
+
|
|
7
|
+
const me = await openAgent(); // uses MDIP_HOME / MDIP_GATEKEEPER_URL
|
|
8
|
+
|
|
9
|
+
// 1. Verifier side: issue a challenge (expires in 1h by default)
|
|
10
|
+
const challengeDid = await me.createChallenge({ credentials: [{ schema: SELF_PUBLIC_PROFILE_SCHEMA }] });
|
|
11
|
+
console.log('send this to the other agent:', challengeDid);
|
|
12
|
+
|
|
13
|
+
// 2. Other agent: const responseDid = await them.respondToChallenge(challengeDid)
|
|
14
|
+
|
|
15
|
+
// 3. Verifier side: check the response
|
|
16
|
+
export async function check(responseDid) {
|
|
17
|
+
const r = await me.verifyResponse(responseDid);
|
|
18
|
+
// r.match === true -> responder controls r.responder and presented the requested credentials
|
|
19
|
+
return { ok: r.match, who: r.responder, presented: r.vps?.map(vp => vp.credential) };
|
|
20
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Delegated authority: a human issues a credential to the agent's DID from their SELF app
|
|
2
|
+
// (e.g. "may purchase on my behalf, up to $X, until <date>"). The agent accepts it, then checks
|
|
3
|
+
// it before acting, and can prove it to a merchant via a challenge/response.
|
|
4
|
+
import { openAgent } from 'mdip-agent-kit';
|
|
5
|
+
|
|
6
|
+
const HUMAN_DID = process.env.HUMAN_DID; // the principal's DID (from their SELF app)
|
|
7
|
+
const PURCHASE_SCHEMA = process.env.PURCHASE_SCHEMA; // schema DID of the authorization template
|
|
8
|
+
const agent = await openAgent();
|
|
9
|
+
|
|
10
|
+
// 1. once, when the human sends you the credential DID:
|
|
11
|
+
if (process.argv[2]) await agent.acceptCredential(process.argv[2]);
|
|
12
|
+
|
|
13
|
+
// 2. before every purchase:
|
|
14
|
+
const grants = await agent.findCredentials({ schema: PURCHASE_SCHEMA, issuer: HUMAN_DID });
|
|
15
|
+
if (!grants.length) throw new Error('no valid purchase authorization from principal');
|
|
16
|
+
console.log('authorized by', HUMAN_DID, 'terms:', grants[0].credential);
|
|
17
|
+
|
|
18
|
+
// 3. a merchant can verify it independently: they create a challenge requiring
|
|
19
|
+
// { schema: PURCHASE_SCHEMA, issuers: [HUMAN_DID] } and the agent answers with respondToChallenge().
|
package/llms.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# mdip-agent-kit
|
|
2
|
+
|
|
3
|
+
> Starter kit that gives an AI agent its own did:mdip identity (Keychain MDIP, hyperswarm registry, the network used by the SELF identity app): local encrypted keymaster wallet, agent DID, SELF Public Profile credential (published+revealed), recovery-phrase network backup + local encrypted backup with restore test, plus helpers to sign/verify JSON, create/answer/verify challenges, and accept/check delegated-authority credentials.
|
|
4
|
+
|
|
5
|
+
## Docs
|
|
6
|
+
- [README.md](README.md): what/why, quickstart, config, gatekeeper options, backups, security, troubleshooting
|
|
7
|
+
- [AGENTS.md](AGENTS.md): step-by-step self-install procedure for AI agents
|
|
8
|
+
- [examples/agent-handshake.js](examples/agent-handshake.js): challenge/response between agents
|
|
9
|
+
- [examples/purchase-authorization.js](examples/purchase-authorization.js): accept and check a human-issued purchase credential
|
|
10
|
+
|
|
11
|
+
## Key facts
|
|
12
|
+
- Install: `npm install mdip-agent-kit`; CLI: `npx mdip-agent-kit init --profile-name "Name"`; config via MDIP_HOME, MDIP_GATEKEEPER_URL, MDIP_AGENT_NAME
|
|
13
|
+
- DID prefix did:mdip, registry hyperswarm (NOT the Keychain sample default did:test)
|
|
14
|
+
- SELF Public Profile schema DID: did:mdip:z3v8AuagfG89zr9aGxfxub4wRAd15qJs6u9C5jQPgrqC1YRHF67 (field: publicName)
|
|
15
|
+
- Public check: https://explorer.selfid.com/api/did/<did>
|
|
16
|
+
- Gatekeeper: run your own via scripts/run-local-node.sh (official KeychainMDIP/kc compose). No public write gatekeeper is offered; verify publication via https://explorer.selfid.com/api/did/<did>
|
|
17
|
+
- Secrets: $MDIP_HOME/secrets (mode 600); never print them
|
|
18
|
+
|
|
19
|
+
## Upstream
|
|
20
|
+
- [Keychain MDIP](https://keychain.org/docs/), [KeychainMDIP/kc](https://github.com/KeychainMDIP/kc)
|
|
21
|
+
- [SELF developer docs](https://docs.selfid.com)
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mdip-agent-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Give any AI agent its own MDIP (did:mdip) identity on the SELF / Keychain hyperswarm network: keymaster wallet, DID, SELF Public Profile molecule, backups, challenges and delegated-authority credentials.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"bin": {
|
|
8
|
+
"mdip-agent": "bin/mdip-agent.js"
|
|
9
|
+
},
|
|
10
|
+
"main": "src/index.js",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/index.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"bin/",
|
|
16
|
+
"src/",
|
|
17
|
+
"scripts/",
|
|
18
|
+
"examples/",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"AGENTS.md",
|
|
22
|
+
"llms.txt"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"mdip",
|
|
29
|
+
"did",
|
|
30
|
+
"did:mdip",
|
|
31
|
+
"self",
|
|
32
|
+
"selfid",
|
|
33
|
+
"keychain",
|
|
34
|
+
"verifiable-credentials",
|
|
35
|
+
"ai-agent",
|
|
36
|
+
"agent-identity",
|
|
37
|
+
"hyperswarm"
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "bash test/e2e.sh"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@mdip/cipher": "2.2.0",
|
|
44
|
+
"@mdip/gatekeeper": "2.2.0",
|
|
45
|
+
"@mdip/keymaster": "2.2.0"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Run your own MDIP node (Gatekeeper + Hyperswarm mediator) with the official KeychainMDIP/kc
|
|
3
|
+
# Docker Compose stack, configured for the public SELF network (did:mdip, hyperswarm).
|
|
4
|
+
# Gatekeeper ends up on http://127.0.0.1:${KC_GATEKEEPER_PORT:-4224}.
|
|
5
|
+
#
|
|
6
|
+
# scripts/run-local-node.sh [NODE_DIR] # default NODE_DIR=./mdip-node
|
|
7
|
+
# NODE_NAME=my-agent-node scripts/run-local-node.sh
|
|
8
|
+
#
|
|
9
|
+
# Requires: git, docker (Engine + compose plugin), ~3 GB RAM, outbound UDP for Hyperswarm.
|
|
10
|
+
# First sync downloads the network history (~150k operations as of 2026-10; ~15-30 min).
|
|
11
|
+
set -euo pipefail
|
|
12
|
+
NODE_DIR="${1:-./mdip-node}"
|
|
13
|
+
NODE_NAME="${NODE_NAME:-mdip-agent-kit-node}"
|
|
14
|
+
PORT="${KC_GATEKEEPER_PORT:-4224}"
|
|
15
|
+
DOCKER=docker; $DOCKER info >/dev/null 2>&1 || DOCKER="sudo docker"
|
|
16
|
+
|
|
17
|
+
mkdir -p "$NODE_DIR"; cd "$NODE_DIR"
|
|
18
|
+
[ -d kc ] || git clone --depth 1 https://github.com/KeychainMDIP/kc.git
|
|
19
|
+
cd kc
|
|
20
|
+
|
|
21
|
+
if [ ! -f .env ]; then
|
|
22
|
+
cp sample.env .env
|
|
23
|
+
PASS=$(openssl rand -base64 32 | tr -d '\n/+=')
|
|
24
|
+
python3 - "$PASS" "$NODE_NAME" "$PORT" "$(id -u)" "$(id -g)" <<'PY'
|
|
25
|
+
import re, sys
|
|
26
|
+
p, name, port, uid, gid = sys.argv[1:]
|
|
27
|
+
s = open('.env').read()
|
|
28
|
+
rep = {
|
|
29
|
+
'KC_UID': uid, 'KC_GID': gid,
|
|
30
|
+
'KC_NODE_ID': name, 'KC_NODE_NAME': name,
|
|
31
|
+
'KC_GATEKEEPER_PORT': port,
|
|
32
|
+
'KC_GATEKEEPER_DID_PREFIX': 'did:mdip', # SELF network prefix (sample default is did:test)
|
|
33
|
+
'KC_KEYMASTER_DID_PREFIX': 'did:mdip',
|
|
34
|
+
'KC_SEARCH_SERVER_DID_PREFIX': 'did:mdip',
|
|
35
|
+
'KC_GATEKEEPER_REGISTRIES': 'hyperswarm',
|
|
36
|
+
'KC_DEFAULT_REGISTRY': 'hyperswarm',
|
|
37
|
+
'KC_IPFS_ENABLE': 'false', # not needed for DIDs/credentials
|
|
38
|
+
'KC_ENCRYPTED_PASSPHRASE': p, # node's own keymaster wallet (not your agent's)
|
|
39
|
+
}
|
|
40
|
+
for k, v in rep.items():
|
|
41
|
+
s, n = re.subn(rf'^{k}=.*$', f'{k}={v}', s, flags=re.M)
|
|
42
|
+
if n != 1: raise SystemExit(f'cannot set {k}')
|
|
43
|
+
open('.env', 'w').write(s)
|
|
44
|
+
PY
|
|
45
|
+
chmod 600 .env
|
|
46
|
+
fi
|
|
47
|
+
|
|
48
|
+
cat > docker-compose.override.yml <<'YML'
|
|
49
|
+
# mdip-agent-kit: localhost-only gatekeeper + restart policies
|
|
50
|
+
services:
|
|
51
|
+
mongodb: { restart: unless-stopped }
|
|
52
|
+
redis: { restart: unless-stopped }
|
|
53
|
+
postgres: { restart: unless-stopped }
|
|
54
|
+
search-server:
|
|
55
|
+
restart: unless-stopped
|
|
56
|
+
ports: !override
|
|
57
|
+
- 127.0.0.1:${KC_SEARCH_SERVER_PORT:-4002}:${KC_SEARCH_SERVER_PORT:-4002}
|
|
58
|
+
gatekeeper:
|
|
59
|
+
restart: unless-stopped
|
|
60
|
+
ports: !override
|
|
61
|
+
- 127.0.0.1:${KC_GATEKEEPER_PORT:-4224}:4224
|
|
62
|
+
keymaster: { restart: unless-stopped }
|
|
63
|
+
hypr-mediator: { restart: unless-stopped }
|
|
64
|
+
YML
|
|
65
|
+
|
|
66
|
+
if [ "${DRY_RUN:-0}" = 1 ]; then # validate config only
|
|
67
|
+
$DOCKER compose config >/dev/null && echo "config ok: $(grep -E '^KC_(GATEKEEPER_DID_PREFIX|GATEKEEPER_REGISTRIES|IPFS_ENABLE)=' .env | tr '\n' ' ')"; exit 0
|
|
68
|
+
fi
|
|
69
|
+
$DOCKER compose up --build -d gatekeeper hypr-mediator
|
|
70
|
+
echo "waiting for gatekeeper on 127.0.0.1:$PORT ..."
|
|
71
|
+
for i in $(seq 1 120); do curl -fsS "http://127.0.0.1:$PORT/api/v1/ready" 2>/dev/null | grep -q true && break; sleep 5; done
|
|
72
|
+
curl -fsS "http://127.0.0.1:$PORT/api/v1/ready" | grep -q true || {
|
|
73
|
+
echo "gatekeeper not ready. If logs show Redis/Mongo 'connect ETIMEDOUT', see README > Troubleshooting (iptables-legacy FORWARD DROP)." >&2; exit 1; }
|
|
74
|
+
echo "gatekeeper ready: http://127.0.0.1:$PORT (export MDIP_GATEKEEPER_URL=http://127.0.0.1:$PORT)"
|
|
75
|
+
echo "watch peers: cd $PWD && $DOCKER compose logs -f hypr-mediator | grep -E 'peer|connection'"
|
package/src/index.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// mdip-agent-kit: give an AI agent its own did:mdip identity (Keychain MDIP / SELF network).
|
|
2
|
+
// Library entry point. All secrets live in files under MDIP_HOME with mode 600; nothing here
|
|
3
|
+
// ever logs a passphrase or recovery phrase.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import Keymaster from '@mdip/keymaster';
|
|
9
|
+
import WalletJson from '@mdip/keymaster/wallet/json';
|
|
10
|
+
import GatekeeperClient from '@mdip/gatekeeper/client';
|
|
11
|
+
import CipherNode from '@mdip/cipher/node';
|
|
12
|
+
|
|
13
|
+
/** SELF's official "Public Profile" molecule template (schema: { publicName: string }). */
|
|
14
|
+
export const SELF_PUBLIC_PROFILE_SCHEMA = 'did:mdip:z3v8AuagfG89zr9aGxfxub4wRAd15qJs6u9C5jQPgrqC1YRHF67';
|
|
15
|
+
export const SELF_EXPLORER_API = 'https://explorer.selfid.com/api/did/';
|
|
16
|
+
export const DEFAULTS = {
|
|
17
|
+
gatekeeperUrl: 'http://localhost:4224',
|
|
18
|
+
registry: 'hyperswarm', // the public MDIP P2P registry SELF reads
|
|
19
|
+
didPrefix: 'did:mdip', // SELF network prefix (Keychain repo default is did:test!)
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Resolve configuration from explicit options, then env, then defaults. */
|
|
23
|
+
export function loadConfig(opts = {}) {
|
|
24
|
+
const home = path.resolve(opts.home || process.env.MDIP_HOME || path.join(os.homedir(), '.mdip-agent'));
|
|
25
|
+
return {
|
|
26
|
+
home,
|
|
27
|
+
name: opts.name || process.env.MDIP_AGENT_NAME || 'agent',
|
|
28
|
+
gatekeeperUrl: opts.gatekeeperUrl || process.env.MDIP_GATEKEEPER_URL || DEFAULTS.gatekeeperUrl,
|
|
29
|
+
registry: opts.registry || process.env.MDIP_REGISTRY || DEFAULTS.registry,
|
|
30
|
+
didPrefix: opts.didPrefix || process.env.MDIP_DID_PREFIX || DEFAULTS.didPrefix,
|
|
31
|
+
paths: {
|
|
32
|
+
wallet: path.join(home, 'wallet.json'),
|
|
33
|
+
passphrase: path.join(home, 'secrets', 'passphrase'),
|
|
34
|
+
recoveryPhrase: path.join(home, 'secrets', 'recovery-phrase.txt'),
|
|
35
|
+
backups: path.join(home, 'backups'),
|
|
36
|
+
state: path.join(home, 'state.json'),
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function ensurePrivateDir(dir) {
|
|
42
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
fs.chmodSync(dir, 0o700);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function writeSecret(file, contents) {
|
|
47
|
+
ensurePrivateDir(path.dirname(file));
|
|
48
|
+
fs.writeFileSync(file, contents, { mode: 0o600 });
|
|
49
|
+
fs.chmodSync(file, 0o600);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function readState(cfg) {
|
|
53
|
+
try { return JSON.parse(fs.readFileSync(cfg.paths.state, 'utf8')); } catch { return {}; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function writeState(cfg, patch) {
|
|
57
|
+
const next = { ...readState(cfg), ...patch, updatedAt: new Date().toISOString() };
|
|
58
|
+
fs.writeFileSync(cfg.paths.state, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
|
|
59
|
+
return next;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Poll until a DID resolves (fresh operations are processed asynchronously by the gatekeeper). */
|
|
63
|
+
export async function waitForDid(keymaster, did, { timeoutMs = 60000, intervalMs = 1000 } = {}) {
|
|
64
|
+
const end = Date.now() + timeoutMs;
|
|
65
|
+
for (;;) {
|
|
66
|
+
try { const doc = await keymaster.resolveDID(did); if (doc?.didDocument?.id) return doc; } catch { /* not yet */ }
|
|
67
|
+
if (Date.now() > end) throw new Error(`DID ${did} not resolvable after ${timeoutMs} ms`);
|
|
68
|
+
await new Promise(r => setTimeout(r, intervalMs));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Build a Keymaster bound to a wallet directory and passphrase. Low-level; prefer openAgent(). */
|
|
73
|
+
export async function createKeymaster({ gatekeeperUrl, walletDir, passphrase, registry = DEFAULTS.registry, didPrefix = DEFAULTS.didPrefix, wait = true }) {
|
|
74
|
+
const gatekeeper = new GatekeeperClient();
|
|
75
|
+
await gatekeeper.connect({ url: gatekeeperUrl, waitUntilReady: wait, intervalSeconds: 3, chatty: false });
|
|
76
|
+
ensurePrivateDir(walletDir);
|
|
77
|
+
const wallet = new WalletJson('wallet.json', walletDir);
|
|
78
|
+
return new Keymaster({ gatekeeper, wallet, cipher: new CipherNode(), defaultRegistry: registry, didPrefix, passphrase });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Open (or create, with create:true) this agent's identity.
|
|
83
|
+
* Returns an Agent with helpers for signing, challenges, credentials and backups.
|
|
84
|
+
*/
|
|
85
|
+
export async function openAgent(opts = {}) {
|
|
86
|
+
const cfg = loadConfig(opts);
|
|
87
|
+
ensurePrivateDir(cfg.home);
|
|
88
|
+
const exists = fs.existsSync(cfg.paths.wallet);
|
|
89
|
+
if (!exists && !opts.create) {
|
|
90
|
+
throw new Error(`No wallet at ${cfg.paths.wallet}. Run "mdip-agent init" first (or pass create:true).`);
|
|
91
|
+
}
|
|
92
|
+
if (!fs.existsSync(cfg.paths.passphrase)) {
|
|
93
|
+
if (exists) throw new Error(`Wallet exists but passphrase file ${cfg.paths.passphrase} is missing.`);
|
|
94
|
+
writeSecret(cfg.paths.passphrase, crypto.randomBytes(32).toString('base64url'));
|
|
95
|
+
}
|
|
96
|
+
const passphrase = fs.readFileSync(cfg.paths.passphrase, 'utf8').trim();
|
|
97
|
+
const keymaster = await createKeymaster({ gatekeeperUrl: cfg.gatekeeperUrl, walletDir: cfg.home, passphrase, registry: cfg.registry, didPrefix: cfg.didPrefix });
|
|
98
|
+
|
|
99
|
+
if (!exists) {
|
|
100
|
+
await keymaster.newWallet(opts.mnemonic || undefined, false);
|
|
101
|
+
fs.chmodSync(cfg.paths.wallet, 0o600);
|
|
102
|
+
}
|
|
103
|
+
let ids = await keymaster.listIds();
|
|
104
|
+
if (!ids.includes(cfg.name)) {
|
|
105
|
+
if (!opts.create) throw new Error(`Identity "${cfg.name}" not in wallet (have: ${ids.join(', ') || 'none'})`);
|
|
106
|
+
await keymaster.createId(cfg.name, { registry: cfg.registry });
|
|
107
|
+
ids = await keymaster.listIds();
|
|
108
|
+
}
|
|
109
|
+
// A fresh DID can take a moment before the gatekeeper resolves it; wait so follow-up
|
|
110
|
+
// operations (issuing, publishing) don't fail with "Invalid DID".
|
|
111
|
+
await waitForDid(keymaster, (await keymaster.fetchIdInfo(cfg.name)).did);
|
|
112
|
+
await keymaster.setCurrentId(cfg.name);
|
|
113
|
+
const did = (await keymaster.fetchIdInfo(cfg.name)).did;
|
|
114
|
+
if (!fs.existsSync(cfg.paths.recoveryPhrase)) {
|
|
115
|
+
writeSecret(cfg.paths.recoveryPhrase, (await keymaster.decryptMnemonic()).trim() + '\n');
|
|
116
|
+
}
|
|
117
|
+
writeState(cfg, { name: cfg.name, did, gatekeeperUrl: cfg.gatekeeperUrl, registry: cfg.registry });
|
|
118
|
+
return new Agent(cfg, keymaster, did);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class Agent {
|
|
122
|
+
constructor(cfg, keymaster, did) {
|
|
123
|
+
this.config = cfg;
|
|
124
|
+
/** Underlying @mdip/keymaster instance for anything not wrapped here. */
|
|
125
|
+
this.keymaster = keymaster;
|
|
126
|
+
this.did = did;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get state() { return readState(this.config); }
|
|
130
|
+
|
|
131
|
+
resolve(did = this.did) { return this.keymaster.resolveDID(did); }
|
|
132
|
+
|
|
133
|
+
// ---- signing -------------------------------------------------------------------------
|
|
134
|
+
/** Sign any JSON object with this agent's DID key (adds a `signature` block). */
|
|
135
|
+
sign(obj) { return this.keymaster.addSignature(obj); }
|
|
136
|
+
/** Verify a signed JSON object; resolves the signer DID on the network. */
|
|
137
|
+
verify(signed) { return this.keymaster.verifySignature(signed); }
|
|
138
|
+
|
|
139
|
+
// ---- challenges ("every interaction is an invite") ------------------------------------
|
|
140
|
+
/**
|
|
141
|
+
* Create a challenge DID another agent/human must answer. Optionally require credentials:
|
|
142
|
+
* createChallenge({ credentials: [{ schema: SCHEMA_DID, issuers: [ISSUER_DID] }], callback })
|
|
143
|
+
*/
|
|
144
|
+
createChallenge(challenge = {}, options = {}) { return this.keymaster.createChallenge(challenge, options); }
|
|
145
|
+
/** Answer someone else's challenge DID; returns a response DID to send back. */
|
|
146
|
+
respondToChallenge(challengeDid, options = {}) { return this.keymaster.createResponse(challengeDid, options); }
|
|
147
|
+
/** Verify a response DID to a challenge you created. Result has .match, .responder, .vps... */
|
|
148
|
+
verifyResponse(responseDid, options = {}) { return this.keymaster.verifyResponse(responseDid, options); }
|
|
149
|
+
|
|
150
|
+
// ---- credentials -----------------------------------------------------------------------
|
|
151
|
+
/** Accept a credential issued to this agent (e.g. a purchase authorization from a SELF app). */
|
|
152
|
+
acceptCredential(credentialDid) { return this.keymaster.acceptCredential(credentialDid); }
|
|
153
|
+
listCredentials() { return this.keymaster.listCredentials(); }
|
|
154
|
+
getCredential(credentialDid) { return this.keymaster.getCredential(credentialDid); }
|
|
155
|
+
/** Publish a held credential to the DID manifest; reveal:true exposes its content publicly. */
|
|
156
|
+
publishCredential(credentialDid, { reveal = false } = {}) { return this.keymaster.publishCredential(credentialDid, { reveal }); }
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Find held credentials (decrypted) by schema and/or issuer - e.g. check that a human's
|
|
160
|
+
* DID authorized this agent to purchase: findCredentials({ schema: PURCHASE_SCHEMA, issuer: HUMAN_DID }).
|
|
161
|
+
* Also filters out credentials whose validUntil has passed.
|
|
162
|
+
*/
|
|
163
|
+
async findCredentials({ schema, issuer } = {}) {
|
|
164
|
+
const found = [];
|
|
165
|
+
for (const did of await this.listCredentials()) {
|
|
166
|
+
const vc = await this.getCredential(did).catch(() => null);
|
|
167
|
+
if (!vc) continue;
|
|
168
|
+
if (schema && !vc.type?.includes(schema)) continue;
|
|
169
|
+
if (issuer && vc.issuer !== issuer) continue;
|
|
170
|
+
if (vc.validUntil && Date.parse(vc.validUntil) < Date.now()) continue;
|
|
171
|
+
if (!(await this.keymaster.verifySignature(vc).catch(() => false))) continue;
|
|
172
|
+
found.push({ did, ...vc });
|
|
173
|
+
}
|
|
174
|
+
return found;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Issue a credential from this agent to `subjectDid` using a schema DID. Returns credential DID. */
|
|
178
|
+
async issueCredential(schemaDid, subjectDid, credential, options = {}) {
|
|
179
|
+
const bound = await this.keymaster.bindCredential(schemaDid, subjectDid, { credential, ...options });
|
|
180
|
+
return this.keymaster.issueCredential(bound, { registry: this.config.registry, ...options });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Self-attest SELF's Public Profile molecule with ONLY { publicName }, accept it,
|
|
185
|
+
* and publish it to the manifest with content revealed. Idempotent per name.
|
|
186
|
+
*/
|
|
187
|
+
async selfAttestPublicProfile(publicName) {
|
|
188
|
+
// Reuse an existing self-issued Public Profile with the same name if we already hold one.
|
|
189
|
+
let credentialDid;
|
|
190
|
+
for (const did of await this.listCredentials()) {
|
|
191
|
+
const vc = await this.getCredential(did).catch(() => null);
|
|
192
|
+
if (vc?.type?.includes(SELF_PUBLIC_PROFILE_SCHEMA) && vc.issuer === this.did && vc.credential?.publicName === publicName) { credentialDid = did; break; }
|
|
193
|
+
}
|
|
194
|
+
if (!credentialDid) {
|
|
195
|
+
credentialDid = await this.issueCredential(SELF_PUBLIC_PROFILE_SCHEMA, this.did, { publicName });
|
|
196
|
+
await waitForDid(this.keymaster, credentialDid);
|
|
197
|
+
await this.acceptCredential(credentialDid);
|
|
198
|
+
}
|
|
199
|
+
await this.publishCredential(credentialDid, { reveal: true });
|
|
200
|
+
const publicProfile = { publicName, credentialDid, schema: SELF_PUBLIC_PROFILE_SCHEMA };
|
|
201
|
+
writeState(this.config, { publicProfile });
|
|
202
|
+
return publicProfile;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---- backups ---------------------------------------------------------------------------
|
|
206
|
+
/**
|
|
207
|
+
* Two backups: (1) network - encrypted ID vault (first time) + encrypted wallet asset on the
|
|
208
|
+
* registry, linked from the mnemonic-derived seed bank DID; (2) local encrypted wallet file.
|
|
209
|
+
* Re-run after any wallet change (new credentials etc.).
|
|
210
|
+
*/
|
|
211
|
+
async backup() {
|
|
212
|
+
const doc = await this.resolve();
|
|
213
|
+
if (!doc.didDocumentData?.vault) await this.keymaster.backupId(this.config.name);
|
|
214
|
+
const walletBackupDid = await this.keymaster.backupWallet(this.config.registry);
|
|
215
|
+
ensurePrivateDir(this.config.paths.backups);
|
|
216
|
+
const file = path.join(this.config.paths.backups, `wallet-${new Date().toLocaleDateString('sv')}.json`);
|
|
217
|
+
writeSecret(file, JSON.stringify(await this.keymaster.exportEncryptedWallet(), null, 2));
|
|
218
|
+
writeState(this.config, { walletBackupDid, lastLocalBackup: file });
|
|
219
|
+
return { walletBackupDid, file };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Non-destructive restore test: restores (a) recovery phrase + network backup and
|
|
224
|
+
* (b) newest local backup file into throwaway temp wallets; checks the same DID, held
|
|
225
|
+
* credentials and a working signing key. Writes nothing to the network.
|
|
226
|
+
*/
|
|
227
|
+
async verifyBackups() {
|
|
228
|
+
const cfg = this.config;
|
|
229
|
+
const expectCreds = await this.listCredentials();
|
|
230
|
+
const results = [];
|
|
231
|
+
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mdip-verify-'));
|
|
232
|
+
const check = async (label, km) => {
|
|
233
|
+
let ok = false, detail = {};
|
|
234
|
+
try {
|
|
235
|
+
await km.setCurrentId(cfg.name);
|
|
236
|
+
const did = (await km.fetchIdInfo(cfg.name)).did;
|
|
237
|
+
const creds = await km.listCredentials();
|
|
238
|
+
const signed = await km.addSignature({ verify: label, at: Date.now() });
|
|
239
|
+
const sigOk = await km.verifySignature(signed);
|
|
240
|
+
const missing = expectCreds.filter(c => !creds.includes(c));
|
|
241
|
+
ok = did === this.did && missing.length === 0 && sigOk;
|
|
242
|
+
detail = { sameDid: did === this.did, credentials: creds.length, missingCredentials: missing.length, signatureVerifies: sigOk };
|
|
243
|
+
} catch (e) { detail = { error: String(e?.message || e) }; }
|
|
244
|
+
results.push({ test: label, pass: ok, ...detail });
|
|
245
|
+
};
|
|
246
|
+
try {
|
|
247
|
+
const km1 = await createKeymaster({ gatekeeperUrl: cfg.gatekeeperUrl, walletDir: path.join(tmpRoot, 'net'), passphrase: crypto.randomBytes(24).toString('base64url'), registry: cfg.registry, didPrefix: cfg.didPrefix });
|
|
248
|
+
await km1.newWallet(fs.readFileSync(cfg.paths.recoveryPhrase, 'utf8').trim(), true);
|
|
249
|
+
await km1.recoverWallet();
|
|
250
|
+
await check('recovery-phrase+network-backup', km1);
|
|
251
|
+
|
|
252
|
+
const files = fs.existsSync(cfg.paths.backups) ? fs.readdirSync(cfg.paths.backups).filter(f => f.endsWith('.json')).sort() : [];
|
|
253
|
+
if (files.length) {
|
|
254
|
+
const passphrase = fs.readFileSync(cfg.paths.passphrase, 'utf8').trim();
|
|
255
|
+
const km2 = await createKeymaster({ gatekeeperUrl: cfg.gatekeeperUrl, walletDir: path.join(tmpRoot, 'file'), passphrase, registry: cfg.registry, didPrefix: cfg.didPrefix });
|
|
256
|
+
const saved = await km2.saveWallet(JSON.parse(fs.readFileSync(path.join(cfg.paths.backups, files.at(-1)), 'utf8')), true);
|
|
257
|
+
if (saved) await check(`local-file:${files.at(-1)}`, km2);
|
|
258
|
+
else results.push({ test: 'local-file', pass: false, error: 'saveWallet failed' });
|
|
259
|
+
} else results.push({ test: 'local-file', pass: false, error: 'no local backup found' });
|
|
260
|
+
} finally {
|
|
261
|
+
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
262
|
+
}
|
|
263
|
+
return { pass: results.every(r => r.pass), results };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Check whether this DID (or another) is visible on SELF's public explorer. */
|
|
267
|
+
async explorerStatus(did = this.did) {
|
|
268
|
+
const res = await fetch(SELF_EXPLORER_API + did);
|
|
269
|
+
const body = await res.json().catch(() => null);
|
|
270
|
+
if (!body || typeof body === 'string') return { visible: false };
|
|
271
|
+
return { visible: true, version: body.didDocumentMetadata?.version, confirmed: body.didDocumentMetadata?.confirmed, manifest: Object.keys(body.didDocumentData?.manifest || {}) };
|
|
272
|
+
}
|
|
273
|
+
}
|