@agentproto/secrets 0.1.0-alpha.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 agentproto 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.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -18,6 +18,58 @@ const x = defineSecrets({
18
18
  })
19
19
  ```
20
20
 
21
+ ## Exposure surface (`@agentproto/secrets/exposure`)
22
+
23
+ The manifest says *which* secrets exist; an **exposure** says *how* a resolved
24
+ secret reaches a runtime. `SecretExposure` is a discriminated union — one
25
+ `kind` per delivery mechanism, so consumers filter with the `isExposureKind`
26
+ guard and handle each with one switch case:
27
+
28
+ | `kind` | Delivers the secret as… |
29
+ | --- | --- |
30
+ | `env` | an environment variable on the agent process |
31
+ | `file` | a file written into the workspace |
32
+ | `egress-substitute` | a `$$SECRET[NAME]$$` placeholder substituted on egress |
33
+ | `mcp-header` | an HTTP **auth header** on an MCP server's transport |
34
+
35
+ ```ts
36
+ import { isExposureKind, type SecretExposure } from "@agentproto/secrets/exposure"
37
+
38
+ const headerExposures = exposures.filter(e => isExposureKind(e, "mcp-header"))
39
+ ```
40
+
41
+ ### `mcp-header` — brokered MCP auth
42
+
43
+ ```ts
44
+ interface McpHeaderExposure {
45
+ kind: "mcp-header"
46
+ credentialPath: string // broker path: "<providerId>" or "<providerId>/<account>"
47
+ server?: string // optional upstream override, forwarded to the broker
48
+ }
49
+ ```
50
+
51
+ `resolveMcpHeaderExposure(exposure, resolver, { signal })` turns that path into
52
+ a ready-to-use header map. The `resolver` is a **structural**
53
+ `McpHeaderResolver` (`resolveHeaders({ path, server?, signal? })`) — the
54
+ `CredentialBroker` from `@agentproto/auth` satisfies it with no adapter, so
55
+ this package stays **dependency-free of `auth`** while still driving it.
56
+
57
+ Every resolved header **value** is run through `assertSafeSecretValue` before
58
+ return — a value containing CR/LF/NUL is rejected, closing off header-injection
59
+ (a smuggled newline can't append extra header lines onto the transport).
60
+
61
+ ```ts
62
+ import { resolveMcpHeaderExposure } from "@agentproto/secrets/exposure"
63
+ import { CredentialBroker } from "@agentproto/auth"
64
+
65
+ const headers = await resolveMcpHeaderExposure(exposure, broker, { signal })
66
+ // → { Authorization: "Bearer …" }, guarded
67
+ ```
68
+
69
+ The same guard (`assertSafeSecretValue`) and the `$$SECRET[NAME]$$` engine
70
+ (`substituteSecrets`, `SECRET_PLACEHOLDER_PATTERN`, `formatPlaceholder`) are
71
+ exported from this subpath for the `egress-substitute` path.
72
+
21
73
  ## License
22
74
 
23
75
  MIT — see [LICENSE](./LICENSE).
@@ -1,4 +1,17 @@
1
1
  #!/usr/bin/env node
2
- // Thin launcher — the built CLI runs on import. Kept separate so the shebang
3
- // lives on a checked-in file rather than fighting the bundler's per-entry output.
4
- import "../dist/cli.mjs"
2
+ // Thin launcher — invokes the built CLI's exported `main`. Kept separate so
3
+ // the shebang lives on a checked-in file rather than fighting the bundler's
4
+ // per-entry output. `main` is exported (not run at import time) so tests can
5
+ // import `cli.ts`'s helpers without triggering a real CLI invocation.
6
+ import { main } from "../dist/cli.mjs"
7
+
8
+ main()
9
+ .then(code => {
10
+ process.exitCode = code
11
+ })
12
+ .catch(err => {
13
+ process.stderr.write(
14
+ `agentproto-secrets: ${err instanceof Error ? err.message : String(err)}\n`
15
+ )
16
+ process.exitCode = 1
17
+ })
@@ -0,0 +1,126 @@
1
+ import { generateKeyPairSync, createHash, createPrivateKey, sign, createPublicKey, verify } from 'crypto';
2
+ import { readFile, mkdir, writeFile, chmod, rename } from 'fs/promises';
3
+ import { dirname, join, basename } from 'path';
4
+
5
+ /**
6
+ * @agentproto/secrets v0.1.0-alpha
7
+ * AIP-19 SECRETS.md `defineSecrets` reference implementation.
8
+ */
9
+
10
+ var IDENTITY_VERSION = 1;
11
+ var IdentityError = class extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "IdentityError";
15
+ }
16
+ };
17
+ function generateIdentity() {
18
+ const x = generateKeyPairSync("x25519");
19
+ const ed = generateKeyPairSync("ed25519");
20
+ return {
21
+ v: IDENTITY_VERSION,
22
+ x25519: {
23
+ pub: x.publicKey.export({ type: "spki", format: "der" }).toString("base64"),
24
+ priv: x.privateKey.export({ type: "pkcs8", format: "der" }).toString("base64")
25
+ },
26
+ ed25519: {
27
+ pub: ed.publicKey.export({ type: "spki", format: "der" }).toString("base64"),
28
+ priv: ed.privateKey.export({ type: "pkcs8", format: "der" }).toString("base64")
29
+ },
30
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
31
+ };
32
+ }
33
+ function identityFingerprint(x25519Pub) {
34
+ return createHash("sha256").update(Buffer.from(x25519Pub, "base64")).digest("hex").slice(0, 16);
35
+ }
36
+ function isEnoent(err) {
37
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
38
+ }
39
+ function isRecord(v) {
40
+ return typeof v === "object" && v !== null;
41
+ }
42
+ function isKeyPair(kp) {
43
+ return isRecord(kp) && typeof kp["pub"] === "string" && typeof kp["priv"] === "string";
44
+ }
45
+ function isDaemonIdentity(value) {
46
+ if (!isRecord(value)) return false;
47
+ if (value["v"] !== IDENTITY_VERSION) return false;
48
+ if (typeof value["createdAt"] !== "string") return false;
49
+ return isKeyPair(value["x25519"]) && isKeyPair(value["ed25519"]);
50
+ }
51
+ async function loadOrCreateIdentity(filePath) {
52
+ try {
53
+ const raw = await readFile(filePath, "utf8");
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(raw);
57
+ } catch {
58
+ throw new IdentityError(
59
+ `identity file ${filePath} is not valid JSON \u2014 refusing to overwrite; move it aside to regenerate`
60
+ );
61
+ }
62
+ if (!isDaemonIdentity(parsed)) {
63
+ throw new IdentityError(
64
+ `identity file ${filePath} is malformed or an unsupported version \u2014 refusing to overwrite; move it aside to regenerate`
65
+ );
66
+ }
67
+ return parsed;
68
+ } catch (err) {
69
+ if (!isEnoent(err)) throw err;
70
+ }
71
+ const identity = generateIdentity();
72
+ await persistIdentity(filePath, identity);
73
+ return identity;
74
+ }
75
+ async function persistIdentity(filePath, identity) {
76
+ const dir = dirname(filePath);
77
+ await mkdir(dir, { recursive: true });
78
+ const tmp = join(dir, `.${basename(filePath)}.tmp-${process.pid}`);
79
+ await writeFile(tmp, JSON.stringify(identity, null, 2) + "\n", {
80
+ encoding: "utf8",
81
+ mode: 384
82
+ });
83
+ await chmod(tmp, 384).catch(() => {
84
+ });
85
+ await rename(tmp, filePath);
86
+ }
87
+ function signTranscript(ed25519Priv, transcript) {
88
+ let priv;
89
+ try {
90
+ priv = createPrivateKey({
91
+ key: Buffer.from(ed25519Priv, "base64"),
92
+ format: "der",
93
+ type: "pkcs8"
94
+ });
95
+ } catch {
96
+ throw new IdentityError("invalid ed25519 private key");
97
+ }
98
+ return sign(null, Buffer.from(transcript), priv).toString("base64");
99
+ }
100
+ function verifyTranscript(ed25519Pub, transcript, signature) {
101
+ let pub;
102
+ try {
103
+ pub = createPublicKey({
104
+ key: Buffer.from(ed25519Pub, "base64"),
105
+ format: "der",
106
+ type: "spki"
107
+ });
108
+ } catch {
109
+ throw new IdentityError("invalid ed25519 public key");
110
+ }
111
+ let sig;
112
+ try {
113
+ sig = Buffer.from(signature, "base64");
114
+ } catch {
115
+ return false;
116
+ }
117
+ try {
118
+ return verify(null, Buffer.from(transcript), pub, sig);
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ export { IDENTITY_VERSION, IdentityError, generateIdentity, identityFingerprint, loadOrCreateIdentity, signTranscript, verifyTranscript };
125
+ //# sourceMappingURL=chunk-2DL6W33G.mjs.map
126
+ //# sourceMappingURL=chunk-2DL6W33G.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/identity/index.ts"],"names":["edSign","edVerify"],"mappings":";;;;;;;;;AAiCO,IAAM,gBAAA,GAAmB;AAIzB,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AA+BO,SAAS,gBAAA,GAAmC;AACjD,EAAA,MAAM,CAAA,GAAI,oBAAoB,QAAQ,CAAA;AACtC,EAAA,MAAM,EAAA,GAAK,oBAAoB,SAAS,CAAA;AACxC,EAAA,OAAO;AAAA,IACL,CAAA,EAAG,gBAAA;AAAA,IACH,MAAA,EAAQ;AAAA,MACN,GAAA,EAAK,CAAA,CAAE,SAAA,CAAU,MAAA,CAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,KAAA,EAAO,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAA;AAAA,MAC1E,IAAA,EAAM,CAAA,CAAE,UAAA,CAAW,MAAA,CAAO,EAAE,IAAA,EAAM,OAAA,E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D;AACA,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAA,CAAO,IAAA,CAAK,SAAA,EAAW,QAAQ,CAAA;AAAA,EACvC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IAAI;AACF,IAAA,OAAOC,OAAS,IAAA,EAAM,MAAA,CAAO,KAAK,UAAU,CAAA,EAAG,KAAK,GAAG,CAAA;AAAA,EACzD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-2DL6W33G.mjs","sourcesContent":["/**\n * @agentproto/secrets/identity — the daemon's persistent cryptographic\n * identity for E2E pairing (design: PAIRING / DESIGN §1).\n *\n * A daemon that accepts pairings needs a stable identity a client can pin:\n * - an **X25519** keypair for key agreement (the client seals its hello to\n * this key, and it is one of the two ECDH inputs to the session key), and\n * - an **Ed25519** keypair for authenticity (the daemon signs the handshake\n * transcript so the client — who learned the public halves out-of-band via\n * the offer URL — can prove it is really talking to the daemon it scanned,\n * not an evil rendezvous in the middle).\n *\n * Both keypairs are stored base64-DER (SPKI public / PKCS8 private), the exact\n * shape `@agentproto/secrets/seal` already uses, so the identity file travels\n * as plain JSON and the seal box can consume the X25519 public half verbatim.\n *\n * Everything here is `node:crypto` — X25519, Ed25519, SHA-256 — so the package\n * keeps its zero-native-dependency footprint. The private halves never leave\n * the identity file (mode 0600) and are never logged.\n */\n\nimport {\n generateKeyPairSync,\n createPublicKey,\n createPrivateKey,\n createHash,\n sign as edSign,\n verify as edVerify,\n} from \"node:crypto\"\nimport { mkdir, readFile, writeFile, chmod, rename } from \"node:fs/promises\"\nimport { dirname, join, basename } from \"node:path\"\n\n/** Current identity-file schema version. */\nexport const IDENTITY_VERSION = 1 as const\n\n/** Raised for every identity load/generate/sign/verify failure. The message\n * is safe to surface — it never contains private key material. */\nexport class IdentityError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"IdentityError\"\n }\n}\n\n/** One keypair, both halves base64-DER. Public = SPKI, private = PKCS8. */\nexport interface IdentityKeyPair {\n /** base64 DER (SPKI) public key — publishable. */\n pub: string\n /** base64 DER (PKCS8) private key — secret. */\n priv: string\n}\n\n/**\n * A daemon's persistent identity. Serialized verbatim to\n * `~/.agentproto/identity.json` (0600). The `x25519` public half is the key a\n * client seals its hello to; the `ed25519` public half is the key a client\n * verifies the daemon's transcript signature against. Both public halves are\n * carried in the offer URL.\n */\nexport interface DaemonIdentity {\n v: typeof IDENTITY_VERSION\n /** Encryption / key-agreement keypair. */\n x25519: IdentityKeyPair\n /** Signing / authenticity keypair. */\n ed25519: IdentityKeyPair\n /** ISO-8601 creation timestamp. */\n createdAt: string\n}\n\n/**\n * Mint a fresh daemon identity: one X25519 keypair (encryption) and one\n * Ed25519 keypair (signing). Called lazily on first `pair offer`.\n */\nexport function generateIdentity(): DaemonIdentity {\n const x = generateKeyPairSync(\"x25519\")\n const ed = generateKeyPairSync(\"ed25519\")\n return {\n v: IDENTITY_VERSION,\n x25519: {\n pub: x.publicKey.export({ type: \"spki\", format: \"der\" }).toString(\"base64\"),\n priv: x.privateKey.export({ type: \"pkcs8\", format: \"der\" }).toString(\"base64\"),\n },\n ed25519: {\n pub: ed.publicKey.export({ type: \"spki\", format: \"der\" }).toString(\"base64\"),\n priv: ed.privateKey.export({ type: \"pkcs8\", format: \"der\" }).toString(\"base64\"),\n },\n createdAt: new Date().toISOString(),\n }\n}\n\n/**\n * Stable short identifier for a daemon, derived from its X25519 public key —\n * the same construction as `sealKeyId` in `@agentproto/secrets/seal` (first 16\n * hex of `sha256(pub DER)`). Displayed everywhere a human confirms identity\n * (offer QR, `pair accept`, `pair ls`). Not a secret.\n */\nexport function identityFingerprint(x25519Pub: string): string {\n return createHash(\"sha256\")\n .update(Buffer.from(x25519Pub, \"base64\"))\n .digest(\"hex\")\n .slice(0, 16)\n}\n\n/** True for a filesystem \"no such file\" error, without an unchecked cast. */\nfunction isEnoent(err: unknown): boolean {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null\n}\n\nfunction isKeyPair(kp: unknown): boolean {\n return isRecord(kp) && typeof kp[\"pub\"] === \"string\" && typeof kp[\"priv\"] === \"string\"\n}\n\nfunction isDaemonIdentity(value: unknown): value is DaemonIdentity {\n if (!isRecord(value)) return false\n if (value[\"v\"] !== IDENTITY_VERSION) return false\n if (typeof value[\"createdAt\"] !== \"string\") return false\n return isKeyPair(value[\"x25519\"]) && isKeyPair(value[\"ed25519\"])\n}\n\n/**\n * Load the daemon identity from `filePath`, creating it on first use. The\n * caller supplies the path (typically `~/.agentproto/identity.json`) so this\n * module stays free of any home-dir policy.\n *\n * The private halves are secret, so a freshly created file is written 0600 and\n * atomically (temp file in the same directory + `rename`, so a crash mid-write\n * can never leave a half-written identity or a world-readable window). A\n * malformed existing file is a hard error — never silently overwritten, since\n * that would rotate the daemon's identity and orphan every existing pairing.\n */\nexport async function loadOrCreateIdentity(\n filePath: string\n): Promise<DaemonIdentity> {\n try {\n const raw = await readFile(filePath, \"utf8\")\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new IdentityError(\n `identity file ${filePath} is not valid JSON — refusing to overwrite; ` +\n `move it aside to regenerate`\n )\n }\n if (!isDaemonIdentity(parsed)) {\n throw new IdentityError(\n `identity file ${filePath} is malformed or an unsupported version — ` +\n `refusing to overwrite; move it aside to regenerate`\n )\n }\n return parsed\n } catch (err) {\n if (!isEnoent(err)) throw err\n // ENOENT → first run; fall through to lazy creation below.\n }\n\n const identity = generateIdentity()\n await persistIdentity(filePath, identity)\n return identity\n}\n\n/** Atomic 0600 write: serialize to a sibling temp file, chmod it before it\n * holds any secret bytes, then rename over the target. */\nasync function persistIdentity(\n filePath: string,\n identity: DaemonIdentity\n): Promise<void> {\n const dir = dirname(filePath)\n await mkdir(dir, { recursive: true })\n const tmp = join(dir, `.${basename(filePath)}.tmp-${process.pid}`)\n await writeFile(tmp, JSON.stringify(identity, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n })\n // Belt-and-suspenders: writeFile's mode is subject to umask on some\n // platforms, so tighten explicitly before the file is visible at its\n // final name. Windows / mounts that ignore chmod fall back to the\n // already-private user profile dir.\n await chmod(tmp, 0o600).catch(() => {})\n await rename(tmp, filePath)\n}\n\n/**\n * Sign a handshake transcript with the daemon's Ed25519 private key. Returns a\n * base64 signature. `transcript` is the exact bytes both sides agree on\n * (`sha256(e_pub ‖ ct₀ ‖ d_e_pub)`); signing it — not the raw messages — is\n * what binds the daemon's authenticity to the whole exchange.\n */\nexport function signTranscript(\n ed25519Priv: string,\n transcript: Uint8Array\n): string {\n let priv\n try {\n priv = createPrivateKey({\n key: Buffer.from(ed25519Priv, \"base64\"),\n format: \"der\",\n type: \"pkcs8\",\n })\n } catch {\n throw new IdentityError(\"invalid ed25519 private key\")\n }\n // Ed25519 takes a null digest algorithm — it hashes internally.\n return edSign(null, Buffer.from(transcript), priv).toString(\"base64\")\n}\n\n/**\n * Verify a transcript signature against a daemon's Ed25519 public key. Returns\n * a boolean — never throws on a bad signature (only on a structurally invalid\n * key), so callers branch on the result rather than a control-flow exception.\n */\nexport function verifyTranscript(\n ed25519Pub: string,\n transcript: Uint8Array,\n signature: string\n): boolean {\n let pub\n try {\n pub = createPublicKey({\n key: Buffer.from(ed25519Pub, \"base64\"),\n format: \"der\",\n type: \"spki\",\n })\n } catch {\n throw new IdentityError(\"invalid ed25519 public key\")\n }\n let sig: Buffer\n try {\n sig = Buffer.from(signature, \"base64\")\n } catch {\n return false\n }\n try {\n return edVerify(null, Buffer.from(transcript), pub, sig)\n } catch {\n return false\n }\n}\n"]}
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,48 @@
1
+ /**
2
+ * agentproto-secrets — a small CLI over the seal primitive + provision flow.
3
+ *
4
+ * agentproto-secrets keygen mint a sealing keypair (JSON)
5
+ * agentproto-secrets seal --pubkey <b64> [src] seal a value -> sealed blob
6
+ * agentproto-secrets unseal --privkey <b64> [blob] open a sealed blob -> plaintext
7
+ * agentproto-secrets provision --provider P --method M \
8
+ * --seal-key-url URL --install-url URL [--header 'K: V']... [src]
9
+ * seal a local credential and
10
+ * install it into a vault,
11
+ * carrying only ciphertext
12
+ *
13
+ * credential source [src]: --from-file <path> [--json-path a.b.c] | --from-env <VAR>
14
+ *
15
+ * Vendor-neutral: `provision` takes the server's URLs + auth headers as flags.
16
+ * The plaintext credential is read, sealed, and sent — it is never printed.
17
+ * When `--header` is omitted and `--provider` names an auth provider
18
+ * registered in `@agentproto/auth`, the Authorization header is instead
19
+ * resolved via `CredentialBroker` (this is the only file in this package
20
+ * that imports `@agentproto/auth` — see `ProvisionAuthDeps` below).
21
+ */
22
+ /** Structural shape `CredentialBroker` satisfies — kept local (rather than
23
+ * importing the class as a type) so tests can inject a fake without touching
24
+ * Keychain or the network. */
25
+ interface AuthHeaderResolver {
26
+ resolveHeaders(o: {
27
+ path: string;
28
+ audience?: string;
29
+ server?: string;
30
+ signal?: AbortSignal;
31
+ }): Promise<Record<string, string>>;
32
+ }
33
+ interface ProvisionAuthDeps {
34
+ /** Whether `providerId` is a known `@agentproto/auth` auth provider. */
35
+ isRegistered(providerId: string): boolean;
36
+ resolver: AuthHeaderResolver;
37
+ }
38
+ /**
39
+ * Resolve the Authorization (etc.) headers a provision request carries.
40
+ * `--header` is an explicit override — when present, the broker is never
41
+ * consulted. Otherwise, a `--provider` registered in `@agentproto/auth`
42
+ * resolves its headers via the broker; an unregistered provider degrades to
43
+ * `explicitHeaders` (empty when none were passed) rather than failing.
44
+ */
45
+ declare function resolveProvisionHeaders(provider: string, explicitHeaders: string[], deps?: ProvisionAuthDeps): Promise<Record<string, string>>;
46
+ declare function main(): Promise<number>;
1
47
 
2
- export { }
48
+ export { type AuthHeaderResolver, type ProvisionAuthDeps, main, resolveProvisionHeaders };
package/dist/cli.mjs CHANGED
@@ -1,13 +1,12 @@
1
1
  import { listRecipeIds, resolveRecipeMethod, resolveSourceSpec } from './chunk-NEGXQWE5.mjs';
2
2
  import { httpTarget, provisionSealed, resolveCredential } from './chunk-NLZ5HXGO.mjs';
3
3
  import { unseal, seal, generateSealKeyPair, sealKeyId } from './chunk-MVHOJPML.mjs';
4
+ import { CredentialBroker, getAuthProvider, KeychainStore } from '@agentproto/auth';
4
5
 
5
6
  /**
6
7
  * @agentproto/secrets v0.1.0-alpha
7
8
  * AIP-19 SECRETS.md `defineSecrets` reference implementation.
8
9
  */
9
-
10
- // src/cli.ts
11
10
  function parse(argv) {
12
11
  const positionals = [];
13
12
  const flags = {};
@@ -90,6 +89,23 @@ function parseHeaders(raw) {
90
89
  }
91
90
  return out;
92
91
  }
92
+ function defaultProvisionAuthDeps() {
93
+ return {
94
+ isRegistered: (id) => getAuthProvider(id) !== void 0,
95
+ resolver: new CredentialBroker({
96
+ store: new KeychainStore(),
97
+ getProvider: getAuthProvider
98
+ })
99
+ };
100
+ }
101
+ async function resolveProvisionHeaders(provider, explicitHeaders, deps) {
102
+ const parsed = parseHeaders(explicitHeaders);
103
+ if (explicitHeaders.length > 0) return parsed;
104
+ const { isRegistered, resolver } = deps ?? defaultProvisionAuthDeps();
105
+ if (!isRegistered(provider)) return parsed;
106
+ const brokered = await resolver.resolveHeaders({ path: provider, audience: "api" });
107
+ return { ...brokered, ...parsed };
108
+ }
93
109
  var USAGE = `agentproto-secrets \u2014 seal secrets and install them into a vault
