@messh/sdk 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/LICENSE +202 -0
- package/README.md +43 -2
- package/dist/errors.d.ts +23 -0
- package/dist/errors.js +32 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.js +151 -0
- package/dist/keys.d.ts +25 -0
- package/dist/keys.js +198 -0
- package/dist/verify.d.ts +116 -0
- package/dist/verify.js +333 -0
- package/dist/wba.d.ts +34 -0
- package/dist/wba.js +120 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @messh/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sign and verify HTTP requests as a [messh](https://messh.io) identity with **Web Bot Auth**: RFC 9421 HTTP Message Signatures, Ed25519, `tag="web-bot-auth"`. No runtime dependencies; Node 20+.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @messh/sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Sign (agent)
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { MesshClient, keyFile } from "@messh/sdk";
|
|
13
|
+
|
|
14
|
+
const client = await MesshClient.create({ identity: "mukul", key: keyFile("~/.ssh/id_ed25519") });
|
|
15
|
+
await client.fetch("https://api.example.com/deploy", { method: "POST", body: JSON.stringify({ env: "staging" }) });
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Use the ssh-ed25519 key you published with `messh publish`. The private key never leaves your machine.
|
|
19
|
+
|
|
20
|
+
## Agents and CI
|
|
21
|
+
|
|
22
|
+
Configure it with environment variables instead of code: `MESSH_IDENTITY`, `MESSH_KEY` (PEM, or base64 of PEM or PKCS#8 DER) or `MESSH_KEY_FILE`, and `MESSH_REGISTRY`. `whoami` checks the key is published, so a missing `messh publish` fails at startup with `not_published` instead of every API answering 401.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
const client = await MesshClient.fromEnv();
|
|
26
|
+
const me = await client.whoami(); // { identity, keyName, keyId, fingerprint, agentUrl }
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Passphrase-protected key? Load it into ssh-agent (`ssh-add`) and pass `key: sshAgent()`.
|
|
30
|
+
|
|
31
|
+
## Verify (API)
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { messhAuth, Verifier } from "@messh/sdk/verify";
|
|
35
|
+
|
|
36
|
+
app.use("/api", messhAuth({ trust: ["mukul"] })); // Express: mount before express.json(); then req.agent
|
|
37
|
+
|
|
38
|
+
const verifier = new Verifier({ trust: ["mukul"] }); // fetch-style runtimes (Workers, Hono, Next.js)
|
|
39
|
+
const agent = await verifier.verifyRequest(request);
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Full reference (every function, input and error code): https://github.com/messhio/messh/blob/main/sdk/README.md
|
|
43
|
+
|
|
44
|
+
License: Apache-2.0
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side error: invalid_identity, invalid_key, invalid_option,
|
|
3
|
+
* sign_failed; from whoami(): not_published, registry_unreachable.
|
|
4
|
+
*/
|
|
5
|
+
export declare class MesshError extends Error {
|
|
6
|
+
readonly code: string;
|
|
7
|
+
constructor(code: string, message: string);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Verification failure. Codes follow the messh spec: missing_signature,
|
|
11
|
+
* bad_signature, digest_mismatch, clock_skew, nonce_replayed, unknown_key
|
|
12
|
+
* (401); untrusted (403); body_too_large (413).
|
|
13
|
+
*/
|
|
14
|
+
export declare class VerifyError extends Error {
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly detail: string;
|
|
17
|
+
readonly status: number;
|
|
18
|
+
constructor(code: string, detail: string, status?: number);
|
|
19
|
+
toJSON(): {
|
|
20
|
+
error: string;
|
|
21
|
+
message: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side error: invalid_identity, invalid_key, invalid_option,
|
|
3
|
+
* sign_failed; from whoami(): not_published, registry_unreachable.
|
|
4
|
+
*/
|
|
5
|
+
export class MesshError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(`${code}: ${message}`);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = "MesshError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Verification failure. Codes follow the messh spec: missing_signature,
|
|
15
|
+
* bad_signature, digest_mismatch, clock_skew, nonce_replayed, unknown_key
|
|
16
|
+
* (401); untrusted (403); body_too_large (413).
|
|
17
|
+
*/
|
|
18
|
+
export class VerifyError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
detail;
|
|
21
|
+
status;
|
|
22
|
+
constructor(code, detail, status = 401) {
|
|
23
|
+
super(`${code}: ${detail}`);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.detail = detail;
|
|
26
|
+
this.status = status;
|
|
27
|
+
this.name = "VerifyError";
|
|
28
|
+
}
|
|
29
|
+
toJSON() {
|
|
30
|
+
return { error: this.code, message: this.detail };
|
|
31
|
+
}
|
|
32
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type KeySource } from "./keys.js";
|
|
2
|
+
export { MesshError, VerifyError } from "./errors.js";
|
|
3
|
+
export { keyEnv, keyFile, keySeed, sshAgent, type KeySource, type Signer } from "./keys.js";
|
|
4
|
+
export { fingerprint, thumbprint, type Directory, type JWK } from "./wba.js";
|
|
5
|
+
export declare const VERSION = "0.1.0";
|
|
6
|
+
export declare const DEFAULT_REGISTRY = "https://messh.io";
|
|
7
|
+
export interface ClientOptions {
|
|
8
|
+
/** messh username, e.g. "mukul". */
|
|
9
|
+
identity: string;
|
|
10
|
+
/** Signing key. Default: keyFile("~/.ssh/id_ed25519"). */
|
|
11
|
+
key?: KeySource;
|
|
12
|
+
/** messh registry base URL. Default: https://messh.io. */
|
|
13
|
+
registry?: string;
|
|
14
|
+
/** Signature lifetime in seconds. Default 60, max 300. */
|
|
15
|
+
expiresIn?: number;
|
|
16
|
+
/** Seconds since epoch (tests). */
|
|
17
|
+
clock?: () => number;
|
|
18
|
+
/** Nonce generator (tests). */
|
|
19
|
+
nonce?: () => string;
|
|
20
|
+
}
|
|
21
|
+
export interface SignInput {
|
|
22
|
+
method: string;
|
|
23
|
+
/** Absolute URL. */
|
|
24
|
+
url: string | URL;
|
|
25
|
+
body?: Uint8Array | string | null;
|
|
26
|
+
/** Host header, if different from the URL's host. */
|
|
27
|
+
host?: string;
|
|
28
|
+
}
|
|
29
|
+
/** This client's key as messh lists it: what an API will see. See {@link MesshClient.whoami}. */
|
|
30
|
+
export interface PublishedKey {
|
|
31
|
+
/** messh username, e.g. "mukul". */
|
|
32
|
+
identity: string;
|
|
33
|
+
/** The key's name on messh, e.g. "build-bot". */
|
|
34
|
+
keyName: string;
|
|
35
|
+
/** RFC 7638 thumbprint, sent as keyid. */
|
|
36
|
+
keyId: string;
|
|
37
|
+
/** SHA256:… of the SSH key. */
|
|
38
|
+
fingerprint: string;
|
|
39
|
+
/** Signature-Agent: <registry>/<identity>. */
|
|
40
|
+
agentUrl: string;
|
|
41
|
+
}
|
|
42
|
+
export declare class MesshClient {
|
|
43
|
+
readonly identity: string;
|
|
44
|
+
readonly registry: string;
|
|
45
|
+
readonly keyId: string;
|
|
46
|
+
/** SSH fingerprint of the signing key (SHA256:…), as `messh keys` and ssh-keygen -l print it. */
|
|
47
|
+
readonly fingerprint: string;
|
|
48
|
+
private readonly signer;
|
|
49
|
+
private readonly expiresIn;
|
|
50
|
+
private readonly clock;
|
|
51
|
+
private readonly nonce;
|
|
52
|
+
private constructor();
|
|
53
|
+
/** Create a client; loads the key once. */
|
|
54
|
+
static create(options: ClientOptions): Promise<MesshClient>;
|
|
55
|
+
/**
|
|
56
|
+
* Create a client from the environment, for agents and CI: MESSH_IDENTITY
|
|
57
|
+
* (required), MESSH_KEY (PEM, or base64 of PEM or PKCS#8 DER) or
|
|
58
|
+
* MESSH_KEY_FILE (default ~/.ssh/id_ed25519), and MESSH_REGISTRY.
|
|
59
|
+
* Options you pass win over the environment.
|
|
60
|
+
*/
|
|
61
|
+
static fromEnv(overrides?: Partial<ClientOptions>): Promise<MesshClient>;
|
|
62
|
+
/**
|
|
63
|
+
* Check that this client's key is published and active on messh, and how
|
|
64
|
+
* APIs will see it. Run it once at startup: it turns the most common setup
|
|
65
|
+
* mistake (an unpublished key, so every API answers 401 unknown_key) into a
|
|
66
|
+
* clear error. Throws MesshError not_published or registry_unreachable.
|
|
67
|
+
*/
|
|
68
|
+
whoami(): Promise<PublishedKey>;
|
|
69
|
+
/** Signature-Agent URL: <registry>/<identity>. */
|
|
70
|
+
get agent(): string;
|
|
71
|
+
/**
|
|
72
|
+
* Headers to add: Signature-Agent, Signature-Input, Signature and, with a
|
|
73
|
+
* body, Content-Digest. Sign last; don't change the request afterwards.
|
|
74
|
+
*/
|
|
75
|
+
sign(input: SignInput): Promise<Record<string, string>>;
|
|
76
|
+
/** Return a signed copy of a fetch Request. */
|
|
77
|
+
signRequest(request: Request): Promise<Request>;
|
|
78
|
+
/** fetch(), signed. Bodies must be strings or bytes (they're hashed). */
|
|
79
|
+
fetch(input: string | URL, init?: RequestInit): Promise<Response>;
|
|
80
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// @messh/sdk: sign HTTP requests as a messh identity (Web Bot Auth).
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import * as wba from "./wba.js";
|
|
5
|
+
import { MesshError } from "./errors.js";
|
|
6
|
+
import { keyEnv, keyFile, resolveKey } from "./keys.js";
|
|
7
|
+
export { MesshError, VerifyError } from "./errors.js";
|
|
8
|
+
export { keyEnv, keyFile, keySeed, sshAgent } from "./keys.js";
|
|
9
|
+
export { fingerprint, thumbprint } from "./wba.js";
|
|
10
|
+
export const VERSION = "0.1.0";
|
|
11
|
+
export const DEFAULT_REGISTRY = "https://messh.io";
|
|
12
|
+
const IDENTITY = /^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$/;
|
|
13
|
+
export class MesshClient {
|
|
14
|
+
identity;
|
|
15
|
+
registry;
|
|
16
|
+
keyId;
|
|
17
|
+
fingerprint;
|
|
18
|
+
signer;
|
|
19
|
+
expiresIn;
|
|
20
|
+
clock;
|
|
21
|
+
nonce;
|
|
22
|
+
constructor(identity, registry, keyId,
|
|
23
|
+
/** SSH fingerprint of the signing key (SHA256:…), as `messh keys` and ssh-keygen -l print it. */
|
|
24
|
+
fingerprint, signer, expiresIn, clock, nonce) {
|
|
25
|
+
this.identity = identity;
|
|
26
|
+
this.registry = registry;
|
|
27
|
+
this.keyId = keyId;
|
|
28
|
+
this.fingerprint = fingerprint;
|
|
29
|
+
this.signer = signer;
|
|
30
|
+
this.expiresIn = expiresIn;
|
|
31
|
+
this.clock = clock;
|
|
32
|
+
this.nonce = nonce;
|
|
33
|
+
}
|
|
34
|
+
/** Create a client; loads the key once. */
|
|
35
|
+
static async create(options) {
|
|
36
|
+
const { identity, registry = DEFAULT_REGISTRY, expiresIn = 60 } = options;
|
|
37
|
+
if (!IDENTITY.test(identity ?? ""))
|
|
38
|
+
throw new MesshError("invalid_identity", `${JSON.stringify(identity)} is not a messh username`);
|
|
39
|
+
if (!/^https?:\/\//.test(registry))
|
|
40
|
+
throw new MesshError("invalid_option", "registry must be an http(s) URL");
|
|
41
|
+
if (!(expiresIn >= 1 && expiresIn <= wba.MAX_LIFETIME))
|
|
42
|
+
throw new MesshError("invalid_option", "expiresIn must be 1..300 seconds");
|
|
43
|
+
const signer = await resolveKey(options.key ?? keyFile(`${homedir()}/.ssh/id_ed25519`));
|
|
44
|
+
const pub = await signer.publicKey();
|
|
45
|
+
return new MesshClient(identity, registry.replace(/\/+$/, ""), wba.thumbprint(pub), wba.fingerprint(pub), signer, expiresIn, options.clock ?? (() => Math.floor(Date.now() / 1000)), options.nonce ?? (() => randomBytes(16).toString("base64url")));
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Create a client from the environment, for agents and CI: MESSH_IDENTITY
|
|
49
|
+
* (required), MESSH_KEY (PEM, or base64 of PEM or PKCS#8 DER) or
|
|
50
|
+
* MESSH_KEY_FILE (default ~/.ssh/id_ed25519), and MESSH_REGISTRY.
|
|
51
|
+
* Options you pass win over the environment.
|
|
52
|
+
*/
|
|
53
|
+
static async fromEnv(overrides = {}) {
|
|
54
|
+
const env = process.env;
|
|
55
|
+
const identity = overrides.identity ?? env.MESSH_IDENTITY;
|
|
56
|
+
if (!identity)
|
|
57
|
+
throw new MesshError("invalid_identity", "set MESSH_IDENTITY to your messh username, or pass identity");
|
|
58
|
+
const key = overrides.key ?? (env.MESSH_KEY ? keyEnv("MESSH_KEY") : env.MESSH_KEY_FILE ? keyFile(env.MESSH_KEY_FILE) : undefined);
|
|
59
|
+
return MesshClient.create({ ...overrides, identity, key, registry: overrides.registry ?? (env.MESSH_REGISTRY || undefined) });
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Check that this client's key is published and active on messh, and how
|
|
63
|
+
* APIs will see it. Run it once at startup: it turns the most common setup
|
|
64
|
+
* mistake (an unpublished key, so every API answers 401 unknown_key) into a
|
|
65
|
+
* clear error. Throws MesshError not_published or registry_unreachable.
|
|
66
|
+
*/
|
|
67
|
+
async whoami() {
|
|
68
|
+
const url = `${this.agent}${wba.DIRECTORY_PATH}`;
|
|
69
|
+
let res;
|
|
70
|
+
try {
|
|
71
|
+
res = await fetch(url, {
|
|
72
|
+
headers: { accept: "application/http-message-signatures-directory+json, application/json", "user-agent": `messh-js/${VERSION}` },
|
|
73
|
+
signal: AbortSignal.timeout(10_000),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
throw new MesshError("registry_unreachable", `can't reach ${this.registry}: ${e.message}`);
|
|
78
|
+
}
|
|
79
|
+
if (res.status === 404) {
|
|
80
|
+
throw new MesshError("not_published", `${this.registry} has no user ${this.identity}; sign up, then publish this key (${this.fingerprint}) with messh publish`);
|
|
81
|
+
}
|
|
82
|
+
const dir = res.ok ? (await res.json().catch(() => null)) : null;
|
|
83
|
+
if (!dir)
|
|
84
|
+
throw new MesshError("registry_unreachable", `${url} answered HTTP ${res.status} without a key directory`);
|
|
85
|
+
const key = (dir.keys ?? []).find((k) => k.kid === this.keyId);
|
|
86
|
+
if (!key) {
|
|
87
|
+
throw new MesshError("not_published", `this key (${this.fingerprint}) isn't an active key of ${this.agent}; publish it with messh publish --key <key>.pub --name <name>`);
|
|
88
|
+
}
|
|
89
|
+
return { identity: this.identity, keyName: key.messh_name ?? "", keyId: this.keyId, fingerprint: key.messh_fingerprint ?? this.fingerprint, agentUrl: this.agent };
|
|
90
|
+
}
|
|
91
|
+
/** Signature-Agent URL: <registry>/<identity>. */
|
|
92
|
+
get agent() {
|
|
93
|
+
return `${this.registry}/${this.identity}`;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Headers to add: Signature-Agent, Signature-Input, Signature and, with a
|
|
97
|
+
* body, Content-Digest. Sign last; don't change the request afterwards.
|
|
98
|
+
*/
|
|
99
|
+
async sign(input) {
|
|
100
|
+
const u = new URL(input.url);
|
|
101
|
+
const agentHeader = wba.quote(this.agent);
|
|
102
|
+
const comps = [
|
|
103
|
+
["@method", input.method.toUpperCase()],
|
|
104
|
+
["@authority", (input.host ?? u.host).toLowerCase()],
|
|
105
|
+
["@path", u.pathname || "/"],
|
|
106
|
+
];
|
|
107
|
+
if (u.search)
|
|
108
|
+
comps.push(["@query", u.search]);
|
|
109
|
+
const headers = { "Signature-Agent": agentHeader };
|
|
110
|
+
if (input.body && input.body.length) {
|
|
111
|
+
const data = typeof input.body === "string" ? Buffer.from(input.body) : input.body;
|
|
112
|
+
headers["Content-Digest"] = wba.contentDigest(data);
|
|
113
|
+
comps.push(["content-digest", headers["Content-Digest"]]);
|
|
114
|
+
}
|
|
115
|
+
comps.push(["signature-agent", agentHeader]);
|
|
116
|
+
const created = Math.floor(this.clock());
|
|
117
|
+
const params = wba.params(comps.map(([n]) => n), created, created + this.expiresIn, this.keyId, this.nonce());
|
|
118
|
+
let sig;
|
|
119
|
+
try {
|
|
120
|
+
sig = await this.signer.sign(wba.base(comps, params));
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
throw new MesshError("sign_failed", e.message);
|
|
124
|
+
}
|
|
125
|
+
headers["Signature-Input"] = `${wba.LABEL}=${params}`;
|
|
126
|
+
headers["Signature"] = `${wba.LABEL}=:${Buffer.from(sig).toString("base64")}:`;
|
|
127
|
+
return headers;
|
|
128
|
+
}
|
|
129
|
+
/** Return a signed copy of a fetch Request. */
|
|
130
|
+
async signRequest(request) {
|
|
131
|
+
const body = request.body ? new Uint8Array(await request.clone().arrayBuffer()) : undefined;
|
|
132
|
+
const headers = new Headers(request.headers);
|
|
133
|
+
for (const [k, v] of Object.entries(await this.sign({ method: request.method, url: request.url, body })))
|
|
134
|
+
headers.set(k, v);
|
|
135
|
+
return new Request(request, { headers, body });
|
|
136
|
+
}
|
|
137
|
+
/** fetch(), signed. Bodies must be strings or bytes (they're hashed). */
|
|
138
|
+
async fetch(input, init = {}) {
|
|
139
|
+
const body = init.body;
|
|
140
|
+
if (body != null && typeof body !== "string" && !(body instanceof Uint8Array)) {
|
|
141
|
+
throw new MesshError("sign_failed", "body must be a string or Uint8Array to be signed");
|
|
142
|
+
}
|
|
143
|
+
const headers = new Headers(init.headers);
|
|
144
|
+
const method = (init.method ?? (body != null ? "POST" : "GET")).toUpperCase();
|
|
145
|
+
for (const [k, v] of Object.entries(await this.sign({ method, url: input, body: body })))
|
|
146
|
+
headers.set(k, v);
|
|
147
|
+
if (!headers.has("user-agent"))
|
|
148
|
+
headers.set("user-agent", `messh-js/${VERSION}`);
|
|
149
|
+
return fetch(input, { ...init, method, headers });
|
|
150
|
+
}
|
|
151
|
+
}
|
package/dist/keys.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Implement to sign in a KMS, HSM or ssh-agent. */
|
|
2
|
+
export interface Signer {
|
|
3
|
+
/** Raw 32-byte Ed25519 public key. */
|
|
4
|
+
publicKey(): Uint8Array | Promise<Uint8Array>;
|
|
5
|
+
/** 64-byte Ed25519 signature over data. */
|
|
6
|
+
sign(data: Uint8Array): Uint8Array | Promise<Uint8Array>;
|
|
7
|
+
}
|
|
8
|
+
/** A Signer, or something that loads one. */
|
|
9
|
+
export type KeySource = Signer | (() => Promise<Signer>);
|
|
10
|
+
/** Unencrypted ssh-ed25519 OpenSSH key or PKCS#8 PEM, e.g. ~/.ssh/id_ed25519. */
|
|
11
|
+
export declare function keyFile(path: string): () => Promise<Signer>;
|
|
12
|
+
/**
|
|
13
|
+
* A key held by ssh-agent, such as a passphrase-protected key you added with
|
|
14
|
+
* ssh-add. The private key stays in the agent. With several Ed25519 keys
|
|
15
|
+
* loaded, pass the fingerprint (SHA256:…) of the one you published.
|
|
16
|
+
*/
|
|
17
|
+
export declare function sshAgent(options?: {
|
|
18
|
+
fingerprint?: string;
|
|
19
|
+
socket?: string;
|
|
20
|
+
}): () => Promise<Signer>;
|
|
21
|
+
/** Key in an environment variable: PEM text, or base64 of PEM or PKCS#8 DER. */
|
|
22
|
+
export declare function keyEnv(name: string): () => Promise<Signer>;
|
|
23
|
+
/** Raw 32-byte Ed25519 seed. */
|
|
24
|
+
export declare function keySeed(seed: Uint8Array): () => Promise<Signer>;
|
|
25
|
+
export declare function resolveKey(source: KeySource): Promise<Signer>;
|