@terminal3/t3n-sdk 2.4.0 → 2.7.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
@@ -600,6 +600,154 @@ declare class UserUpsertError extends T3nError {
600
600
  static fromWire(raw: string): UserUpsertError | null;
601
601
  }
602
602
 
603
+ /**
604
+ * Org-data wire types mirroring the Rust contract shapes in
605
+ * `tee-contract-org-data` and `org-data-types`.
606
+ *
607
+ * Plain TypeScript interfaces (no zod) — the SDK does not use a
608
+ * validation library for domain types; see the existing `types/` files.
609
+ *
610
+ * Reference: `org-data-types/src/lib.rs` and
611
+ * `tee-contract-org-data/src/org_data.rs`.
612
+ */
613
+ /**
614
+ * Capability grant stored under `ORG_CONTRACT_GRANTS_MAP`.
615
+ *
616
+ * Mirrors `org_data_types::UserGrant`.
617
+ */
618
+ interface UserGrant {
619
+ /** The user this grant applies to (`did:t3n:<40-hex>`). */
620
+ user_did: string;
621
+ /** WIT function names the user may invoke (e.g. `"run-payroll"`). */
622
+ functions: string[];
623
+ /** Data scope paths the user may access (e.g. `"payroll/employees"`). */
624
+ scopes: string[];
625
+ /**
626
+ * Optional key-value constraints that must match the request metadata
627
+ * exactly for every key present in this map.
628
+ */
629
+ constraints: Record<string, string>;
630
+ /** Unix timestamp (secs) after which this grant is expired. `null` means never expires. */
631
+ expires_at_secs: number | null;
632
+ }
633
+ /**
634
+ * Policy record for an organisation's data tier.
635
+ *
636
+ * Mirrors `org_data_types::OrgPolicyMeta`.
637
+ */
638
+ interface OrgPolicyMeta {
639
+ /** DIDs (`did:t3n:<40-hex>`) of users authorised to manage policy and read data. */
640
+ admins: string[];
641
+ /** Maximum number of admins allowed for this org. */
642
+ max_admins: number;
643
+ /** Unix timestamp (secs) when the policy was first created. */
644
+ created_at_secs: number;
645
+ /** Unix timestamp (secs) of the most recent policy update. */
646
+ updated_at_secs: number;
647
+ }
648
+ type EmploymentStatus = "Active" | "Terminated";
649
+ /** Singapore CPF residency categories. */
650
+ type ResidencyCategory = "Citizen" | "Pr1" | "Pr2" | "PrThreePlus" | "Foreigner";
651
+ type AgeBand = "Under35" | "Age35To45" | "Age45To50" | "Age50To55" | "Age55To60" | "Age60To65" | "Over65";
652
+ interface ExpenseClaim {
653
+ claim_id: string;
654
+ amount_cents: number;
655
+ category: string;
656
+ description: string;
657
+ per_diem_days?: number;
658
+ }
659
+ /**
660
+ * Employee data row stored under `OrgData[org || "payroll/employees" || entry_id]`.
661
+ *
662
+ * Mirrors `tee-contract-payroll::types::EmployeeRecord`.
663
+ */
664
+ interface EmployeeRecord {
665
+ employee_id: string;
666
+ employment_status: EmploymentStatus;
667
+ is_on_probation: boolean;
668
+ hire_date: string;
669
+ termination_date?: string;
670
+ /** Monthly gross base salary in integer cents SGD. */
671
+ base_salary_cents: number;
672
+ unpaid_leave_days: number;
673
+ working_days_in_period: number;
674
+ overtime_hours: number;
675
+ hourly_rate_cents: number;
676
+ residency: ResidencyCategory;
677
+ age_band: AgeBand;
678
+ expense_claims: ExpenseClaim[];
679
+ /** Opaque reference used by the service layer for disbursement. */
680
+ bank_account_ref: string;
681
+ bank_account_changed_recently: boolean;
682
+ }
683
+ /**
684
+ * Standard response returned by all policy write and data mutation operations.
685
+ *
686
+ * Mirrors `tee-contract-org-data::org_data::MutationResponse`.
687
+ */
688
+ interface MutationResponse {
689
+ /** `"created"`, `"updated"`, or `"deleted"`. */
690
+ status: string;
691
+ /** Hex-encoded entry ID; present on data write/delete operations. */
692
+ entry_id?: string;
693
+ /** Whether the target key existed before deletion; present on single-entry deletes. */
694
+ deleted?: boolean;
695
+ /** Number of entries removed; present on `org-data-delete-scope`. */
696
+ deleted_entries?: number;
697
+ tx_hash: string | null;
698
+ }
699
+ /**
700
+ * Response type alias for org-writers-get.
701
+ *
702
+ * The wire body is `{ writers: string[] }` where each entry is
703
+ * `did:t3n:<40-hex>`.
704
+ */
705
+ interface OrgWriters {
706
+ writers: string[];
707
+ }
708
+ /**
709
+ * Response type alias for org-grants-get.
710
+ *
711
+ * The wire body echoes the `contract_id` alongside the grant list.
712
+ */
713
+ interface OrgContractGrants {
714
+ contract_id: string;
715
+ grants: UserGrant[];
716
+ }
717
+ /** Response for `org-data-list`. */
718
+ interface DataListResponse {
719
+ /** Hex-encoded entry IDs for this page. */
720
+ entry_ids: string[];
721
+ /** Offset to pass for the next page. `null` when this is the last page. */
722
+ next_offset: number | null;
723
+ /** Total number of entries in the scope (across all pages). */
724
+ total: number;
725
+ }
726
+ /** Response for `org-data-get`. */
727
+ interface DataGetResponse {
728
+ entry_id: string;
729
+ /** Hex-encoded raw payload bytes. */
730
+ payload_hex: string;
731
+ }
732
+ /**
733
+ * Legacy direct-route org-data envelope shape retained for compatibility.
734
+ *
735
+ * This mirrors the removed `/api/user-contract/execute` body format from
736
+ * the transitional transport. New callers should use `OrgDataClient`,
737
+ * which now dispatches through authenticated `/api/rpc` +
738
+ * `action.execute` instead.
739
+ */
740
+ interface OrgDataActionWire {
741
+ nonce: string;
742
+ user_did: string;
743
+ authenticator_id: string;
744
+ contract_id: string;
745
+ function: string;
746
+ args_hash: string;
747
+ expires_at_secs: number;
748
+ signature: string;
749
+ }
750
+
603
751
  /**
604
752
  * Public types export for T3n SDK
605
753
  */