94
110
 
95
111
  keygen mint a sealing keypair (JSON to stdout)
@@ -150,11 +166,13 @@ async function main() {
150
166
  } catch (err) {
151
167
  return fail(err instanceof Error ? err.message : String(err));
152
168
  }
153
- const target = httpTarget({
154
- sealKeyUrl,
155
- installUrl,
156
- headers: parseHeaders(args.headers)
157
- });
169
+ let headers;
170
+ try {
171
+ headers = await resolveProvisionHeaders(provider, args.headers);
172
+ } catch (err) {
173
+ return fail(err instanceof Error ? err.message : String(err));
174
+ }
175
+ const target = httpTarget({ sealKeyUrl, installUrl, headers });
158
176
  try {
159
177
  const out = await provisionSealed({
160
178
  target,
@@ -190,14 +208,7 @@ function fail(message) {
190
208
  `);
191
209
  return 1;
192
210
  }
193
- main().then((code) => {
194
- process.exitCode = code;
195
- }).catch((err) => {
196
- process.stderr.write(
197
- `agentproto-secrets: ${err instanceof Error ? err.message : String(err)}
198
- `
199
- );
200
- process.exitCode = 1;
201
- });
211
+
212
+ export { main, resolveProvisionHeaders };
202
213
  //# sourceMappingURL=cli.mjs.map
203
214
  //# sourceMappingURL=cli.mjs.map