@terminal3/t3n-sdk 2.3.0 → 2.5.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
+ * The signed action envelope sent to `POST /api/org-data/execute`.
734
+ *
735
+ * Field order matches `node/service/src/org_data.rs::OrgDataSignedAction`
736
+ * and `SignableEnvelope`. The `signature` field is the EIP-191
737
+ * personal_sign over the canonical JSON of the eight fields above it.
738
+ */
739
+ interface OrgDataActionWire {
740
+ nonce: string;
741
+ user_did: string;
742
+ authenticator_id: string;
743
+ org_did: 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,190 @@ interface BuildPayrollInvocationOpts {
1712
1917
  */
1713
1918
  declare function buildPayrollInvocation(opts: BuildPayrollInvocationOpts): PayrollInvocation;
1714
1919
 
1920
+ /**
1921
+ * OrgDataClient — user-signed org-data dispatch client.
1922
+ *
1923
+ * Implements the two-step flow that `node/service/src/org_data.rs`
1924
+ * defines:
1925
+ *
1926
+ * 1. `POST /api/org-data/nonce` — fetch a single-use replay nonce.
1927
+ * 2. `POST /api/org-data/execute` — submit a signed envelope whose
1928
+ * EIP-191 signature covers the canonical JSON of the eight
1929
+ * `SignableEnvelope` fields, in the exact field-declaration order
1930
+ * used by the Rust struct (see `org_data.rs` lines 104–117).
1931
+ *
1932
+ * The `args_hash` is `hex(sha256(JSON.stringify(args)))` — the same
1933
+ * binding the Rust harness (`org_data_client.rs`) computes.
1934
+ *
1935
+ * `authenticator_id` is `"eth:0x<40 lowercase hex>"` derived
1936
+ * deterministically from the caller's ETH secret key.
1937
+ */
1938
+
1939
+ /**
1940
+ * Options accepted by {@link executeOrgDataAction}.
1941
+ */
1942
+ interface ExecuteOrgDataActionOptions {
1943
+ /** Envelope TTL in seconds. Defaults to {@link DEFAULT_ENVELOPE_TTL_SECS}. */
1944
+ ttlSecs?: number;
1945
+ }
1946
+ interface CreatePolicyInput {
1947
+ orgDid: string;
1948
+ initialAdminDid: string;
1949
+ maxAdmins?: number;
1950
+ }
1951
+ interface UpdateMetaInput {
1952
+ orgDid: string;
1953
+ admins: string[];
1954
+ maxAdmins?: number;
1955
+ }
1956
+ interface SetWritersInput {
1957
+ orgDid: string;
1958
+ scope: string;
1959
+ writers: string[];
1960
+ }
1961
+ interface SetGrantsInput {
1962
+ orgDid: string;
1963
+ contractId: string;
1964
+ grants: UserGrant[];
1965
+ }
1966
+ interface DeleteGrantsInput {
1967
+ orgDid: string;
1968
+ contractId: string;
1969
+ }
1970
+ interface WriteDataInput {
1971
+ orgDid: string;
1972
+ scope: string;
1973
+ payloadHex: string;
1974
+ /** Explicit entry ID (32 hex chars). When present, enables idempotent upsert. */
1975
+ entryId?: string;
1976
+ /** Client-supplied monotonic counter for ID derivation when `entryId` is absent. */
1977
+ clientSeqNo?: number;
1978
+ }
1979
+ interface DeleteDataInput {
1980
+ orgDid: string;
1981
+ scope: string;
1982
+ /** Hex-encoded entry ID (32 hex chars). */
1983
+ entryId: string;
1984
+ }
1985
+ interface DeleteScopeInput {
1986
+ orgDid: string;
1987
+ scope: string;
1988
+ }
1989
+ interface PolicyGetInput {
1990
+ orgDid: string;
1991
+ }
1992
+ interface WritersGetInput {
1993
+ orgDid: string;
1994
+ scope: string;
1995
+ }
1996
+ interface GrantsGetInput {
1997
+ orgDid: string;
1998
+ contractId: string;
1999
+ }
2000
+ interface DataListInput {
2001
+ orgDid: string;
2002
+ scope: string;
2003
+ offset?: number;
2004
+ limit?: number;
2005
+ }
2006
+ interface DataGetInput {
2007
+ orgDid: string;
2008
+ scope: string;
2009
+ /** Hex-encoded entry ID (32 hex chars). */
2010
+ entryId: string;
2011
+ }
2012
+ /**
2013
+ * Options used when constructing an {@link OrgDataClient}.
2014
+ */
2015
+ interface OrgDataClientOptions {
2016
+ /** Envelope TTL in seconds applied to every call. Default: 300. */
2017
+ ttlSecs?: number;
2018
+ }
2019
+ /**
2020
+ * Client for the user-authenticated org-data dispatch API.
2021
+ *
2022
+ * Constructed with the node's base URL, the caller's 32-byte ETH secret
2023
+ * key, and the caller's DID (`did:t3n:<40-hex>`). Every method
2024
+ * transparently fetches a fresh nonce, signs the envelope with EIP-191,
2025
+ * and posts to `/api/org-data/execute`.
2026
+ *
2027
+ * The signing key must be the same key registered as an authenticator
2028
+ * (`eth:0x<addr>`) for `userDid` in the DID registry — the service
2029
+ * verifies this binding before dispatching any contract call.
2030
+ */
2031
+ declare class OrgDataClient {
2032
+ private readonly baseUrl;
2033
+ private readonly ethSecret;
2034
+ private readonly userDid;
2035
+ private readonly opts;
2036
+ constructor(baseUrl: string, ethSecret: Uint8Array, userDid: string, opts?: OrgDataClientOptions);
2037
+ private call;
2038
+ /**
2039
+ * Initialise the data-tier policy for an existing organisation.
2040
+ *
2041
+ * The calling user must be named as `initialAdminDid`. New orgs created
2042
+ * after the org-data contract was deployed have their policy seeded
2043
+ * automatically by the organisation contract; call this only for orgs
2044
+ * that pre-date the contract deployment.
2045
+ */
2046
+ createPolicy(input: CreatePolicyInput): Promise<MutationResponse>;
2047
+ /**
2048
+ * Replace the admin list and/or `max_admins` cap on an existing policy.
2049
+ *
2050
+ * The calling user cannot remove themselves when they are the sole
2051
+ * remaining admin; another admin must be added first.
2052
+ */
2053
+ updateMeta(input: UpdateMetaInput): Promise<MutationResponse>;
2054
+ /**
2055
+ * Full replacement of the writer list for a data scope.
2056
+ *
2057
+ * Passing an empty list removes the entry (no writers allowed).
2058
+ * Scope names are canonicalised to lowercase before storage.
2059
+ */
2060
+ setWriters(input: SetWritersInput): Promise<MutationResponse>;
2061
+ /**
2062
+ * Full replacement of the user-grant list for a contract.
2063
+ *
2064
+ * Passing an empty list removes the entry.
2065
+ */
2066
+ setGrants(input: SetGrantsInput): Promise<MutationResponse>;
2067
+ /**
2068
+ * Delete the grant entry for a contract entirely.
2069
+ */
2070
+ deleteGrants(input: DeleteGrantsInput): Promise<MutationResponse>;
2071
+ /**
2072
+ * Write a data entry to the org's scope.
2073
+ *
2074
+ * When `entryId` is supplied, the call is an idempotent upsert.
2075
+ * When absent, `clientSeqNo` is required and the entry ID is derived
2076
+ * via SHA-256 from `(org_did, scope, writer_did, client_seq_no)`.
2077
+ */
2078
+ writeData(input: WriteDataInput): Promise<MutationResponse>;
2079
+ /** Delete a single data entry by entry ID. */
2080
+ deleteData(input: DeleteDataInput): Promise<MutationResponse>;
2081
+ /**
2082
+ * Bulk-delete all entries in a scope.
2083
+ *
2084
+ * Requires admin access (unlike `deleteData` which requires writer access).
2085
+ */
2086
+ deleteScope(input: DeleteScopeInput): Promise<MutationResponse>;
2087
+ /** Read the policy metadata for an org (admin-only). */
2088
+ policyGet(input: PolicyGetInput): Promise<OrgPolicyMeta>;
2089
+ /** Read the writer list for a scope (admin-only). */
2090
+ writersGet(input: WritersGetInput): Promise<OrgWriters>;
2091
+ /** Read the grant list for a contract (admin-only). */
2092
+ grantsGet(input: GrantsGetInput): Promise<OrgContractGrants>;
2093
+ /**
2094
+ * List entry IDs for a scope (admin-only), paginated.
2095
+ *
2096
+ * Pass `offset` from the previous response's `next_offset` to fetch
2097
+ * the next page.
2098
+ */
2099
+ dataList(input: DataListInput): Promise<DataListResponse>;
2100
+ /** Retrieve a single data entry by entry ID (admin-only). */
2101
+ dataGet(input: DataGetInput): Promise<DataGetResponse>;
2102
+ }
2103
+
1715
2104
  /**
1716
2105
  * Cryptographic utilities for T3n SDK
1717
2106
  *
@@ -1933,5 +2322,5 @@ declare function clearKeyCache(): void;
1933
2322
  */
1934
2323
  declare function loadConfig(baseUrl?: string): SdkConfig;
1935
2324
 
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 };
2325
+ 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 };
2326
+ 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 };