@terminal3/t3n-sdk 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1507,6 +1507,211 @@ declare function createRandomHandler(): GuestToHostHandler;
1507
1507
  */
1508
1508
  declare function createDefaultHandlers(baseUrl: string): GuestToHostHandlers;
1509
1509
 
1510
+ /**
1511
+ * User-to-Agent Delegation (T3-TS-030).
1512
+ *
1513
+ * TypeScript reference implementation of the delegation credential and
1514
+ * envelope shapes defined in `node/tee_contracts/delegation-types`.
1515
+ *
1516
+ * The wire shape is byte-for-byte identical to the Rust source — pinned
1517
+ * by the KAT fixtures under `tests/kat/`. Specifically:
1518
+ *
1519
+ * - `not_before_secs` / `not_after_secs` / `batch_cap_cents` are
1520
+ * emitted as **JSON strings** (e.g. `"1700086400"`) so JS Number
1521
+ * precision never enters the canonicalisation surface.
1522
+ * - `nonce` (16 B), `vc_id` (16 B), `request_hash` (32 B),
1523
+ * `agent_pubkey` (33 B compressed secp256k1), `user_sig`,
1524
+ * `agent_sig` are emitted as **base64url-no-pad** strings.
1525
+ * - `org_did` / `user_did` are emitted as `did:t3n:<40-hex>` (the
1526
+ * `CompactDid` `Display` form).
1527
+ *
1528
+ * Canonicalisation uses the npm `canonicalize` package (RFC 8785 JCS).
1529
+ * Cryptography uses `@noble/curves` (secp256k1) and `@noble/hashes`
1530
+ * (sha256, keccak_256).
1531
+ */
1532
+ /** Domain tag carried in `DelegationCredential.v`. */
1533
+ declare const DELEGATION_CREDENTIAL_DOMAIN: "ot3.delegation/1";
1534
+ /** Domain tag prepended to the agent-side pre-image. */
1535
+ declare const DELEGATION_INVOCATION_DOMAIN: "ot3.invocation/1";
1536
+ declare const VC_ID_LEN = 16;
1537
+ declare const NONCE_LEN = 16;
1538
+ declare const REQUEST_HASH_LEN = 32;
1539
+ declare const AGENT_PUBKEY_LEN = 33;
1540
+ declare const ETH_SIG_LEN = 65;
1541
+ /** User-to-agent delegation credential body. */
1542
+ interface DelegationCredential {
1543
+ /** Domain tag, must equal {@link DELEGATION_CREDENTIAL_DOMAIN}. */
1544
+ v: string;
1545
+ /** `did:t3n:<40-hex>` user DID. */
1546
+ user_did: string;
1547
+ /** 33-byte compressed secp256k1 public key the agent uses per call. */
1548
+ agent_pubkey: Uint8Array;
1549
+ /** `did:t3n:<40-hex>` org DID. */
1550
+ org_did: string;
1551
+ /** Contract id, e.g. `"tee:payroll"`. */
1552
+ contract: string;
1553
+ /** Function name, e.g. `"run-payroll"`. */
1554
+ function: string;
1555
+ /** Org-data scopes the contract may read on this user's behalf. */
1556
+ scopes: string[];
1557
+ /** Flat key-value labels checked against the org grant. */
1558
+ metadata: Record<string, string>;
1559
+ /** Inclusive lower bound of the validity window (unix seconds). */
1560
+ not_before_secs: bigint;
1561
+ /** Inclusive upper bound of the validity window (unix seconds). */
1562
+ not_after_secs: bigint;
1563
+ /** Random 16-byte credential id. */
1564
+ vc_id: Uint8Array;
1565
+ }
1566
+ /** Envelope wrapping a contract-specific request body. */
1567
+ interface DelegationEnvelope {
1568
+ /** RFC 8785 JCS bytes of the credential, exactly as signed. */
1569
+ credential_jcs: Uint8Array;
1570
+ /** 65-byte EIP-191 signature over `credential_jcs`. */
1571
+ user_sig: Uint8Array;
1572
+ /** Per-call agent signature over the invocation pre-image. */
1573
+ agent_sig: Uint8Array;
1574
+ /** 16-byte agent-generated per-call nonce. */
1575
+ nonce: Uint8Array;
1576
+ /** SHA-256 of the canonical request body. */
1577
+ request_hash: Uint8Array;
1578
+ }
1579
+ /** Payroll-specific request body wrapped by a delegation envelope. */
1580
+ interface PayrollRunRequest {
1581
+ /** `did:t3n:<40-hex>` org id. */
1582
+ org_id: string;
1583
+ cycle_id: string;
1584
+ pay_period_start: string;
1585
+ pay_period_end: string;
1586
+ /** Total cap on the run's net disbursement, in cents. */
1587
+ batch_cap_cents: bigint;
1588
+ /** `employee_id` → previous-cycle baseline net disbursement, cents (decimal string). */
1589
+ historical_baselines: Record<string, string>;
1590
+ }
1591
+ /** Convenience wrapper paired with the matching delegation envelope. */
1592
+ interface PayrollInvocation {
1593
+ envelope: DelegationEnvelope;
1594
+ request: PayrollRunRequest;
1595
+ }
1596
+ /** Response from `tee:delegation.sign`. */
1597
+ interface SignDelegationResponse {
1598
+ credential_jcs: Uint8Array;
1599
+ user_sig: Uint8Array;
1600
+ }
1601
+ declare function b64uEncode(input: Uint8Array): string;
1602
+ /**
1603
+ * Encode raw bytes to base64url-no-pad (RFC 4648 §5 with padding
1604
+ * dropped). The same encoding T3-TS-030 wire-shape uses for binary
1605
+ * fields (`agent_pubkey`, `vc_id`, `nonce`, `agent_sig`, `user_sig`,
1606
+ * `request_hash`, `credential_jcs`).
1607
+ *
1608
+ * Public API since v2.2: callers building `PayrollInvocation` JSON
1609
+ * for the wire (e.g. the t3n-mcp `runPayroll` handler) need this
1610
+ * encoder to match the contract's deserializer.
1611
+ */
1612
+ declare function b64uEncodeBytes(input: Uint8Array): string;
1613
+ /**
1614
+ * Decode a base64url-no-pad string. Strict — rejects standard-alphabet
1615
+ * `+` / `/` and any padding `=`.
1616
+ */
1617
+ declare function b64uDecodeStrict(input: string): Uint8Array;
1618
+ /** @internal — preserved alias for in-tree callers. Prefer
1619
+ * {@link b64uEncodeBytes} / {@link b64uDecodeStrict}. */
1620
+ declare const _b64uEncode: typeof b64uEncode;
1621
+ /** Build a `did:t3n:<40-hex>` from raw 20 bytes. */
1622
+ declare function compactDidFromBytes(bytes: Uint8Array): string;
1623
+ /**
1624
+ * Canonicalise a {@link DelegationCredential} to RFC 8785 JCS bytes.
1625
+ *
1626
+ * Output is byte-identical to the Rust `canonicalise_credential` in
1627
+ * `delegation-types` (pinned by `tests/kat/credential.json`).
1628
+ */
1629
+ declare function canonicaliseCredential(credential: DelegationCredential): Uint8Array;
1630
+ /** Canonicalise an arbitrary {@link PayrollRunRequest} to JCS bytes. */
1631
+ declare function canonicaliseRequest(request: PayrollRunRequest): Uint8Array;
1632
+ /** SHA-256 of the canonicalised request body. */
1633
+ declare function requestHash(request: PayrollRunRequest): Uint8Array;
1634
+ /**
1635
+ * Build the agent-side pre-image bytes:
1636
+ * `utf8(DELEGATION_INVOCATION_DOMAIN) || vc_id || nonce || request_hash`.
1637
+ *
1638
+ * SHA-256 of these bytes is what the agent's secp256k1 signature is
1639
+ * verified against.
1640
+ */
1641
+ declare function buildInvocationPreimage(vcId: Uint8Array, nonce: Uint8Array, reqHash: Uint8Array): Uint8Array;
1642
+ /** Options for {@link buildDelegationCredential}. */
1643
+ interface BuildDelegationCredentialOpts {
1644
+ user_did: string;
1645
+ agent_pubkey: Uint8Array;
1646
+ org_did: string;
1647
+ contract: string;
1648
+ function: string;
1649
+ scopes?: string[];
1650
+ metadata?: Record<string, string>;
1651
+ not_before_secs: bigint | number;
1652
+ not_after_secs: bigint | number;
1653
+ vc_id: Uint8Array;
1654
+ }
1655
+ /**
1656
+ * Construct a {@link DelegationCredential} and validate body-level
1657
+ * invariants (domain, lengths, validity window). Throws on the same
1658
+ * conditions the Rust `validate_credential_body` rejects.
1659
+ */
1660
+ declare function buildDelegationCredential(opts: BuildDelegationCredentialOpts): DelegationCredential;
1661
+ /**
1662
+ * Body-level validation matching `delegation-types::validate_credential_body`,
1663
+ * minus the `now`/`max_validity_secs` checks (which are caller-supplied).
1664
+ * Throws with a message identifying the offending invariant.
1665
+ */
1666
+ declare function validateCredentialBody(c: DelegationCredential): void;
1667
+ /** Compute the EIP-191 "personal_sign" digest of a message. */
1668
+ declare function eip191Digest(msg: Uint8Array): Uint8Array;
1669
+ /**
1670
+ * EIP-191 sign `jcs` under `secret`, returning a 65-byte signature
1671
+ * (`r || s || v`, with `v` in 27/28 — Ethereum convention) and the
1672
+ * recovered 20-byte ETH address.
1673
+ */
1674
+ declare function signCredential(jcs: Uint8Array, secret: Uint8Array): {
1675
+ sig: Uint8Array;
1676
+ addr: Uint8Array;
1677
+ };
1678
+ /**
1679
+ * Recover the 20-byte ETH address that signed `msg` under EIP-191.
1680
+ * Mirrors `delegation-types::eth_recover_eip191`.
1681
+ *
1682
+ * **Signature malleability — accepted by design.** This routine does
1683
+ * not enforce low-s. EIP-2 mandates low-s for *transaction* signatures,
1684
+ * but EIP-191 / `personal_sign` has no such requirement, and ethers.js
1685
+ * / MetaMask / web3.js produce both shapes. Two distinct `(r, s)` and
1686
+ * `(r, n − s)` pairs verify under the same recovered address — replay
1687
+ * protection comes from the envelope's `request_hash` + `nonce`, not
1688
+ * from byte-uniqueness of the signature.
1689
+ */
1690
+ declare function ethRecoverEip191(msg: Uint8Array, sig: Uint8Array): Uint8Array;
1691
+ /**
1692
+ * Sign the agent-side invocation pre-image. The signature is raw
1693
+ * compact ECDSA (64 bytes) over `sha256(preimage)` — what
1694
+ * `delegation-types::verify_agent_sig` accepts as the 64-byte form.
1695
+ */
1696
+ declare function signAgentInvocation(preimage: Uint8Array, secret: Uint8Array): Uint8Array;
1697
+ /** Options for {@link buildPayrollInvocation}. */
1698
+ interface BuildPayrollInvocationOpts {
1699
+ credentialJcs: Uint8Array;
1700
+ userSig: Uint8Array;
1701
+ /** Credential's `vc_id` — needed for the agent pre-image. */
1702
+ vcId: Uint8Array;
1703
+ nonce: Uint8Array;
1704
+ request: PayrollRunRequest;
1705
+ agentSecret: Uint8Array;
1706
+ }
1707
+ /**
1708
+ * Assemble a complete {@link PayrollInvocation} (envelope + request)
1709
+ * given a user-signed credential and a per-call agent secret. Computes
1710
+ * `request_hash` from the canonical request bytes and produces an
1711
+ * `agent_sig` over `sha256(invocation_preimage)`.
1712
+ */
1713
+ declare function buildPayrollInvocation(opts: BuildPayrollInvocationOpts): PayrollInvocation;
1714
+
1510
1715
  /**
1511
1716
  * Cryptographic utilities for T3n SDK
1512
1717
  *
@@ -1728,5 +1933,5 @@ declare function clearKeyCache(): void;
1728
1933
  */