@@ -1694,6 +1842,63 @@ declare function ethRecoverEip191(msg: Uint8Array, sig: Uint8Array): Uint8Array;
1694
1842
  * `delegation-types::verify_agent_sig` accepts as the 64-byte form.
1695
1843
  */
1696
1844
  declare function signAgentInvocation(preimage: Uint8Array, secret: Uint8Array): Uint8Array;
1845
+ /**
1846
+ * Options for {@link DelegationCustodialClient}.
1847
+ */
1848
+ interface DelegationCustodialClientOpts {
1849
+ /**
1850
+ * Explicit semver string for the delegation contract (e.g. `"1.0.0"`).
1851
+ * When omitted the client resolves `"latest"` via
1852
+ * `GET /api/contracts/current?name=tee:delegation/contracts` (one
1853
+ * request per client instance, cached in `getScriptVersion`).
1854
+ */
1855
+ scriptVersion?: string;
1856
+ }
1857
+ /**
1858
+ * Result returned by {@link DelegationCustodialClient.signCustodial}.
1859
+ */
1860
+ interface SignCustodialResult {
1861
+ /** RFC 8785 JCS bytes of the credential, exactly as signed by the node. */
1862
+ credentialJcs: Uint8Array;
1863
+ /** 65-byte EIP-191 signature over `credentialJcs` produced by the TEE. */
1864
+ userSig: Uint8Array;
1865
+ }
1866
+ /**
1867
+ * Wraps the `tee:delegation/contracts::sign` function for OIDC users
1868
+ * (or any user whose private key is held by the TEE rather than the
1869
+ * browser).
1870
+ *
1871
+ * ETH-EOA users who hold their own key should call
1872
+ * {@link signCredential} directly — no network round-trip required.
1873
+ *
1874
+ * The client must be constructed with an authenticated {@link T3nClient}
1875
+ * instance and the node's base URL; `signCustodial` sends the credential
1876
+ * body to the TEE and returns the signed bytes.
1877
+ *
1878
+ * Reference: `node/tests/harness/src/payroll_seed.rs` (the
1879
+ * `tee:delegation.sign` invocation at line 550).
1880
+ */
1881
+ declare class DelegationCustodialClient {
1882
+ private readonly t3n;
1883
+ private readonly baseUrl;
1884
+ private readonly opts;
1885
+ constructor(t3n: T3nClient, baseUrl: string, opts?: DelegationCustodialClientOpts);
1886
+ /**
1887
+ * Request the TEE to sign a delegation credential on behalf of the
1888
+ * authenticated user.
1889
+ *
1890
+ * The `body` is sent as-is as the `input.body` field of the
1891
+ * `tee:delegation/contracts::sign` action. Use
1892
+ * {@link buildDelegationCredential} + the wire-shape projection to
1893
+ * produce the correct representation — binary fields (`agent_pubkey`,
1894
+ * `vc_id`) must be base64url-no-pad strings, and `not_before_secs` /
1895
+ * `not_after_secs` must be decimal strings.
1896
+ *
1897
+ * Returns `{ credentialJcs, userSig }` — both as `Uint8Array` — ready
1898
+ * to be passed into {@link buildPayrollInvocation}.
1899
+ */
1900
+ signCustodial(body: Record<string, unknown>): Promise<SignCustodialResult>;
1901
+ }
1697
1902
  /** Options for {@link buildPayrollInvocation}. */
