@calimero-network/mero-js 19.14.1 → 19.16.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.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Assemble the credential a node reads from `X-Calimero-Proof`.
3
+ *
4
+ * A request-carried proof is three links, and the node needs all of them in one
5
+ * header: the account root certified the device, the device (optionally)
6
+ * certified a short-lived session key, and that key signed THIS request. Each
7
+ * link is minted by its own function here — {@link signDeviceCert},
8
+ * {@link signLoginStatement}, {@link signRequest} — and each already returns
9
+ * the borsh encoding of the Rust type the node deserializes. Rust's
10
+ * `CallerProof` is a plain struct of those three fields, and borsh writes a
11
+ * struct as its fields back to back, so assembling the header is concatenation
12
+ * rather than a fourth encoder.
13
+ *
14
+ * That is worth stating because it is load-bearing and it is not obvious: if it
15
+ * were re-encoded here there would be a second spelling of a signed structure,
16
+ * able to disagree with the one that was signed. `caller-proof.test.ts` pins the
17
+ * concatenation against bytes produced by core itself.
18
+ */
19
+ /** The three links, each already hex-encoded by the function that signed it. */
20
+ export interface CallerProofInput {
21
+ /**
22
+ * `signDeviceCert(...)` — the account root's certificate over the device key,
23
+ * with the genesis that names the account.
24
+ */
25
+ credential: string;
26
+ /**
27
+ * `signLoginStatement(...)`, when signing with a session key.
28
+ *
29
+ * Omit it on the two-link chain, where the device key signs the request
30
+ * itself. Omitting is not the same as passing an empty string: borsh writes
31
+ * `Option` as a tag byte, so the two produce different bytes and only one of
32
+ * them parses.
33
+ */
34
+ session?: string;
35
+ /** `signRequest(...)` — the signature over this exact method, path and body. */
36
+ request: string;
37
+ }
38
+ /**
39
+ * Concatenate the three links into the header value.
40
+ *
41
+ * Returns hex, ready to present as `X-Calimero-Proof`.
42
+ */
43
+ export declare function callerProof(input: CallerProofInput): string;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Assemble the credential a node reads from `X-Calimero-Proof`.
3
+ *
4
+ * A request-carried proof is three links, and the node needs all of them in one
5
+ * header: the account root certified the device, the device (optionally)
6
+ * certified a short-lived session key, and that key signed THIS request. Each
7
+ * link is minted by its own function here — {@link signDeviceCert},
8
+ * {@link signLoginStatement}, {@link signRequest} — and each already returns
9
+ * the borsh encoding of the Rust type the node deserializes. Rust's
10
+ * `CallerProof` is a plain struct of those three fields, and borsh writes a
11
+ * struct as its fields back to back, so assembling the header is concatenation
12
+ * rather than a fourth encoder.
13
+ *
14
+ * That is worth stating because it is load-bearing and it is not obvious: if it
15
+ * were re-encoded here there would be a second spelling of a signed structure,
16
+ * able to disagree with the one that was signed. `caller-proof.test.ts` pins the
17
+ * concatenation against bytes produced by core itself.
18
+ */
19
+ import { fromHexUnsized, hex, concat } from "../crypto/internal.js";
20
+ /**
21
+ * Concatenate the three links into the header value.
22
+ *
23
+ * Returns hex, ready to present as `X-Calimero-Proof`.
24
+ */
25
+ export function callerProof(input) {
26
+ const credential = fromHexUnsized(input.credential, "credential");
27
+ const request = fromHexUnsized(input.request, "request signature");
28
+ // Borsh `Option<T>`: a single tag byte, then the value when present. A
29
+ // two-link chain is `None`, not an empty `Some` — the node reads the tag
30
+ // before anything else, so getting it backwards fails to parse rather than
31
+ // failing to verify, which at least is loud.
32
+ const session = input.session === undefined
33
+ ? new Uint8Array([0])
34
+ : concat(new Uint8Array([1]), fromHexUnsized(input.session, "session statement"));
35
+ return hex(concat(credential, session, request));
36
+ }
@@ -0,0 +1,3 @@
1
+ export { requestBodyHash, signRequest, type RequestSigInput, } from "./request-sig.js";
2
+ export { callerProof, type CallerProofInput } from "./caller-proof.js";
3
+ export { createProofSigner, type ProofRequest, type ProofSignerOptions, } from "./proof-signer.js";
@@ -0,0 +1,3 @@
1
+ export { requestBodyHash, signRequest, } from "./request-sig.js";
2
+ export { callerProof } from "./caller-proof.js";
3
+ export { createProofSigner, } from "./proof-signer.js";
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Turn a device key into something the HTTP client can call per request.
3
+ *
4
+ * A session is a bearer token: mint once, present many times. A request-carried
5
+ * proof is the opposite — it commits to one method, one path and one body, so
6
+ * it has to be produced at the moment of the call, by something holding the
7
+ * signing key. This is that something, shaped like `getAuthToken` so the key
8
+ * stays with the caller and never reaches the transport.
9
+ */
10
+ /** What the transport knows about the call it is about to make. */
11
+ export interface ProofRequest {
12
+ /** `GET`, `POST`, … exactly as it will be sent. */
13
+ method: string;
14
+ /** The URL path the node will see, **without** the query string. */
15
+ path: string;
16
+ /** The exact bytes that will be sent, if any. */
17
+ body?: unknown;
18
+ }
19
+ export interface ProofSignerOptions {
20
+ /** `signDeviceCert(...)`, hex. */
21
+ credential: string;
22
+ /**
23
+ * `signLoginStatement(...)`, hex — the three-link chain.
24
+ *
25
+ * Omit for the two-link chain, where `signerSecret` is the device key itself.
26
+ */
27
+ session?: string;
28
+ /**
29
+ * The ed25519 secret that signs each request, hex: the session key when
30
+ * `session` is set, otherwise the device key.
31
+ */
32
+ signerSecret: string;
33
+ /**
34
+ * How long each signature stays valid. Seconds, default 120.
35
+ *
36
+ * This is what bounds replay and nothing else does, so it is deliberately
37
+ * short and deliberately not configurable to "never". A clock skew allowance
38
+ * lives on the node; this only has to outlive the flight time.
39
+ */
40
+ ttlSeconds?: number;
41
+ /** Unix seconds. Injectable so a test does not depend on the wall clock. */
42
+ now?: () => number;
43
+ }
44
+ /**
45
+ * Build the `X-Calimero-Proof` value for one request.
46
+ *
47
+ * Pass the result to the HTTP client's `getProof`.
48
+ */
49
+ export declare function createProofSigner(options: ProofSignerOptions): (request: ProofRequest) => Promise<string>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Turn a device key into something the HTTP client can call per request.
3
+ *
4
+ * A session is a bearer token: mint once, present many times. A request-carried
5
+ * proof is the opposite — it commits to one method, one path and one body, so
6
+ * it has to be produced at the moment of the call, by something holding the
7
+ * signing key. This is that something, shaped like `getAuthToken` so the key
8
+ * stays with the caller and never reaches the transport.
9
+ */
10
+ import { callerProof } from "./caller-proof.js";
11
+ import { signRequest } from "./request-sig.js";
12
+ /**
13
+ * The bytes a body will actually be sent as.
14
+ *
15
+ * Refuses what it cannot hash without consuming or re-encoding. A stream can be
16
+ * read once, and reading it here would send an empty body; `FormData` and
17
+ * `URLSearchParams` are serialized by `fetch` in ways this cannot reproduce
18
+ * byte for byte. Signing a guess would produce a signature over bytes that
19
+ * never travelled, and the node would reject it with a signature error that
20
+ * says nothing about the real cause — so this throws, naming the type.
21
+ */
22
+ function bodyBytes(body) {
23
+ if (body === undefined || body === null)
24
+ return new Uint8Array(0);
25
+ if (typeof body === "string")
26
+ return body;
27
+ if (body instanceof Uint8Array)
28
+ return body;
29
+ if (body instanceof ArrayBuffer)
30
+ return new Uint8Array(body);
31
+ if (ArrayBuffer.isView(body)) {
32
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
33
+ }
34
+ throw new Error(`a request-carried proof cannot commit to a ${body?.constructor?.name ?? typeof body} body: pass a string or bytes, or use a session for this call`);
35
+ }
36
+ /**
37
+ * Build the `X-Calimero-Proof` value for one request.
38
+ *
39
+ * Pass the result to the HTTP client's `getProof`.
40
+ */
41
+ export function createProofSigner(options) {
42
+ const ttl = options.ttlSeconds ?? 120;
43
+ const clock = options.now ?? (() => Math.floor(Date.now() / 1000));
44
+ return async (request) => {
45
+ const issuedAt = clock();
46
+ return callerProof({
47
+ credential: options.credential,
48
+ session: options.session,
49
+ request: await signRequest({
50
+ method: request.method,
51
+ path: request.path,
52
+ body: bodyBytes(request.body),
53
+ issuedAt,
54
+ expiresAt: issuedAt + ttl,
55
+ signerSecret: options.signerSecret,
56
+ }),
57
+ });
58
+ };
59
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Sign one HTTP request, so a caller's identity travels with it.
3
+ *
4
+ * This is the bottom link of the chain a delegated client presents. A session
5
+ * has the node mint and remember something; this has the caller prove itself on
6
+ * every call, so the node holds no session state and the same path works
7
+ * whether or not the node runs a login provider at all.
8
+ *
9
+ * ```text
10
+ * account root ──signs──▶ DeviceCert cold, once, offline
11
+ * device key ──signs──▶ LoginStatement once per session, hours
12
+ * session key ──signs──▶ RequestSig per call ◀── this module
13
+ * ```
14
+ *
15
+ * **The middle link is optional.** A CLI or a server-side job signs with its
16
+ * device key directly and presents two links; a browser keeping the device key
17
+ * behind a hardware or extension boundary mints a session key and presents
18
+ * three. The node's verifier handles both, so which you produce here is a
19
+ * question about where your key lives, not about what the node accepts.
20
+ *
21
+ * **What it binds.** Method, path and a hash of the body. A signature for
22
+ * `GET /a` is not a signature for `POST /a`, for `GET /b`, or for the same call
23
+ * with different arguments.
24
+ *
25
+ * **The path excludes the query string**, deliberately: a proxy may legitimately
26
+ * rewrite it — a token parameter most of all — and signing over bytes something
27
+ * else is entitled to change means failing for reasons the caller cannot see.
28
+ * Anything that must be bound belongs in the body.
29
+ *
30
+ * **The method is not normalized.** `HEAD` and `GET` are the same *permission*
31
+ * and the node's permission layer folds them, but they are different requests.
32
+ * Sign the method you are about to send.
33
+ *
34
+ * **Replay inside the window performs the identical request** and is bounded
35
+ * rather than prevented — keep `expiresAt` short. A warrant, which authorizes a
36
+ * change with lasting effect, carries a nonce ledger for this; a request
37
+ * signature does not.
38
+ *
39
+ * **The byte contract is pinned in core**, at
40
+ * `crates/account/src/tests/request_wire_fixture.rs`, for the same reason the
41
+ * warrant and login ones are: the domains are `pub(crate)` there and the field
42
+ * order is implicit in a `derive`, so nothing on that side forces anyone to
43
+ * notice this file depends on both. This module's test asserts the same vectors.
44
+ */
45
+ import { fromHex } from "../crypto/internal.js";
46
+ /**
47
+ * Commit to a request body.
48
+ *
49
+ * Always call it, including for a body-less request: an empty body hashes to a
50
+ * value like any other, and there is no "absent body" encoding for a verifier
51
+ * to disagree with you about.
52
+ */
53
+ export declare function requestBodyHash(body?: Uint8Array | string): Promise<Uint8Array>;
54
+ /** What a caller is about to send. */
55
+ export interface RequestSigInput {
56
+ /**
57
+ * The HTTP method, exactly as it will appear on the wire — `GET`, `POST`,
58
+ * `HEAD`. Not folded: see the module note.
59
+ */
60
+ method: string;
61
+ /**
62
+ * The path, **without** the query string. `/admin-api/namespaces`, not
63
+ * `/admin-api/namespaces?token=…`.
64
+ */
65
+ path: string;
66
+ /**
67
+ * The request body, or nothing. Pass exactly the bytes you will send: the
68
+ * signature commits to their hash, so a body re-serialized between signing
69
+ * and sending is a signature for a different request.
70
+ */
71
+ body?: Uint8Array | string;
72
+ /** Unix seconds at signing. */
73
+ issuedAt: number | bigint;
74
+ /**
75
+ * Unix seconds after which the node must refuse it.
76
+ *
77
+ * Keep it short — minutes, not hours. It is what bounds replay, and nothing
78
+ * else does.
79
+ */
80
+ expiresAt: number | bigint;
81
+ /**
82
+ * The ed25519 signing secret, hex (32 bytes): the session key on the
83
+ * three-link chain, the device key on the two-link one.
84
+ *
85
+ * Never sent anywhere. It signs locally and only the signature travels.
86
+ */
87
+ signerSecret: string;
88
+ }
89
+ /**
90
+ * Sign one request and return it hex-encoded, ready to present.
91
+ *
92
+ * Returns the encoding rather than an object for the reason `signWarrant` and
93
+ * `signLoginStatement` do: the signature covers exactly these bytes, and a
94
+ * caller that rebuilt the fields from JSON would have a second spelling able to
95
+ * disagree with what was signed.
96
+ */
97
+ export declare function signRequest(input: RequestSigInput): Promise<string>;
98
+ /** Re-exported so a caller can check a hex signer key before signing with it. */
99
+ export { fromHex };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Sign one HTTP request, so a caller's identity travels with it.
3
+ *
4
+ * This is the bottom link of the chain a delegated client presents. A session
5
+ * has the node mint and remember something; this has the caller prove itself on
6
+ * every call, so the node holds no session state and the same path works
7
+ * whether or not the node runs a login provider at all.
8
+ *
9
+ * ```text
10
+ * account root ──signs──▶ DeviceCert cold, once, offline
11
+ * device key ──signs──▶ LoginStatement once per session, hours
12
+ * session key ──signs──▶ RequestSig per call ◀── this module
13
+ * ```
14
+ *
15
+ * **The middle link is optional.** A CLI or a server-side job signs with its
16
+ * device key directly and presents two links; a browser keeping the device key
17
+ * behind a hardware or extension boundary mints a session key and presents
18
+ * three. The node's verifier handles both, so which you produce here is a
19
+ * question about where your key lives, not about what the node accepts.
20
+ *
21
+ * **What it binds.** Method, path and a hash of the body. A signature for
22
+ * `GET /a` is not a signature for `POST /a`, for `GET /b`, or for the same call
23
+ * with different arguments.
24
+ *
25
+ * **The path excludes the query string**, deliberately: a proxy may legitimately
26
+ * rewrite it — a token parameter most of all — and signing over bytes something
27
+ * else is entitled to change means failing for reasons the caller cannot see.
28
+ * Anything that must be bound belongs in the body.
29
+ *
30
+ * **The method is not normalized.** `HEAD` and `GET` are the same *permission*
31
+ * and the node's permission layer folds them, but they are different requests.
32
+ * Sign the method you are about to send.
33
+ *
34
+ * **Replay inside the window performs the identical request** and is bounded
35
+ * rather than prevented — keep `expiresAt` short. A warrant, which authorizes a
36
+ * change with lasting effect, carries a nonce ledger for this; a request
37
+ * signature does not.
38
+ *
39
+ * **The byte contract is pinned in core**, at
40
+ * `crates/account/src/tests/request_wire_fixture.rs`, for the same reason the
41
+ * warrant and login ones are: the domains are `pub(crate)` there and the field
42
+ * order is implicit in a `derive`, so nothing on that side forces anyone to
43
+ * notice this file depends on both. This module's test asserts the same vectors.
44
+ */
45
+ import { concat, domainHash, fromHex, hex, importSigningKey, u32le, u64le, } from "../crypto/internal.js";
46
+ const SIGN_DOMAIN = new TextEncoder().encode("calimero.auth.request.v1");
47
+ /**
48
+ * Its own domain, distinct from the signing one.
49
+ *
50
+ * The two are different jobs on the same bytes: this produces the commitment,
51
+ * the other signs over it. Sharing a domain would make the commitment a
52
+ * truncated disclosure of bytes something signs.
53
+ */
54
+ const BODY_DOMAIN = new TextEncoder().encode("calimero.auth.request.body.v1");
55
+ /** A borsh `String`: its own `u32` little-endian length, then the UTF-8. */
56
+ function borshString(value) {
57
+ const bytes = new TextEncoder().encode(value);
58
+ return concat(u32le(bytes.length), bytes);
59
+ }
60
+ /**
61
+ * Commit to a request body.
62
+ *
63
+ * Always call it, including for a body-less request: an empty body hashes to a
64
+ * value like any other, and there is no "absent body" encoding for a verifier
65
+ * to disagree with you about.
66
+ */
67
+ export async function requestBodyHash(body = new Uint8Array(0)) {
68
+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
69
+ return domainHash(BODY_DOMAIN, [bytes]);
70
+ }
71
+ /**
72
+ * Sign one request and return it hex-encoded, ready to present.
73
+ *
74
+ * Returns the encoding rather than an object for the reason `signWarrant` and
75
+ * `signLoginStatement` do: the signature covers exactly these bytes, and a
76
+ * caller that rebuilt the fields from JSON would have a second spelling able to
77
+ * disagree with what was signed.
78
+ */
79
+ export async function signRequest(input) {
80
+ const key = await importSigningKey(input.signerSecret);
81
+ const bodyHash = await requestBodyHash(input.body);
82
+ const issuedAt = u64le(input.issuedAt);
83
+ const expiresAt = u64le(input.expiresAt);
84
+ const encoder = new TextEncoder();
85
+ const preimage = await domainHash(SIGN_DOMAIN, [
86
+ encoder.encode(input.method),
87
+ encoder.encode(input.path),
88
+ bodyHash,
89
+ issuedAt,
90
+ expiresAt,
91
+ ]);
92
+ const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, key, preimage));
93
+ return hex(concat(borshString(input.method), borshString(input.path), bodyHash, issuedAt, expiresAt, signature));
94
+ }
95
+ /** Re-exported so a caller can check a hex signer key before signing with it. */
96
+ export { fromHex };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calimero-network/mero-js",
3
- "version": "19.14.1",
3
+ "version": "19.16.0",
4
4
  "description": "Pure JavaScript SDK for Calimero",
5
5
  "type": "module",
6
6
  "exports": {