1729
1934
  declare function loadConfig(baseUrl?: string): SdkConfig;
1730
1935
 
1731
- export { AuthMethod, AuthenticationError, ContractResponseError, DEFAULT_KYC_POLL_CADENCE, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, RpcError, SessionStateError, SessionStatus, T3nClient, T3nError, TERMINAL_KYC_STATUSES, UserUpsertError, WasmError, bytesToString, clearKeyCache, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createRandomHandler, decodeWasmErrorMessage, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, parseContractResponse, redactSecrets, redactSecretsFromJson, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, validateConfig, verifyDkgAttestation, verifyTdxQuote };
1732
- export type { AuthInput, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, Did, DkgAttestation, DkgVerifyResult, Environment, EthAuthInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, OidcAuthInput, OidcCredentials, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PeerQuoteResult, QuoteVerifyResult, SdkConfig, SessionCrypto, SessionId, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, Transport, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult };
1936
+ export { AGENT_PUBKEY_LEN, AuthMethod, AuthenticationError, ContractResponseError, DEFAULT_KYC_POLL_CADENCE, DELEGATION_CREDENTIAL_DOMAIN, DELEGATION_INVOCATION_DOMAIN, ETH_SIG_LEN, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, NONCE_LEN, REQUEST_HASH_LEN, RpcError, SessionStateError, SessionStatus, T3nClient, T3nError, TERMINAL_KYC_STATUSES, UserUpsertError, VC_ID_LEN, WasmError, _b64uEncode, b64uDecodeStrict, b64uEncodeBytes, buildDelegationCredential, buildInvocationPreimage, buildPayrollInvocation, bytesToString, canonicaliseCredential, canonicaliseRequest, clearKeyCache, compactDidFromBytes, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createRandomHandler, decodeWasmErrorMessage, eip191Digest, ethRecoverEip191, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, parseContractResponse, redactSecrets, redactSecretsFromJson, requestHash, setEnvironment, setGlobalLogLevel, setNodeUrl, signAgentInvocation, signCredential, stringToBytes, validateConfig, validateCredentialBody, verifyDkgAttestation, verifyTdxQuote };
1937
+ export type { AuthInput, BuildDelegationCredentialOpts, BuildPayrollInvocationOpts, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, DelegationCredential, DelegationEnvelope, Did, DkgAttestation, DkgVerifyResult, Environment, EthAuthInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, OidcAuthInput, OidcCredentials, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollInvocation, PayrollRunRequest, PeerQuoteResult, QuoteVerifyResult, SdkConfig, SessionCrypto, SessionId, SignDelegationResponse, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, Transport, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult };