@brazosd/node 0.1.0 → 0.1.2

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.
Files changed (4) hide show
  1. package/README.md +43 -3
  2. package/index.d.ts +287 -0
  3. package/index.js +498 -0
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Brazosd Node.js SDK
2
2
 
3
- Node.js 22+ ESM client generated from Brazosd's OpenAPI schemas, with automatic cloud-function identity and no runtime dependencies.
3
+ Node.js 22.13+ ESM client generated from Brazosd's OpenAPI schemas, with automatic cloud-function identity and no runtime dependencies.
4
4
 
5
5
  Install the public npm package:
6
6
 
@@ -85,6 +85,46 @@ const client = createClient({
85
85
 
86
86
  Each client keeps its own URL, credential provider and request configuration. Concurrent clients do not share global authentication state. Public operations work without credentials when `apiUrl` is supplied. A schema-defined `Authorization` parameter, when present, takes precedence over the client's credential provider.
87
87
 
88
+ ## Sign in with Brazosd
89
+
90
+ SSO requires `@brazosd/node` 0.1.2 or later. `createSSO()` supports
91
+ `org-user` (same-organization user API credentials) and
92
+ `identity` (an identity JWT for users from any organization):
93
+
94
+ ```js
95
+ import { createSSO } from '@brazosd/node';
96
+
97
+ const sso = createSSO({
98
+ appId: process.env.BRAZOSD_APP_ID,
99
+ redirectUri: 'https://your-app.example/auth/brazosd/callback',
100
+ loginSecret: process.env.SSO_LOGIN_SECRET, // 32 random bytes as base64url
101
+ });
102
+ const { authorizationUrl, setCookie } = await sso.beginLogin('identity');
103
+ // Send setCookie, then redirect to authorizationUrl.
104
+ // On the registered callback:
105
+ // const { tokens, identity, clearCookie } = await sso.completeLogin(url, cookie);
106
+ ```
107
+
108
+ The SDK binds the browser transaction with an encrypted HttpOnly cookie, state
109
+ and PKCE. Service credentials remain on the app server. Store the verified
110
+ identity or user credentials in your own server session and send an opaque
111
+ session cookie to the browser. Identity JWTs contain `account_id`, `org_id`,
112
+ `user_id` and `sub=String(account_id)`; `(iss, sub)` is the recommended identity
113
+ key. They cannot call Brazosd APIs or refresh API credentials.
114
+
115
+ `sso.userClient({getTokens, saveTokens})` refreshes org-user credentials and
116
+ keeps each user's identity isolated. Shared session stores must compare-and-swap
117
+ updates using the `expectedRefreshToken` supplied to `saveTokens`. Call
118
+ `sso.revoke(tokens)` on logout and delete the app session. No failures fall back
119
+ to service-user permissions.
120
+
121
+ JWT verification uses strict issuer/audience/type/signature/expiry checks and
122
+ memory plus SQLite JWKS caching. The default cache is
123
+ `~/.cache/brazosd-sso/jwks.sqlite`; supply a `SQLiteSSOKeyCache` or `SSOKeyCache`
124
+ adapter for other storage. See the [SSO integration guide](../../docs/api/sso.md)
125
+ for callbacks, session lifecycle, private deployments and complete examples.
126
+ Install or update with `npm install @brazosd/node@^0.1.2`.
127
+
88
128
  ## Errors and cancellation
89
129
 
90
130
  API errors throw `BrazosdError` with `status` and a bounded response `body`. Handle permission errors, conflicts and throttling explicitly. Generated calls return a `CancelablePromise`: call `.cancel()` before completion to abort the HTTP request. Cancellation rejects with `CancelError`. A client-wide `signal` is also supported; cancel a returned stream through its `Response.body`.
@@ -103,13 +143,13 @@ const part = await rangedClient.api.downloadCloudDrive({ path: '@brazosd://org.d
103
143
  ## Regeneration and validation
104
144
 
105
145
  Releases use `sdks/node/VERSION` independently of the server version. Changing
106
- that file on `main` triggers `.github/workflows/publish-node-sdk.yml`, which tests
146
+ that file on `main` triggers `.github/workflows/publish-sdk.yaml`, which tests
107
147
  the SDK, publishes to npm, requests npmmirror synchronization, and verifies
108
148
  installation from the mirror. Rerun a failed mirror synchronization with the same
109
149
  version; changed package contents require a new version.
110
150
 
111
151
  After the first npm publication, configure a GitHub Actions trusted publisher for
112
- `cloudcarver/brazosd`, workflow `publish-node-sdk.yml`, with direct publishing
152
+ `cloudcarver/brazosd`, workflow `publish-sdk.yaml`, with direct publishing
113
153
  allowed. The workflow uses OIDC and does not need an npm token. Run
114
154
  `node scripts/publish.mjs --dry-run` in this directory to validate packaging
115
155
  without publishing.
package/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  // Generated by scripts/generate.mjs; edit src/ and OpenAPI sources instead.
2
+ import { JsonWebKey as JsonWebKey$1 } from 'node:crypto';
3
+
2
4
  type ApiRequestOptions = {
3
5
  readonly method: "GET" | "PUT" | "POST" | "DELETE" | "OPTIONS" | "HEAD" | "PATCH";
4
6
  readonly url: string;
@@ -687,6 +689,11 @@ type AppendAgentSessionEventRequest = {
687
689
  */
688
690
  skipPersistent?: boolean;
689
691
  };
692
+ export type SSOMode = "org-user" | "identity";
693
+ type AuthorizeSSORequest = {
694
+ mode: SSOMode;
695
+ orgId: number;
696
+ };
690
697
  type BillingCredit = {
691
698
  createdAt: string;
692
699
  earnedAmountMicroyuans: number;
@@ -753,6 +760,10 @@ type BillingUserDailyCost = {
753
760
  orgId: number;
754
761
  sandboxNetworkTrafficAmountMicroyuans: number;
755
762
  shallowSleepSandboxAmountMicroyuans: number;
763
+ /**
764
+ * Saved and deep-sleep snapshot storage charges.
765
+ */
766
+ snapshotAmountMicroyuans: number;
756
767
  tokenAmountMicroyuans: number;
757
768
  /**
758
769
  * Total billable tool-service cost, including image generation, web search, video understanding, and audio transcription.
@@ -1637,6 +1648,16 @@ type CreateSnapshotRequest = {
1637
1648
  description: string;
1638
1649
  name: string;
1639
1650
  };
1651
+ type CreateSSORequest = {
1652
+ appId: string;
1653
+ /**
1654
+ * BASE64URL(SHA256(code_verifier)); only PKCE S256 is supported.
1655
+ */
1656
+ codeChallenge: string;
1657
+ mode: SSOMode;
1658
+ redirectUri: string;
1659
+ state: string;
1660
+ };
1640
1661
  type CreateTradeAPIOrderItem = {
1641
1662
  amountMicroyuans: number;
1642
1663
  note?: string;
@@ -1851,6 +1872,12 @@ type EnterprisePermissionPolicySummary = {
1851
1872
  type EnterprisePermissionRules = {
1852
1873
  rules: Array<EnterprisePermissionRule>;
1853
1874
  };
1875
+ type ExchangeSSOCodeRequest = {
1876
+ appId: string;
1877
+ code: string;
1878
+ codeVerifier: string;
1879
+ redirectUri: string;
1880
+ };
1854
1881
  type FakePayNotifyRequest = {
1855
1882
  orgRechargeOrderId: string;
1856
1883
  };
@@ -2578,6 +2605,11 @@ type RecruitAgentRequest = {
2578
2605
  */
2579
2606
  displayName?: string;
2580
2607
  };
2608
+ type RefreshSSOTokensRequest = {
2609
+ appId: string;
2610
+ refreshToken: string;
2611
+ requestId: string;
2612
+ };
2581
2613
  type RefreshTokenRequest = {
2582
2614
  /**
2583
2615
  * Refresh token issued with the token family.
@@ -2885,11 +2917,19 @@ type Snapshot = {
2885
2917
  * Snapshot UUID.
2886
2918
  */
2887
2919
  id: string;
2920
+ /**
2921
+ * Storage usage has been settled through this instant.
2922
+ */
2923
+ lastBilledAt?: string;
2888
2924
  name: string;
2889
2925
  orgId: number;
2890
2926
  provider: SnapshotProvider;
2891
2927
  sourceSandboxId?: string;
2892
2928
  state: "creating" | "ready" | "failed" | "deleting";
2929
+ /**
2930
+ * Full ECS snapshot size in GiB, including fractional GiB. Derived from exact provider bytes, never the source disk capacity. Absent until verified.
2931
+ */
2932
+ storageGib?: number;
2893
2933
  taskId?: number;
2894
2934
  updatedAt: string;
2895
2935
  /**
@@ -2897,6 +2937,51 @@ type Snapshot = {
2897
2937
  */
2898
2938
  userId: number;
2899
2939
  };
2940
+ type SSOAppConfiguration = {
2941
+ redirectUris: Array<string>;
2942
+ };
2943
+ type SSOAuthorization = {
2944
+ redirectUrl: string;
2945
+ };
2946
+ type SSOGrant = {
2947
+ appId: string;
2948
+ appName: string;
2949
+ createdAt: string;
2950
+ expiresAt: string;
2951
+ id: string;
2952
+ orgId: number;
2953
+ userId: number;
2954
+ };
2955
+ type SSORequest = {
2956
+ appId: string;
2957
+ appName: string;
2958
+ appOrgId: number;
2959
+ expiresAt: string;
2960
+ id: string;
2961
+ mode: SSOMode;
2962
+ redirectUri: string;
2963
+ };
2964
+ export type SSOTokens = {
2965
+ /**
2966
+ * Only present in org-user mode. Scoped to this user, org and revocable application grant.
2967
+ */
2968
+ accessToken?: string;
2969
+ accountId: number;
2970
+ expiresAt: string;
2971
+ grantId?: string;
2972
+ /**
2973
+ * Only present in identity mode. JWT with sub=string(account_id), account_id, org_id, user_id, iss, aud=app ID, iat, exp and token_use=sso_identity. Never accepted as a brazosd API credential.
2974
+ */
2975
+ identityToken?: string;
2976
+ mode: SSOMode;
2977
+ orgId: number;
2978
+ refreshExpiresAt?: string;
2979
+ /**
2980
+ * Only present in org-user mode. Exchange only at /sso/refresh using the application's service credential.
2981
+ */
2982
+ refreshToken?: string;
2983
+ userId: number;
2984
+ };
2900
2985
  type AcademicLocale = "zh" | "en" | "es";
2901
2986
  type StartAcademicLessonRequest = {
2902
2987
  courseVersion: number;
@@ -3486,6 +3571,30 @@ declare class DefaultService {
3486
3571
  * @throws ApiError
3487
3572
  */
3488
3573
  signOutOtherAccountDevices(): CancelablePromise<void>;
3574
+ /**
3575
+ * List the signed-in account's active application grants
3576
+ * @returns SSOGrant Active application grants
3577
+ * @throws ApiError
3578
+ */
3579
+ listAccountSsoGrants(): CancelablePromise<Array<SSOGrant>>;
3580
+ /**
3581
+ * Revoke an application grant using the owning account login
3582
+ * @returns void
3583
+ * @throws ApiError
3584
+ */
3585
+ revokeAccountSsoGrant({ grantId, }: {
3586
+ grantId: string;
3587
+ }): CancelablePromise<void>;
3588
+ /**
3589
+ * Authorize using a human account login
3590
+ * Uses an account access token, never an application or organization token. The selected org must contain the account; org-user mode additionally requires the application's org. Produces a single-use authorization code, not API credentials.
3591
+ * @returns SSOAuthorization Verified callback URL containing code and state
3592
+ * @throws ApiError
3593
+ */
3594
+ authorizeSsoRequest({ requestId, requestBody, }: {
3595
+ requestId: string;
3596
+ requestBody: AuthorizeSSORequest;
3597
+ }): CancelablePromise<SSOAuthorization>;
3489
3598
  /**
3490
3599
  * Remove an agent contact list member
3491
3600
  * Remove a delegation target from the specified agent within the current org
@@ -5981,6 +6090,58 @@ declare class DefaultService {
5981
6090
  getSnapshot({ snapshotUuid, }: {
5982
6091
  snapshotUuid: string;
5983
6092
  }): CancelablePromise<Snapshot>;
6093
+ /**
6094
+ * Register additional exact SSO callback URLs
6095
+ * Requires permission to manage the application's service user. The application's https hostname with /auth/brazosd/callback is always registered. HTTPS is required except for loopback development callbacks.
6096
+ * @returns SSOAppConfiguration Configured callbacks
6097
+ * @throws ApiError
6098
+ */
6099
+ configureSsoApp({ appId, requestBody, }: {
6100
+ appId: string;
6101
+ requestBody: SSOAppConfiguration;
6102
+ }): CancelablePromise<SSOAppConfiguration>;
6103
+ /**
6104
+ * Revoke a user grant using the application's service identity
6105
+ * @returns void
6106
+ * @throws ApiError
6107
+ */
6108
+ revokeSsoGrant({ grantId, }: {
6109
+ grantId: string;
6110
+ }): CancelablePromise<void>;
6111
+ /**
6112
+ * Rotate an application's organization-user credentials
6113
+ * Authenticates the application's service user as well as its SSO refresh credential. Previous token retries with the same requestId return the same result for two minutes. SSO refresh credentials cannot be used by ordinary refresh endpoints.
6114
+ * @returns SSOTokens Rotated credentials
6115
+ * @throws ApiError
6116
+ */
6117
+ refreshSsoTokens({ requestBody, }: {
6118
+ requestBody: RefreshSSOTokensRequest;
6119
+ }): CancelablePromise<SSOTokens>;
6120
+ /**
6121
+ * Begin an application login
6122
+ * Authenticate using the application's service user. The browser receives only a short-lived request ID; the service credential and PKCE verifier stay on the application server.
6123
+ * @returns SSORequest Login request
6124
+ * @throws ApiError
6125
+ */
6126
+ createSsoRequest({ requestBody, }: {
6127
+ requestBody: CreateSSORequest;
6128
+ }): CancelablePromise<SSORequest>;
6129
+ /**
6130
+ * Preview a short-lived SSO request
6131
+ * @returns SSORequest Application and callback to display before authorization
6132
+ * @throws ApiError
6133
+ */
6134
+ getSsoRequest({ requestId, }: {
6135
+ requestId: string;
6136
+ }): CancelablePromise<SSORequest>;
6137
+ /**
6138
+ * Exchange a single-use authorization code
6139
+ * @returns SSOTokens Organization credentials or an application-specific identity JWT
6140
+ * @throws ApiError
6141
+ */
6142
+ exchangeSsoCode({ requestBody, }: {
6143
+ requestBody: ExchangeSSOCodeRequest;
6144
+ }): CancelablePromise<SSOTokens>;
5984
6145
  /**
5985
6146
  * Get current org merchant profile
5986
6147
  * @returns TradeMerchant Merchant profile returned
@@ -6492,7 +6653,22 @@ type Usage = {
6492
6653
  day: string;
6493
6654
  cpuMillicoreMicroseconds: number;
6494
6655
  memoryMibMicroseconds: number;
6656
+ /**
6657
+ * Total compute and OSS request charges, in microyuan.
6658
+ */
6495
6659
  chargedAmountMicroyuans: number;
6660
+ /**
6661
+ * Observed billable OSS GET-class requests settled on this UTC day.
6662
+ */
6663
+ ossGetRequests: number;
6664
+ /**
6665
+ * Observed billable OSS PUT-class requests settled on this UTC day, including LIST and DELETE.
6666
+ */
6667
+ ossPutRequests: number;
6668
+ /**
6669
+ * OSS portion of chargedAmountMicroyuans.
6670
+ */
6671
+ ossChargedAmountMicroyuans: number;
6496
6672
  incomplete: boolean;
6497
6673
  };
6498
6674
  declare class DefaultService$2 {
@@ -6657,6 +6833,117 @@ interface Credentials$1 {
6657
6833
  export type CredentialProvider = () => Credentials$1 | Promise<Credentials$1>;
6658
6834
  /** Reads only the access credential. Refresh tokens belong to the runtime. */
6659
6835
  export declare function fileCredentials(path?: string): CredentialProvider;
6836
+ export interface SSOIdentity {
6837
+ iss: string;
6838
+ aud: string;
6839
+ sub: string;
6840
+ account_id: number;
6841
+ org_id: number;
6842
+ user_id: number;
6843
+ iat: number;
6844
+ exp: number;
6845
+ token_use: "sso_identity";
6846
+ }
6847
+ export interface SSOJWK extends JsonWebKey$1 {
6848
+ kid: string;
6849
+ exp: number;
6850
+ }
6851
+ export interface CachedSSOKeys {
6852
+ keys: SSOJWK[];
6853
+ freshUntil: number;
6854
+ }
6855
+ /** Store only public keys here; an application's user/session store is separate. */
6856
+ export interface SSOKeyCache {
6857
+ get(issuer: string): Promise<CachedSSOKeys | undefined>;
6858
+ set(issuer: string, keys: CachedSSOKeys): Promise<void>;
6859
+ }
6860
+ /** Persistent SQLite cache. Supply a shared cache adapter when using cloud SQLite. */
6861
+ export declare class SQLiteSSOKeyCache implements SSOKeyCache {
6862
+ readonly filename: string;
6863
+ private database?;
6864
+ constructor(filename: string);
6865
+ private db;
6866
+ get(issuer: string): Promise<CachedSSOKeys | undefined>;
6867
+ set(issuer: string, keys: CachedSSOKeys): Promise<void>;
6868
+ close(): Promise<void>;
6869
+ }
6870
+ export declare class SSOIdentityVerifier {
6871
+ private readonly options;
6872
+ private memory?;
6873
+ private loading?;
6874
+ private fetching?;
6875
+ private lastUnknownRefresh;
6876
+ constructor(options: {
6877
+ issuer: string;
6878
+ audience: string;
6879
+ jwksUrl: string;
6880
+ cache: SSOKeyCache;
6881
+ });
6882
+ private download;
6883
+ private cacheNamespace;
6884
+ private keys;
6885
+ verify(token: string): Promise<SSOIdentity>;
6886
+ }
6887
+ export type SSOUserTokens = SSOTokens & {
6888
+ mode: "org-user";
6889
+ accessToken: string;
6890
+ refreshToken: string;
6891
+ grantId: string;
6892
+ refreshExpiresAt: string;
6893
+ };
6894
+ export type SSOIdentityTokens = SSOTokens & {
6895
+ mode: "identity";
6896
+ identityToken: string;
6897
+ };
6898
+ export interface SSOOptions extends Pick<ClientOptions, "apiUrl" | "credentials" | "credentialsFile"> {
6899
+ appId: string;
6900
+ redirectUri: string;
6901
+ /** 32 random bytes encoded as base64url. Keep secret and stable across instances. */
6902
+ loginSecret: string;
6903
+ /** Public static frontend origin, default https://brazosd.com. */
6904
+ webUrl?: string;
6905
+ issuer?: string;
6906
+ jwksUrl?: string;
6907
+ /** Defaults to ~/.cache/brazosd-sso/jwks.sqlite, plus memory. */
6908
+ keyCache?: SSOKeyCache;
6909
+ }
6910
+ /** The service identity authenticates the application; never use it as a user fallback. */
6911
+ export declare class BrazosdSSO {
6912
+ private readonly options;
6913
+ private readonly service;
6914
+ private readonly secret;
6915
+ private readonly cookiePrefix;
6916
+ private readonly secure;
6917
+ private readonly verifier;
6918
+ private readonly refreshing;
6919
+ constructor(options: SSOOptions);
6920
+ private cookie;
6921
+ private aad;
6922
+ private seal;
6923
+ private open;
6924
+ /** Send setCookie and redirect to authorizationUrl. No service credential enters the URL. */
6925
+ beginLogin(mode: SSOMode): Promise<{
6926
+ authorizationUrl: string;
6927
+ setCookie: string;
6928
+ }>;
6929
+ /** Call only on the registered callback. Persist returned tokens in the application's server-side session store. */
6930
+ completeLogin(callbackUrl: string, cookieHeader: string): Promise<{
6931
+ tokens: SSOUserTokens | SSOIdentityTokens;
6932
+ identity?: SSOIdentity;
6933
+ clearCookie: string;
6934
+ }>;
6935
+ verifyIdentityToken(token: string): Promise<SSOIdentity>;
6936
+ /** Concurrent instances derive the same retry ID from the same refresh credential. */
6937
+ refresh(tokens: SSOUserTokens): Promise<SSOUserTokens>;
6938
+ /** saveTokens must compare-and-swap using expectedRefreshToken when sessions are shared. */
6939
+ userClient(session: {
6940
+ getTokens(): Promise<SSOUserTokens>;
6941
+ saveTokens(tokens: SSOUserTokens, expectedRefreshToken: string): Promise<void>;
6942
+ }): BrazosdClient;
6943
+ /** Also delete the application's own session/cookie after revoking this grant. */
6944
+ revoke(tokens: SSOUserTokens): Promise<void>;
6945
+ }
6946
+ export declare function createSSO(options: SSOOptions): BrazosdSSO;
6660
6947
  export declare class BrazosdError extends Error {
6661
6948
  readonly status: number;
6662
6949
  readonly body: string;
package/index.js CHANGED
@@ -797,6 +797,53 @@ var DefaultService = class {
797
797
  }
798
798
  });
799
799
  }
800
+ /**
801
+ * List the signed-in account's active application grants
802
+ * @returns SSOGrant Active application grants
803
+ * @throws ApiError
804
+ */
805
+ listAccountSsoGrants() {
806
+ return this.httpRequest.request({
807
+ method: "GET",
808
+ url: "/account/sso/grants"
809
+ });
810
+ }
811
+ /**
812
+ * Revoke an application grant using the owning account login
813
+ * @returns void
814
+ * @throws ApiError
815
+ */
816
+ revokeAccountSsoGrant({
817
+ grantId
818
+ }) {
819
+ return this.httpRequest.request({
820
+ method: "DELETE",
821
+ url: "/account/sso/grants/{grantId}",
822
+ path: {
823
+ "grantId": grantId
824
+ }
825
+ });
826
+ }
827
+ /**
828
+ * Authorize using a human account login
829
+ * Uses an account access token, never an application or organization token. The selected org must contain the account; org-user mode additionally requires the application's org. Produces a single-use authorization code, not API credentials.
830
+ * @returns SSOAuthorization Verified callback URL containing code and state
831
+ * @throws ApiError
832
+ */
833
+ authorizeSsoRequest({
834
+ requestId,
835
+ requestBody
836
+ }) {
837
+ return this.httpRequest.request({
838
+ method: "POST",
839
+ url: "/account/sso/requests/{requestId}/authorize",
840
+ path: {
841
+ "requestId": requestId
842
+ },
843
+ body: requestBody,
844
+ mediaType: "application/json"
845
+ });
846
+ }
800
847
  /**
801
848
  * Remove an agent contact list member
802
849
  * Remove a delegation target from the specified agent within the current org
@@ -5733,6 +5780,105 @@ var DefaultService = class {
5733
5780
  }
5734
5781
  });
5735
5782
  }
5783
+ /**
5784
+ * Register additional exact SSO callback URLs
5785
+ * Requires permission to manage the application's service user. The application's https hostname with /auth/brazosd/callback is always registered. HTTPS is required except for loopback development callbacks.
5786
+ * @returns SSOAppConfiguration Configured callbacks
5787
+ * @throws ApiError
5788
+ */
5789
+ configureSsoApp({
5790
+ appId,
5791
+ requestBody
5792
+ }) {
5793
+ return this.httpRequest.request({
5794
+ method: "PUT",
5795
+ url: "/sso/apps/{appId}",
5796
+ path: {
5797
+ "appId": appId
5798
+ },
5799
+ body: requestBody,
5800
+ mediaType: "application/json"
5801
+ });
5802
+ }
5803
+ /**
5804
+ * Revoke a user grant using the application's service identity
5805
+ * @returns void
5806
+ * @throws ApiError
5807
+ */
5808
+ revokeSsoGrant({
5809
+ grantId
5810
+ }) {
5811
+ return this.httpRequest.request({
5812
+ method: "DELETE",
5813
+ url: "/sso/grants/{grantId}",
5814
+ path: {
5815
+ "grantId": grantId
5816
+ }
5817
+ });
5818
+ }
5819
+ /**
5820
+ * Rotate an application's organization-user credentials
5821
+ * Authenticates the application's service user as well as its SSO refresh credential. Previous token retries with the same requestId return the same result for two minutes. SSO refresh credentials cannot be used by ordinary refresh endpoints.
5822
+ * @returns SSOTokens Rotated credentials
5823
+ * @throws ApiError
5824
+ */
5825
+ refreshSsoTokens({
5826
+ requestBody
5827
+ }) {
5828
+ return this.httpRequest.request({
5829
+ method: "POST",
5830
+ url: "/sso/refresh",
5831
+ body: requestBody,
5832
+ mediaType: "application/json"
5833
+ });
5834
+ }
5835
+ /**
5836
+ * Begin an application login
5837
+ * Authenticate using the application's service user. The browser receives only a short-lived request ID; the service credential and PKCE verifier stay on the application server.
5838
+ * @returns SSORequest Login request
5839
+ * @throws ApiError
5840
+ */
5841
+ createSsoRequest({
5842
+ requestBody
5843
+ }) {
5844
+ return this.httpRequest.request({
5845
+ method: "POST",
5846
+ url: "/sso/requests",
5847
+ body: requestBody,
5848
+ mediaType: "application/json"
5849
+ });
5850
+ }
5851
+ /**
5852
+ * Preview a short-lived SSO request
5853
+ * @returns SSORequest Application and callback to display before authorization
5854
+ * @throws ApiError
5855
+ */
5856
+ getSsoRequest({
5857
+ requestId
5858
+ }) {
5859
+ return this.httpRequest.request({
5860
+ method: "GET",
5861
+ url: "/sso/requests/{requestId}",
5862
+ path: {
5863
+ "requestId": requestId
5864
+ }
5865
+ });
5866
+ }
5867
+ /**
5868
+ * Exchange a single-use authorization code
5869
+ * @returns SSOTokens Organization credentials or an application-specific identity JWT
5870
+ * @throws ApiError
5871
+ */
5872
+ exchangeSsoCode({
5873
+ requestBody
5874
+ }) {
5875
+ return this.httpRequest.request({
5876
+ method: "POST",
5877
+ url: "/sso/token",
5878
+ body: requestBody,
5879
+ mediaType: "application/json"
5880
+ });
5881
+ }
5736
5882
  /**
5737
5883
  * Get current org merchant profile
5738
5884
  * @returns TradeMerchant Merchant profile returned
@@ -6881,6 +7027,27 @@ var operations = {
6881
7027
  "401": "void"
6882
7028
  }
6883
7029
  },
7030
+ "GET /account/sso/grants": {
7031
+ "authenticated": true,
7032
+ "redirect": false,
7033
+ "responses": {
7034
+ "200": "json"
7035
+ }
7036
+ },
7037
+ "DELETE /account/sso/grants/{grantId}": {
7038
+ "authenticated": true,
7039
+ "redirect": false,
7040
+ "responses": {
7041
+ "204": "void"
7042
+ }
7043
+ },
7044
+ "POST /account/sso/requests/{requestId}/authorize": {
7045
+ "authenticated": true,
7046
+ "redirect": false,
7047
+ "responses": {
7048
+ "200": "json"
7049
+ }
7050
+ },
6884
7051
  "DELETE /agent-contact-list/{agentId}": {
6885
7052
  "authenticated": true,
6886
7053
  "redirect": false,
@@ -9016,6 +9183,48 @@ var operations = {
9016
9183
  "404": "void"
9017
9184
  }
9018
9185
  },
9186
+ "PUT /sso/apps/{appId}": {
9187
+ "authenticated": true,
9188
+ "redirect": false,
9189
+ "responses": {
9190
+ "200": "json"
9191
+ }
9192
+ },
9193
+ "DELETE /sso/grants/{grantId}": {
9194
+ "authenticated": true,
9195
+ "redirect": false,
9196
+ "responses": {
9197
+ "204": "void"
9198
+ }
9199
+ },
9200
+ "POST /sso/refresh": {
9201
+ "authenticated": true,
9202
+ "redirect": false,
9203
+ "responses": {
9204
+ "200": "json"
9205
+ }
9206
+ },
9207
+ "POST /sso/requests": {
9208
+ "authenticated": true,
9209
+ "redirect": false,
9210
+ "responses": {
9211
+ "201": "json"
9212
+ }
9213
+ },
9214
+ "GET /sso/requests/{requestId}": {
9215
+ "authenticated": false,
9216
+ "redirect": false,
9217
+ "responses": {
9218
+ "200": "json"
9219
+ }
9220
+ },
9221
+ "POST /sso/token": {
9222
+ "authenticated": true,
9223
+ "redirect": false,
9224
+ "responses": {
9225
+ "200": "json"
9226
+ }
9227
+ },
9019
9228
  "GET /trade/merchant": {
9020
9229
  "authenticated": true,
9021
9230
  "redirect": false,
@@ -9573,6 +9782,291 @@ async function execute(context, kind, options, signal) {
9573
9782
  return response.text();
9574
9783
  }
9575
9784
 
9785
+ // src/sso.ts
9786
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
9787
+ import { join } from "node:path";
9788
+ import { homedir } from "node:os";
9789
+
9790
+ // src/sso-jwks.ts
9791
+ import { createPublicKey, verify } from "node:crypto";
9792
+ import { mkdir } from "node:fs/promises";
9793
+ import { dirname } from "node:path";
9794
+ var SQLiteSSOKeyCache = class {
9795
+ constructor(filename) {
9796
+ this.filename = filename;
9797
+ }
9798
+ filename;
9799
+ database;
9800
+ db() {
9801
+ return this.database ??= import("node:sqlite").then(async ({ DatabaseSync }) => {
9802
+ if (this.filename !== ":memory:") await mkdir(dirname(this.filename), { recursive: true, mode: 448 });
9803
+ const db = new DatabaseSync(this.filename);
9804
+ db.exec("PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS brazosd_sso_jwks (issuer TEXT PRIMARY KEY, payload TEXT NOT NULL)");
9805
+ return db;
9806
+ });
9807
+ }
9808
+ async get(issuer) {
9809
+ const row = (await this.db()).prepare("SELECT payload FROM brazosd_sso_jwks WHERE issuer=?").get(issuer);
9810
+ return row ? JSON.parse(String(row.payload)) : void 0;
9811
+ }
9812
+ async set(issuer, keys) {
9813
+ (await this.db()).prepare("INSERT INTO brazosd_sso_jwks(issuer,payload) VALUES(?,?) ON CONFLICT(issuer) DO UPDATE SET payload=excluded.payload").run(issuer, JSON.stringify(keys));
9814
+ }
9815
+ async close() {
9816
+ if (this.database) (await this.database).close();
9817
+ this.database = void 0;
9818
+ }
9819
+ };
9820
+ function decodePart(part) {
9821
+ if (!/^[A-Za-z0-9_-]+$/.test(part)) throw new Error("Invalid SSO JWT encoding");
9822
+ const raw = Buffer.from(part, "base64url");
9823
+ if (raw.toString("base64url") !== part) throw new Error("Invalid SSO JWT encoding");
9824
+ const value = JSON.parse(raw.toString("utf8"));
9825
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid SSO JWT object");
9826
+ return value;
9827
+ }
9828
+ var SSOIdentityVerifier = class {
9829
+ constructor(options) {
9830
+ this.options = options;
9831
+ const url = new URL(options.jwksUrl);
9832
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.hash) throw new Error("Invalid JWKS URL");
9833
+ }
9834
+ options;
9835
+ memory;
9836
+ loading;
9837
+ fetching;
9838
+ lastUnknownRefresh = 0;
9839
+ async download() {
9840
+ if (this.fetching) return this.fetching;
9841
+ const run = async () => {
9842
+ const response = await fetch(this.options.jwksUrl, { redirect: "error", signal: AbortSignal.timeout(1e4) });
9843
+ if (!response.ok) {
9844
+ await response.body?.cancel();
9845
+ throw new Error(`JWKS endpoint returned HTTP ${response.status}`);
9846
+ }
9847
+ const jwks = await response.json();
9848
+ if (!Array.isArray(jwks.keys) || jwks.keys.length > 100) throw new Error("Invalid JWKS response");
9849
+ const ids = /* @__PURE__ */ new Set();
9850
+ for (const key of jwks.keys) {
9851
+ if (key.kty !== "OKP" || key.crv !== "Ed25519" || key.alg !== "EdDSA" || key.use !== "sig" || typeof key.kid !== "string" || !key.kid || ids.has(key.kid) || !Number.isSafeInteger(key.exp) || typeof key.x !== "string" || Buffer.from(key.x, "base64url").length !== 32 || key.d !== void 0) {
9852
+ throw new Error("Invalid SSO signing key");
9853
+ }
9854
+ ids.add(key.kid);
9855
+ }
9856
+ const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(response.headers.get("cache-control") ?? "");
9857
+ const seconds = Math.min(maxAge ? Number(maxAge[1]) : 300, 3600);
9858
+ const keys = { keys: jwks.keys, freshUntil: Date.now() + seconds * 1e3 };
9859
+ await this.options.cache.set(this.cacheNamespace(), keys);
9860
+ this.memory = keys;
9861
+ return keys;
9862
+ };
9863
+ this.fetching = run();
9864
+ try {
9865
+ return await this.fetching;
9866
+ } finally {
9867
+ this.fetching = void 0;
9868
+ }
9869
+ }
9870
+ cacheNamespace() {
9871
+ return this.options.issuer + "\n" + new URL(this.options.jwksUrl).href;
9872
+ }
9873
+ async keys() {
9874
+ if (this.memory && this.memory.freshUntil > Date.now()) return this.memory;
9875
+ if (this.loading) return this.loading;
9876
+ this.loading = (async () => {
9877
+ const stored = await this.options.cache.get(this.cacheNamespace());
9878
+ if (stored && stored.freshUntil > Date.now()) return this.memory = stored;
9879
+ return this.download();
9880
+ })();
9881
+ try {
9882
+ return await this.loading;
9883
+ } finally {
9884
+ this.loading = void 0;
9885
+ }
9886
+ }
9887
+ async verify(token) {
9888
+ if (token.length > 16384) throw new Error("SSO JWT is too large");
9889
+ const parts = token.split(".");
9890
+ if (parts.length !== 3) throw new Error("Invalid SSO JWT");
9891
+ const header = decodePart(parts[0]);
9892
+ const claims = decodePart(parts[1]);
9893
+ if (header.alg !== "EdDSA" || header.typ !== "brazosd-sso+jwt" || typeof header.kid !== "string" || !header.kid || header.kid.length > 128 || header.crit !== void 0 || header.jku !== void 0 || header.jwk !== void 0 || header.x5u !== void 0) throw new Error("Invalid SSO JWT header");
9894
+ if (claims.iss !== this.options.issuer || claims.aud !== this.options.audience || claims.token_use !== "sso_identity") throw new Error("SSO JWT issuer, audience or purpose mismatch");
9895
+ const now = Math.floor(Date.now() / 1e3);
9896
+ if (![claims.account_id, claims.org_id, claims.user_id].every((id) => typeof id === "number" && Number.isSafeInteger(id) && id > 0) || claims.sub !== String(claims.account_id)) throw new Error("Invalid SSO identity");
9897
+ if (typeof claims.exp !== "number" || typeof claims.iat !== "number" || !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat) || claims.exp <= now || claims.iat > now + 30 || claims.exp <= claims.iat || claims.exp - claims.iat > 300 || claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isSafeInteger(claims.nbf) || claims.nbf > now + 30)) throw new Error("SSO JWT expired or has invalid timestamps");
9898
+ let set = await this.keys();
9899
+ let key = set.keys.find((item) => item.kid === header.kid);
9900
+ if (!key && (this.fetching || Date.now() - this.lastUnknownRefresh >= 5e3)) {
9901
+ this.lastUnknownRefresh = Date.now();
9902
+ set = await this.download();
9903
+ key = set.keys.find((item) => item.kid === header.kid);
9904
+ }
9905
+ if (!key || key.exp <= now || claims.exp > key.exp) throw new Error("Unknown or expired SSO signing key");
9906
+ const signature = Buffer.from(parts[2], "base64url");
9907
+ if (signature.length !== 64 || signature.toString("base64url") !== parts[2] || !verify(null, Buffer.from(parts[0] + "." + parts[1]), createPublicKey({ key, format: "jwk" }), signature)) throw new Error("Invalid SSO JWT signature");
9908
+ return claims;
9909
+ }
9910
+ };
9911
+
9912
+ // src/sso.ts
9913
+ function userTokens(tokens) {
9914
+ if (tokens.mode !== "org-user" || !tokens.accessToken || !tokens.refreshToken || !tokens.grantId || !tokens.refreshExpiresAt || tokens.identityToken) throw new Error("Organization-user SSO credentials required");
9915
+ }
9916
+ function sameSecret(a, b) {
9917
+ const x = Buffer.from(a), y = Buffer.from(b);
9918
+ return x.length === y.length && timingSafeEqual(x, y);
9919
+ }
9920
+ var BrazosdSSO = class {
9921
+ constructor(options) {
9922
+ this.options = options;
9923
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(options.appId)) throw new Error("Invalid SSO application ID");
9924
+ this.secret = Buffer.from(options.loginSecret, "base64url");
9925
+ if (this.secret.length !== 32 || this.secret.toString("base64url") !== options.loginSecret) throw new Error("SSO loginSecret must contain 32 random bytes encoded as base64url");
9926
+ const callback = new URL(options.redirectUri);
9927
+ this.secure = callback.protocol === "https:";
9928
+ if (!this.secure && !(callback.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(callback.hostname)) || callback.username || callback.password || callback.hash) throw new Error("SSO callback requires HTTPS, except for loopback development");
9929
+ this.cookiePrefix = (this.secure ? "__Host-" : "") + "brazosd_sso_" + options.appId + "_";
9930
+ this.service = createClient(options);
9931
+ this.verifier = new SSOIdentityVerifier({
9932
+ issuer: options.issuer ?? "https://brazosd.com",
9933
+ audience: options.appId,
9934
+ jwksUrl: options.jwksUrl ?? "https://api.brazosd.com/.well-known/jwks.json",
9935
+ cache: options.keyCache ?? new SQLiteSSOKeyCache(join(homedir(), ".cache", "brazosd-sso", "jwks.sqlite"))
9936
+ });
9937
+ }
9938
+ options;
9939
+ service;
9940
+ secret;
9941
+ cookiePrefix;
9942
+ secure;
9943
+ verifier;
9944
+ refreshing = /* @__PURE__ */ new Map();
9945
+ cookie(state, value, maxAge) {
9946
+ return `${this.cookiePrefix}${state}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${this.secure ? "; Secure" : ""}`;
9947
+ }
9948
+ aad() {
9949
+ return Buffer.from(`brazosd:sso:login:${this.options.appId}:${this.options.redirectUri}`);
9950
+ }
9951
+ seal(transaction) {
9952
+ const iv = randomBytes(12);
9953
+ const cipher = createCipheriv("aes-256-gcm", this.secret, iv);
9954
+ cipher.setAAD(this.aad());
9955
+ const payload = Buffer.concat([cipher.update(JSON.stringify(transaction)), cipher.final()]);
9956
+ return Buffer.concat([iv, cipher.getAuthTag(), payload]).toString("base64url");
9957
+ }
9958
+ open(value) {
9959
+ const data = Buffer.from(value, "base64url");
9960
+ if (data.length < 29 || data.length > 2048) throw new Error("Invalid SSO login cookie");
9961
+ const cipher = createDecipheriv("aes-256-gcm", this.secret, data.subarray(0, 12));
9962
+ cipher.setAAD(this.aad());
9963
+ cipher.setAuthTag(data.subarray(12, 28));
9964
+ return JSON.parse(Buffer.concat([cipher.update(data.subarray(28)), cipher.final()]).toString("utf8"));
9965
+ }
9966
+ /** Send setCookie and redirect to authorizationUrl. No service credential enters the URL. */
9967
+ async beginLogin(mode) {
9968
+ if (mode !== "identity" && mode !== "org-user") throw new Error("Invalid SSO mode");
9969
+ const state = randomBytes(32).toString("base64url");
9970
+ const verifier = randomBytes(32).toString("base64url");
9971
+ const request2 = await this.service.api.createSsoRequest({ requestBody: {
9972
+ appId: this.options.appId,
9973
+ redirectUri: this.options.redirectUri,
9974
+ mode,
9975
+ state,
9976
+ codeChallenge: createHash("sha256").update(verifier).digest("base64url")
9977
+ } });
9978
+ const authorization = new URL(mode === "org-user" ? "/sso/" : "/sso_jwt/", this.options.webUrl ?? "https://brazosd.com");
9979
+ if (!["http:", "https:"].includes(authorization.protocol) || authorization.username || authorization.password) throw new Error("Invalid SSO frontend URL");
9980
+ authorization.searchParams.set("request_id", request2.id);
9981
+ const expiresAt = Date.parse(request2.expiresAt);
9982
+ return { authorizationUrl: authorization.href, setCookie: this.cookie(state, this.seal({ state, verifier, mode, expiresAt }), Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3))) };
9983
+ }
9984
+ /** Call only on the registered callback. Persist returned tokens in the application's server-side session store. */
9985
+ async completeLogin(callbackUrl, cookieHeader) {
9986
+ const callback = new URL(callbackUrl);
9987
+ const registered = new URL(this.options.redirectUri);
9988
+ const state = callback.searchParams.get("state") ?? "";
9989
+ const code = callback.searchParams.get("code") ?? "";
9990
+ if (!/^[A-Za-z0-9_-]{43}$/.test(state) || callback.searchParams.getAll("state").length !== 1 || callback.searchParams.getAll("code").length !== 1) throw new Error("Invalid SSO callback");
9991
+ callback.searchParams.delete("state");
9992
+ callback.searchParams.delete("code");
9993
+ callback.searchParams.sort();
9994
+ registered.searchParams.sort();
9995
+ if (callback.href !== registered.href) throw new Error("SSO callback URL mismatch");
9996
+ const name = this.cookiePrefix + state;
9997
+ const values = cookieHeader.split(";").map((item) => item.trim()).filter((item) => item.startsWith(name + "="));
9998
+ if (values.length !== 1) throw new Error("SSO login cookie is missing or ambiguous");
9999
+ let transaction;
10000
+ try {
10001
+ transaction = this.open(values[0].slice(name.length + 1));
10002
+ } catch {
10003
+ throw new Error("Invalid SSO login cookie");
10004
+ }
10005
+ if (typeof transaction.state !== "string" || !sameSecret(state, transaction.state) || !(transaction.expiresAt > Date.now()) || !["org-user", "identity"].includes(transaction.mode)) throw new Error("SSO login expired or state mismatch");
10006
+ const tokens = await this.service.api.exchangeSsoCode({ requestBody: { appId: this.options.appId, code, redirectUri: this.options.redirectUri, codeVerifier: transaction.verifier } });
10007
+ if (tokens.mode !== transaction.mode) throw new Error("SSO response mode mismatch");
10008
+ const clearCookie = this.cookie(state, "", 0);
10009
+ if (tokens.mode === "org-user") {
10010
+ userTokens(tokens);
10011
+ return { tokens, clearCookie };
10012
+ }
10013
+ if (!tokens.identityToken || tokens.accessToken || tokens.refreshToken) throw new Error("Invalid SSO identity response");
10014
+ const identity = await this.verifyIdentityToken(tokens.identityToken);
10015
+ if (identity.account_id !== tokens.accountId || identity.org_id !== tokens.orgId || identity.user_id !== tokens.userId) throw new Error("SSO identity response mismatch");
10016
+ return { tokens, identity, clearCookie };
10017
+ }
10018
+ verifyIdentityToken(token) {
10019
+ return this.verifier.verify(token);
10020
+ }
10021
+ /** Concurrent instances derive the same retry ID from the same refresh credential. */
10022
+ async refresh(tokens) {
10023
+ userTokens(tokens);
10024
+ if (!(Date.parse(tokens.refreshExpiresAt) > Date.now())) throw new Error("SSO grant expired; log in again");
10025
+ const id = createHash("sha256").update("brazosd-sso-refresh\0" + tokens.refreshToken).digest().subarray(0, 16);
10026
+ id[6] = id[6] & 15 | 64;
10027
+ id[8] = id[8] & 63 | 128;
10028
+ const hex = id.toString("hex");
10029
+ const requestId = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
10030
+ let pending = this.refreshing.get(requestId);
10031
+ if (!pending) {
10032
+ pending = this.service.api.refreshSsoTokens({ requestBody: { appId: this.options.appId, refreshToken: tokens.refreshToken, requestId } }).then((next) => {
10033
+ userTokens(next);
10034
+ if (next.grantId !== tokens.grantId || next.accountId !== tokens.accountId || next.orgId !== tokens.orgId || next.userId !== tokens.userId) throw new Error("SSO refresh identity mismatch");
10035
+ return next;
10036
+ });
10037
+ this.refreshing.set(requestId, pending);
10038
+ }
10039
+ try {
10040
+ return await pending;
10041
+ } finally {
10042
+ if (this.refreshing.get(requestId) === pending) this.refreshing.delete(requestId);
10043
+ }
10044
+ }
10045
+ /** saveTokens must compare-and-swap using expectedRefreshToken when sessions are shared. */
10046
+ userClient(session) {
10047
+ const serviceCredentials = this.options.credentials ?? fileCredentials(this.options.credentialsFile);
10048
+ return createClient({ apiUrl: this.options.apiUrl, credentials: async () => {
10049
+ let tokens = await session.getTokens();
10050
+ userTokens(tokens);
10051
+ if (!(Date.parse(tokens.expiresAt) > Date.now() + 3e4)) {
10052
+ const next = await this.refresh(tokens);
10053
+ await session.saveTokens(next, tokens.refreshToken);
10054
+ tokens = await session.getTokens();
10055
+ userTokens(tokens);
10056
+ }
10057
+ return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, apiUrl: this.options.apiUrl ?? (await serviceCredentials()).apiUrl };
10058
+ } });
10059
+ }
10060
+ /** Also delete the application's own session/cookie after revoking this grant. */
10061
+ async revoke(tokens) {
10062
+ userTokens(tokens);
10063
+ await this.service.api.revokeSsoGrant({ grantId: tokens.grantId });
10064
+ }
10065
+ };
10066
+ function createSSO(options) {
10067
+ return new BrazosdSSO(options);
10068
+ }
10069
+
9576
10070
  // src/index.ts
9577
10071
  var BrazosdClient = class {
9578
10072
  api;
@@ -9595,9 +10089,13 @@ function createClient(options) {
9595
10089
  export {
9596
10090
  BrazosdClient,
9597
10091
  BrazosdError,
10092
+ BrazosdSSO,
9598
10093
  CancelError,
9599
10094
  CancelablePromise,
9600
10095
  DEFAULT_CREDENTIALS_FILE,
10096
+ SQLiteSSOKeyCache,
10097
+ SSOIdentityVerifier,
9601
10098
  createClient,
10099
+ createSSO,
9602
10100
  fileCredentials
9603
10101
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brazosd/node",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Brazosd Node.js SDK with automatic cloud function identity",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,7 +26,7 @@
26
26
  "README.md"
27
27
  ],
28
28
  "engines": {
29
- "node": ">=22"
29
+ "node": ">=22.13"
30
30
  },
31
31
  "scripts": {
32
32
  "generate": "node scripts/generate.mjs",