1698
1903
  interface BuildPayrollInvocationOpts {
1699
1904
  credentialJcs: Uint8Array;
@@ -1712,6 +1917,196 @@ interface BuildPayrollInvocationOpts {
1712
1917
  */
1713
1918
  declare function buildPayrollInvocation(opts: BuildPayrollInvocationOpts): PayrollInvocation;
1714
1919
 
1920
+ /**
1921
+ * OrgDataClient — typed wrapper over the existing authenticated
1922
+ * `/api/rpc` + `action.execute` pipeline.
1923
+ *
1924
+ * Unlike the removed direct `/api/user-contract/*` transport, this
1925
+ * client reuses Trinity's normal session-backed ETH auth flow:
1926
+ *
1927
+ * 1. `auth.handshake`
1928
+ * 2. `auth.authenticate`
1929
+ * 3. `action.execute`
1930
+ *
1931
+ * The class keeps its public constructor stable for callers that
1932
+ * already have an ETH secret key and expected DID, but internally it
1933
+ * owns a lazily-authenticated `T3nClient` instance rather than
1934
+ * constructing one-shot signed HTTP envelopes per call.
1935
+ */
1936
+
1937
+ interface CreatePolicyInput {
1938
+ orgDid: string;
1939
+ initialAdminDid: string;
1940
+ maxAdmins?: number;
1941
+ }
1942
+ interface UpdateMetaInput {
1943
+ orgDid: string;
1944
+ admins: string[];
1945
+ maxAdmins?: number;
1946
+ }
1947
+ interface SetWritersInput {
1948
+ orgDid: string;
1949
+ scope: string;
1950
+ writers: string[];
1951
+ }
1952
+ interface SetGrantsInput {
1953
+ orgDid: string;
1954
+ contractId: string;
1955
+ grants: UserGrant[];
1956
+ }
1957
+ interface DeleteGrantsInput {
1958
+ orgDid: string;
1959
+ contractId: string;
1960
+ }
1961
+ interface WriteDataInput {
1962
+ orgDid: string;
1963
+ scope: string;
1964
+ payloadHex: string;
1965
+ /** Explicit entry ID (32 hex chars). When present, enables idempotent upsert. */
1966
+ entryId?: string;
1967
+ /** Client-supplied monotonic counter for ID derivation when `entryId` is absent. */
1968
+ clientSeqNo?: number;
1969
+ }
1970
+ interface DeleteDataInput {
1971
+ orgDid: string;
1972
+ scope: string;
1973
+ /** Hex-encoded entry ID (32 hex chars). */
1974
+ entryId: string;
1975
+ }
1976
+ interface DeleteScopeInput {
1977
+ orgDid: string;
1978
+ scope: string;
1979
+ }
1980
+ interface PolicyGetInput {
1981
+ orgDid: string;
1982
+ }
1983
+ interface WritersGetInput {
1984
+ orgDid: string;
1985
+ scope: string;
1986
+ }
1987
+ interface GrantsGetInput {
1988
+ orgDid: string;
1989
+ contractId: string;
1990
+ }
1991
+ interface DataListInput {
1992
+ orgDid: string;
1993
+ scope: string;
1994
+ offset?: number;
1995
+ limit?: number;
1996
+ }
1997
+ interface DataGetInput {
1998
+ orgDid: string;
1999
+ scope: string;
2000
+ /** Hex-encoded entry ID (32 hex chars). */
2001
+ entryId: string;
2002
+ }
2003
+ interface ExecuteOrgDataActionOptions {
2004
+ /**
2005
+ * Deprecated. The direct signed-envelope transport used this as the
2006
+ * envelope expiry window; the session-backed RPC path ignores it.
2007
+ */
2008
+ ttlSecs?: number;
2009
+ }
2010
+ /**
2011
+ * Options used when constructing an {@link OrgDataClient}.
2012
+ */
2013
+ interface OrgDataClientOptions extends ExecuteOrgDataActionOptions {
2014
+ /** Optional preloaded WASM component for tests or shared callers. */
2015
+ wasmComponent?: WasmComponent;
2016
+ /** Optional transport override, primarily for tests. */
2017
+ transport?: Transport;
2018
+ /**
2019
+ * Optional handler overrides. If `EthSign` is omitted, the client
2020
+ * uses the supplied `ethSecret` to satisfy Trinity's existing ETH
2021
+ * auth challenge flow automatically.
2022
+ */
2023
+ handlers?: GuestToHostHandlers;
2024
+ }
2025
+ /**
2026
+ * Client for session-authenticated org-data contract execution.
2027
+ *
2028
+ * Constructed with the node's base URL, the caller's 32-byte ETH secret
2029
+ * key, and the caller's DID (`did:t3n:<40-hex>`). The first method call
2030
+ * lazily creates a `T3nClient`, completes ETH session auth, verifies that
2031
+ * the authenticated DID matches `userDid`, and then reuses that session for
2032
+ * subsequent contract calls.
2033
+ */
2034
+ declare class OrgDataClient {
2035
+ private readonly baseUrl;
2036
+ private readonly ethSecret;
2037
+ private readonly userDid;
2038
+ private readonly opts;
2039
+ private clientPromise;
2040
+ constructor(baseUrl: string, ethSecret: Uint8Array, userDid: string, opts?: OrgDataClientOptions);
2041
+ private getAuthenticatedClient;
2042
+ private initialiseClient;
2043
+ private call;
2044
+ /**
2045
+ * Initialise the data-tier policy for an existing organisation.
2046
+ *
2047
+ * The calling user must be named as `initialAdminDid`. New orgs created
2048
+ * after the org-data contract was deployed have their policy seeded
2049
+ * automatically by the organisation contract; call this only for orgs
2050
+ * that pre-date the contract deployment.
2051
+ */
2052
+ createPolicy(input: CreatePolicyInput): Promise<MutationResponse>;
2053
+ /**
2054
+ * Replace the admin list and/or `max_admins` cap on an existing policy.
2055
+ *
2056
+ * The calling user cannot remove themselves when they are the sole
2057
+ * remaining admin; another admin must be added first.
2058
+ */
2059
+ updateMeta(input: UpdateMetaInput): Promise<MutationResponse>;
2060
+ /**
2061
+ * Full replacement of the writer list for a data scope.
2062
+ *
2063
+ * Passing an empty list removes the entry (no writers allowed).
2064
+ * Scope names are canonicalised to lowercase before storage.
2065
+ */
2066
+ setWriters(input: SetWritersInput): Promise<MutationResponse>;
2067
+ /**
2068
+ * Full replacement of the user-grant list for a contract.
2069
+ *
2070
+ * Passing an empty list removes the entry.
2071
+ */
2072
+ setGrants(input: SetGrantsInput): Promise<MutationResponse>;
2073
+ /**
2074
+ * Delete the grant entry for a contract entirely.
2075
+ */
2076
+ deleteGrants(input: DeleteGrantsInput): Promise<MutationResponse>;
2077
+ /**
2078
+ * Write a data entry to the org's scope.
2079
+ *
2080
+ * When `entryId` is supplied, the call is an idempotent upsert.
2081
+ * When absent, `clientSeqNo` is required and the entry ID is derived
2082
+ * via SHA-256 from `(org_did, scope, writer_did, client_seq_no)`.
2083
+ */
2084
+ writeData(input: WriteDataInput): Promise<MutationResponse>;
2085
+ /** Delete a single data entry by entry ID. */
2086
+ deleteData(input: DeleteDataInput): Promise<MutationResponse>;
2087
+ /**
2088
+ * Bulk-delete all entries in a scope.
2089
+ *
2090
+ * Requires admin access (unlike `deleteData` which requires writer access).
2091
+ */
2092
+ deleteScope(input: DeleteScopeInput): Promise<MutationResponse>;
2093
+ /** Read the policy metadata for an org (admin-only). */
2094
+ policyGet(input: PolicyGetInput): Promise<OrgPolicyMeta>;
2095
+ /** Read the writer list for a scope (admin-only). */
2096
+ writersGet(input: WritersGetInput): Promise<OrgWriters>;
2097
+ /** Read the grant list for a contract (admin-only). */
2098
+ grantsGet(input: GrantsGetInput): Promise<OrgContractGrants>;
2099
+ /**
2100
+ * List entry IDs for a scope (admin-only), paginated.
2101
+ *
2102
+ * Pass `offset` from the previous response's `next_offset` to fetch
2103
+ * the next page.
2104
+ */
2105
+ dataList(input: DataListInput): Promise<DataListResponse>;
2106
+ /** Retrieve a single data entry by entry ID (admin-only). */
2107
+ dataGet(input: DataGetInput): Promise<DataGetResponse>;
2108
+ }
2109
+
1715
2110
  /**
1716
2111
  * Cryptographic utilities for T3n SDK
1717
2112
  *
@@ -1933,5 +2328,5 @@ declare function clearKeyCache(): void;
1933
2328
  */
1934
2329
  declare function loadConfig(baseUrl?: string): SdkConfig;
1935
2330
 
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 };
2331
+ export { AGENT_PUBKEY_LEN, AuthMethod, AuthenticationError, ContractResponseError, DEFAULT_KYC_POLL_CADENCE, DELEGATION_CREDENTIAL_DOMAIN, DELEGATION_INVOCATION_DOMAIN, DelegationCustodialClient, ETH_SIG_LEN, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, NONCE_LEN, OrgDataClient, 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 };
2332
+ export type { AgeBand, AuthInput, BuildDelegationCredentialOpts, BuildPayrollInvocationOpts, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationCredential, DelegationCustodialClientOpts, DelegationEnvelope, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, Did, DkgAttestation, DkgVerifyResult, EmployeeRecord, EmploymentStatus, Environment, EthAuthInput, ExecuteOrgDataActionOptions, ExpenseClaim, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, MutationResponse, OidcAuthInput, OidcCredentials, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollInvocation, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, QuoteVerifyResult, ResidencyCategory, SdkConfig, SessionCrypto, SessionId, SetGrantsInput, SetWritersInput, SignCustodialResult, SignDelegationResponse, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, Transport, UpdateMetaInput, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WriteDataInput, WritersGetInput };