From 770f95c25e5a8d75cc684ab8e879b2f12c2ba6ff Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 4 Sep 2023 17:07:51 +0200 Subject: [PATCH 01/30] initial --- .github/workflows/generate_schemas.yml | 7 + languages/go/bitwarden_client.go | 50 + languages/go/bitwarden_libary.go | 54 + languages/go/bitwarden_libary_custom.go | 54 + languages/go/build.sh | 8 + languages/go/command_runner.go | 35 + languages/go/go.mod | 5 + languages/go/go.sum | 2 + languages/go/main.go | 101 ++ languages/go/project.go | 118 +++ languages/go/schema.go | 1221 +++++++++++++++++++++++ languages/go/secrets.go | 109 ++ support/scripts/schemas.ts | 10 + 13 files changed, 1774 insertions(+) create mode 100644 languages/go/bitwarden_client.go create mode 100644 languages/go/bitwarden_libary.go create mode 100644 languages/go/bitwarden_libary_custom.go create mode 100755 languages/go/build.sh create mode 100644 languages/go/command_runner.go create mode 100644 languages/go/go.mod create mode 100644 languages/go/go.sum create mode 100644 languages/go/main.go create mode 100644 languages/go/project.go create mode 100644 languages/go/schema.go create mode 100644 languages/go/secrets.go diff --git a/.github/workflows/generate_schemas.yml b/.github/workflows/generate_schemas.yml index a391cfb83..bed0ed484 100644 --- a/.github/workflows/generate_schemas.yml +++ b/.github/workflows/generate_schemas.yml @@ -63,3 +63,10 @@ jobs: name: sdk-schemas-json path: ${{ github.workspace }}/support/schemas/* if-no-files-found: error + + - name: Upload Go schemas artifact + uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2 + with: + name: schemas.go + path: ${{ github.workspace }}/languages/go/schema.go + if-no-files-found: error diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go new file mode 100644 index 000000000..25ec18569 --- /dev/null +++ b/languages/go/bitwarden_client.go @@ -0,0 +1,50 @@ +package main + +import "encoding/json" + +type BitwardenClient struct { + client ClientPointer + lib BitwardenLibrary + commandRunner CommandRunnerInterface + Projects ProjectsInterface + Secrets SecretsInterface +} + +func NewBitwardenClient(settings ClientSettings, lib BitwardenLibrary) *BitwardenClient { + settingsJSON, err := json.Marshal(settings) + if err != nil { + panic(err) + } + + client, err := lib.Init(string(settingsJSON)) + if err != nil { + panic(err) + } + runner := NewCommandRunner(client, lib) + + return &BitwardenClient{ + lib: lib, + client: client, + commandRunner: runner, + Projects: NewProjects(runner), + Secrets: NewSecrets(runner), + } +} + +func (c *BitwardenClient) AccessTokenLogin(accessToken string) ResponseForAPIKeyLoginResponse { + req := AccessTokenLoginRequest{AccessToken: accessToken} + command := Command{AccessTokenLogin: &req} + + responseStr := c.commandRunner.RunCommand(command) + + var response ResponseForAPIKeyLoginResponse + if err := json.Unmarshal([]byte(responseStr), &response); err != nil { + panic(err) + } + + return response +} + +func (c *BitwardenClient) Close() { + c.lib.FreeMem(c.client) +} diff --git a/languages/go/bitwarden_libary.go b/languages/go/bitwarden_libary.go new file mode 100644 index 000000000..887a64ae3 --- /dev/null +++ b/languages/go/bitwarden_libary.go @@ -0,0 +1,54 @@ +//go:build !custom +// +build !custom + +package main + +import ( + "fmt" + "unsafe" +) + +/* +#cgo LDFLAGS: -lbitwarden_c +#cgo linux LDFLAGS: -L/usr/local/lib -L/usr/lib +#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/lib +#include +typedef void* ClientPtr; +extern char* run_command(const char *command, ClientPtr client); +extern ClientPtr init(const char *clientSettings); +extern void free_mem(ClientPtr client); +*/ +import "C" + +type ClientPointer struct { + Pointer C.ClientPtr +} + +type BitwardenLibrary interface { + Init(clientSettings string) (ClientPointer, error) + FreeMem(client ClientPointer) + RunCommand(command string, client ClientPointer) (string, error) +} + +type BitwardenLibraryImpl struct{} + +func (b *BitwardenLibraryImpl) Init(clientSettings string) (ClientPointer, error) { + ptr := C.init(C.CString(clientSettings)) + if ptr == nil { + return ClientPointer{}, fmt.Errorf("initialization failed") + } + return ClientPointer{Pointer: ptr}, nil +} + +func (b *BitwardenLibraryImpl) FreeMem(client ClientPointer) { + C.free_mem(client.Pointer) +} + +func (b *BitwardenLibraryImpl) RunCommand(command string, client ClientPointer) (string, error) { + cstr := C.run_command(C.CString(command), client.Pointer) + if cstr == nil { + return "", fmt.Errorf("run command failed") + } + defer C.free(unsafe.Pointer(cstr)) + return C.GoString(cstr), nil +} diff --git a/languages/go/bitwarden_libary_custom.go b/languages/go/bitwarden_libary_custom.go new file mode 100644 index 000000000..b57020fda --- /dev/null +++ b/languages/go/bitwarden_libary_custom.go @@ -0,0 +1,54 @@ +//go:build custom +// +build custom + +package main + +import ( + "fmt" + "unsafe" +) + +/* +#cgo LDFLAGS: -lbitwarden_c +#cgo linux LDFLAGS: -L/usr/local/lib -L/usr/lib +#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/lib +#include +typedef void* ClientPtr; +extern char* run_command(const char *command, ClientPtr client); +extern ClientPtr init(const char *clientSettings); +extern void free_mem(ClientPtr client); +*/ +import "C" + +type ClientPointer struct { + Pointer C.ClientPtr +} + +type BitwardenLibrary interface { + Init(clientSettings string) (ClientPointer, error) + FreeMem(client ClientPointer) + RunCommand(command string, client ClientPointer) (string, error) +} + +type BitwardenLibraryImpl struct{} + +func (b *BitwardenLibraryImpl) Init(clientSettings string) (ClientPointer, error) { + ptr := C.init(C.CString(clientSettings)) + if ptr == nil { + return ClientPointer{}, fmt.Errorf("initialization failed") + } + return ClientPointer{Pointer: ptr}, nil +} + +func (b *BitwardenLibraryImpl) FreeMem(client ClientPointer) { + C.free_mem(client.Pointer) +} + +func (b *BitwardenLibraryImpl) RunCommand(command string, client ClientPointer) (string, error) { + cstr := C.run_command(C.CString(command), client.Pointer) + if cstr == nil { + return "", fmt.Errorf("run command failed") + } + defer C.free(unsafe.Pointer(cstr)) + return C.GoString(cstr), nil +} diff --git a/languages/go/build.sh b/languages/go/build.sh new file mode 100755 index 000000000..f3a5125f3 --- /dev/null +++ b/languages/go/build.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +if [ -n "$BITWARDEN_LIB_PATH" ]; then + sed "s/{{.LibPath}}/$BITWARDEN_LIB_PATH/g" bitwarden_library.go > bitwarden_library.go + go build -tags custom +else + go build +fi diff --git a/languages/go/command_runner.go b/languages/go/command_runner.go new file mode 100644 index 000000000..5578b5ac1 --- /dev/null +++ b/languages/go/command_runner.go @@ -0,0 +1,35 @@ +package main + +import ( + "encoding/json" +) + +type CommandRunnerInterface interface { + RunCommand(command Command) string +} + +type CommandRunner struct { + client ClientPointer + lib BitwardenLibrary +} + +func NewCommandRunner(client ClientPointer, lib BitwardenLibrary) *CommandRunner { + return &CommandRunner{ + client: client, + lib: lib, + } +} + +func (c *CommandRunner) RunCommand(command Command) string { + commandJSON, err := json.Marshal(command) + if err != nil { + panic(err) + } + + responseStr, err := c.lib.RunCommand(string(commandJSON), c.client) + if err != nil { + panic(err) + } + + return responseStr +} diff --git a/languages/go/go.mod b/languages/go/go.mod new file mode 100644 index 000000000..47a65a149 --- /dev/null +++ b/languages/go/go.mod @@ -0,0 +1,5 @@ +module github.com/bitwarden/sdk + +go 1.20 + +require github.com/gofrs/uuid v4.4.0+incompatible diff --git a/languages/go/go.sum b/languages/go/go.sum new file mode 100644 index 000000000..c0ad68738 --- /dev/null +++ b/languages/go/go.sum @@ -0,0 +1,2 @@ +github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= +github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= diff --git a/languages/go/main.go b/languages/go/main.go new file mode 100644 index 000000000..d016a295a --- /dev/null +++ b/languages/go/main.go @@ -0,0 +1,101 @@ +package main + +import ( + "fmt" + "os" + + "github.com/gofrs/uuid" +) + +func main() { + apiURL := os.Getenv("API_URL") + if apiURL == "" { + apiURL = "https://api.bitwarden.com" // Default + } + identityURL := os.Getenv("IDENTITY_URL") + if identityURL == "" { + identityURL = "https://identity.bitwarden.com" // Default + } + userAgent := os.Getenv("USER_AGENT") + if userAgent == "" { + userAgent = "Bitwarden SDK" // Default + } + + clientSettings := ClientSettings{ + APIURL: apiURL, + IdentityURL: identityURL, + DeviceType: "SDK", + UserAgent: userAgent, + } + + lib := &BitwardenLibraryImpl{} + bitwardenClient := NewBitwardenClient(clientSettings, lib) + + accessToken := os.Getenv("ACCESS_TOKEN") + organizationIDStr := os.Getenv("ORGANIZATION_ID") + projectName := os.Getenv("PROJECT_NAME") + + if projectName == "" { + projectName = "NewTestProject" // default value + } + + responseForAPIKeyLoginResponse := bitwardenClient.AccessTokenLogin(accessToken) + fmt.Println(responseForAPIKeyLoginResponse) + + organizationID, err := uuid.FromString(organizationIDStr) + if err != nil { + panic(err) + } + + responseForProjectResponse, err := bitwardenClient.Projects.Create(organizationID.String(), projectName) + if err != nil { + panic(err) + } + fmt.Println(responseForProjectResponse) + projectID := responseForProjectResponse.Data.ID + fmt.Println(projectID) + + if _, err = bitwardenClient.Projects.List(organizationID.String()); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Projects.Get(projectID); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Projects.Update(projectID, organizationID.String(), projectName+"2"); err != nil { + panic(err) + } + + key := "key" + value := "value" + note := "note" + + responseForSecretResponse, err := bitwardenClient.Secrets.Create(key, value, note, organizationID.String(), []string{projectID}) + if err != nil { + panic(err) + } + secretID := responseForSecretResponse.Data.ID + + if _, err = bitwardenClient.Secrets.List(organizationID.String()); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Secrets.Get(secretID); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Secrets.Update(secretID, key, value, note, organizationID.String(), []string{projectID}); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Secrets.Delete([]string{secretID}); err != nil { + panic(err) + } + + if _, err = bitwardenClient.Projects.Delete([]string{projectID}); err != nil { + panic(err) + } + + bitwardenClient.Close() +} diff --git a/languages/go/project.go b/languages/go/project.go new file mode 100644 index 000000000..c96ca595a --- /dev/null +++ b/languages/go/project.go @@ -0,0 +1,118 @@ +package main + +import ( + "encoding/json" + "fmt" +) + +type ProjectsInterface interface { + Create(organizationID string, name string) (ResponseForProjectResponse, error) + List(organizationID string) (ResponseForProjectsResponse, error) + Get(projectID string) (ResponseForProjectResponse, error) + Update(projectID string, organizationID string, name string) (ResponseForProjectResponse, error) + Delete(projectIDs []string) (ResponseForProjectsDeleteResponse, error) +} + +type Projects struct { + CommandRunner CommandRunnerInterface +} + +func NewProjects(commandRunner CommandRunnerInterface) *Projects { + return &Projects{CommandRunner: commandRunner} +} + +func (p *Projects) Get(id string) (ResponseForProjectResponse, error) { + command := Command{ + Projects: &ProjectsCommand{ + Get: &ProjectGetRequest{ + ID: id, + }, + }, + } + + responseStr := p.CommandRunner.RunCommand(command) + var response ResponseForProjectResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForProjectResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + + return response, nil +} + +func (p *Projects) Create(organizationId string, name string) (ResponseForProjectResponse, error) { + command := Command{ + Projects: &ProjectsCommand{ + Create: &ProjectCreateRequest{ + OrganizationID: organizationId, + Name: name, + }, + }, + } + + return p.executeCommand(command) +} + +func (p *Projects) Update(id, organizationId string, name string) (ResponseForProjectResponse, error) { + command := Command{ + Projects: &ProjectsCommand{ + Update: &ProjectPutRequest{ + ID: id, + OrganizationID: organizationId, + Name: name, + }, + }, + } + + return p.executeCommand(command) +} + +func (p *Projects) Delete(ids []string) (ResponseForProjectsDeleteResponse, error) { + command := Command{ + Projects: &ProjectsCommand{ + Delete: &ProjectsDeleteRequest{ + IDS: ids, + }, + }, + } + + responseStr := p.CommandRunner.RunCommand(command) + var response ResponseForProjectsDeleteResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForProjectsDeleteResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + + return response, nil +} + +func (p *Projects) List(organizationId string) (ResponseForProjectsResponse, error) { + command := Command{ + Projects: &ProjectsCommand{ + List: &ProjectsListRequest{ + OrganizationID: organizationId, + }, + }, + } + + responseStr := p.CommandRunner.RunCommand(command) + var response ResponseForProjectsResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForProjectsResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + + return response, nil +} + +// Helper method for common command execution and response handling +func (p *Projects) executeCommand(command Command) (ResponseForProjectResponse, error) { + responseStr := p.CommandRunner.RunCommand(command) + var response ResponseForProjectResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForProjectResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + + return response, nil +} diff --git a/languages/go/schema.go b/languages/go/schema.go new file mode 100644 index 000000000..6768f9fc5 --- /dev/null +++ b/languages/go/schema.go @@ -0,0 +1,1221 @@ +// This file was generated from JSON Schema using quicktype, do not modify it directly. +// To parse and unparse this JSON data, add this code to your project and do: +// +// clientSettings, err := UnmarshalClientSettings(bytes) +// bytes, err = clientSettings.Marshal() +// +// command, err := UnmarshalCommand(bytes) +// bytes, err = command.Marshal() +// +// docRef, err := UnmarshalDocRef(bytes) +// bytes, err = docRef.Marshal() +// +// responseForAPIKeyLoginResponse, err := UnmarshalResponseForAPIKeyLoginResponse(bytes) +// bytes, err = responseForAPIKeyLoginResponse.Marshal() +// +// responseForFingerprintResponse, err := UnmarshalResponseForFingerprintResponse(bytes) +// bytes, err = responseForFingerprintResponse.Marshal() +// +// responseForPasswordLoginResponse, err := UnmarshalResponseForPasswordLoginResponse(bytes) +// bytes, err = responseForPasswordLoginResponse.Marshal() +// +// responseForProjectResponse, err := UnmarshalResponseForProjectResponse(bytes) +// bytes, err = responseForProjectResponse.Marshal() +// +// responseForProjectsDeleteResponse, err := UnmarshalResponseForProjectsDeleteResponse(bytes) +// bytes, err = responseForProjectsDeleteResponse.Marshal() +// +// responseForProjectsResponse, err := UnmarshalResponseForProjectsResponse(bytes) +// bytes, err = responseForProjectsResponse.Marshal() +// +// responseForSecretIdentifiersResponse, err := UnmarshalResponseForSecretIdentifiersResponse(bytes) +// bytes, err = responseForSecretIdentifiersResponse.Marshal() +// +// responseForSecretResponse, err := UnmarshalResponseForSecretResponse(bytes) +// bytes, err = responseForSecretResponse.Marshal() +// +// responseForSecretsDeleteResponse, err := UnmarshalResponseForSecretsDeleteResponse(bytes) +// bytes, err = responseForSecretsDeleteResponse.Marshal() +// +// responseForSecretsResponse, err := UnmarshalResponseForSecretsResponse(bytes) +// bytes, err = responseForSecretsResponse.Marshal() +// +// responseForSyncResponse, err := UnmarshalResponseForSyncResponse(bytes) +// bytes, err = responseForSyncResponse.Marshal() +// +// responseForUserAPIKeyResponse, err := UnmarshalResponseForUserAPIKeyResponse(bytes) +// bytes, err = responseForUserAPIKeyResponse.Marshal() + +package main + +import "encoding/json" + +func UnmarshalClientSettings(data []byte) (ClientSettings, error) { + var r ClientSettings + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ClientSettings) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalCommand(data []byte) (Command, error) { + var r Command + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *Command) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalDocRef(data []byte) (DocRef, error) { + var r DocRef + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *DocRef) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForAPIKeyLoginResponse(data []byte) (ResponseForAPIKeyLoginResponse, error) { + var r ResponseForAPIKeyLoginResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForAPIKeyLoginResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForFingerprintResponse(data []byte) (ResponseForFingerprintResponse, error) { + var r ResponseForFingerprintResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForFingerprintResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForPasswordLoginResponse(data []byte) (ResponseForPasswordLoginResponse, error) { + var r ResponseForPasswordLoginResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForPasswordLoginResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForProjectResponse(data []byte) (ResponseForProjectResponse, error) { + var r ResponseForProjectResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForProjectResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForProjectsDeleteResponse(data []byte) (ResponseForProjectsDeleteResponse, error) { + var r ResponseForProjectsDeleteResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForProjectsDeleteResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForProjectsResponse(data []byte) (ResponseForProjectsResponse, error) { + var r ResponseForProjectsResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForProjectsResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForSecretIdentifiersResponse(data []byte) (ResponseForSecretIdentifiersResponse, error) { + var r ResponseForSecretIdentifiersResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForSecretIdentifiersResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForSecretResponse(data []byte) (ResponseForSecretResponse, error) { + var r ResponseForSecretResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForSecretResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForSecretsDeleteResponse(data []byte) (ResponseForSecretsDeleteResponse, error) { + var r ResponseForSecretsDeleteResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForSecretsDeleteResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForSecretsResponse(data []byte) (ResponseForSecretsResponse, error) { + var r ResponseForSecretsResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForSecretsResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForSyncResponse(data []byte) (ResponseForSyncResponse, error) { + var r ResponseForSyncResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForSyncResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +func UnmarshalResponseForUserAPIKeyResponse(data []byte) (ResponseForUserAPIKeyResponse, error) { + var r ResponseForUserAPIKeyResponse + err := json.Unmarshal(data, &r) + return r, err +} + +func (r *ResponseForUserAPIKeyResponse) Marshal() ([]byte, error) { + return json.Marshal(r) +} + +// Basic client behavior settings. These settings specify the various targets and behavior +// of the Bitwarden Client. They are optional and uneditable once the client is +// initialized. +// +// Defaults to +// +// ``` # use bitwarden::client::client_settings::{ClientSettings, DeviceType}; # use +// assert_matches::assert_matches; let settings = ClientSettings { identity_url: +// "https://identity.bitwarden.com".to_string(), api_url: +// "https://api.bitwarden.com".to_string(), user_agent: "Bitwarden Rust-SDK".to_string(), +// device_type: DeviceType::SDK, }; let default = ClientSettings::default(); +// assert_matches!(settings, default); ``` +// +// Targets `localhost:8080` for debug builds. +type ClientSettings struct { + // The api url of the targeted Bitwarden instance. Defaults to `https://api.bitwarden.com` + APIURL string `json:"apiUrl"` + // Device type to send to Bitwarden. Defaults to SDK + DeviceType DeviceType `json:"deviceType"` + // The identity url of the targeted Bitwarden instance. Defaults to + // `https://identity.bitwarden.com` + IdentityURL string `json:"identityUrl"` + // The user_agent to sent to Bitwarden. Defaults to `Bitwarden Rust-SDK` + UserAgent string `json:"userAgent"` +} + +// Login with username and password +// +// This command is for initiating an authentication handshake with Bitwarden. Authorization +// may fail due to requiring 2fa or captcha challenge completion despite accurate +// credentials. +// +// This command is not capable of handling authentication requiring 2fa or captcha. +// +// Returns: [PasswordLoginResponse](bitwarden::auth::login::PasswordLoginResponse) +// +// Login with API Key +// +// This command is for initiating an authentication handshake with Bitwarden. +// +// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) +// +// Login with Secrets Manager Access Token +// +// This command is for initiating an authentication handshake with Bitwarden. +// +// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) +// +// > Requires Authentication Get the API key of the currently authenticated user +// +// Returns: [UserApiKeyResponse](bitwarden::platform::UserApiKeyResponse) +// +// Get the user's passphrase +// +// Returns: String +// +// > Requires Authentication Retrieve all user data, ciphers and organizations the user is a +// part of +// +// Returns: [SyncResponse](bitwarden::platform::SyncResponse) +type Command struct { + PasswordLogin *PasswordLoginRequest `json:"passwordLogin,omitempty"` + APIKeyLogin *APIKeyLoginRequest `json:"apiKeyLogin,omitempty"` + AccessTokenLogin *AccessTokenLoginRequest `json:"accessTokenLogin,omitempty"` + GetUserAPIKey *SecretVerificationRequest `json:"getUserApiKey,omitempty"` + Fingerprint *FingerprintRequest `json:"fingerprint,omitempty"` + Sync *SyncRequest `json:"sync,omitempty"` + Secrets *SecretsCommand `json:"secrets,omitempty"` + Projects *ProjectsCommand `json:"projects,omitempty"` +} + +// Login to Bitwarden with Api Key +type APIKeyLoginRequest struct { + // Bitwarden account client_id + ClientID string `json:"clientId"` + // Bitwarden account client_secret + ClientSecret string `json:"clientSecret"` + // Bitwarden account master password + Password string `json:"password"` +} + +// Login to Bitwarden with access token +type AccessTokenLoginRequest struct { + // Bitwarden service API access token + AccessToken string `json:"accessToken"` +} + +type FingerprintRequest struct { + // The input material, used in the fingerprint generation process. + FingerprintMaterial string `json:"fingerprintMaterial"` + // The user's public key encoded with base64. + PublicKey string `json:"publicKey"` +} + +type SecretVerificationRequest struct { + // The user's master password to use for user verification. If supplied, this will be used + // for verification purposes. + MasterPassword *string `json:"masterPassword"` + // Alternate user verification method through OTP. This is provided for users who have no + // master password due to use of Customer Managed Encryption. Must be present and valid if + // master_password is absent. + Otp *string `json:"otp"` +} + +// Login to Bitwarden with Username and Password +type PasswordLoginRequest struct { + // Bitwarden account email address + Email string `json:"email"` + // Bitwarden account master password + Password string `json:"password"` + TwoFactor *TwoFactorRequest `json:"twoFactor"` +} + +type TwoFactorRequest struct { + // Two-factor provider + Provider TwoFactorProvider `json:"provider"` + // Two-factor remember + Remember bool `json:"remember"` + // Two-factor Token + Token string `json:"token"` +} + +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Retrieve a project by the provided identifier +// +// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Creates a new project in the provided organization using the given data +// +// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Lists all projects of the given organization +// +// Returns: [ProjectsResponse](bitwarden::secrets_manager::projects::ProjectsResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Updates an existing project with the provided ID using the given data +// +// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Deletes all the projects whose IDs match the provided ones +// +// Returns: +// [ProjectsDeleteResponse](bitwarden::secrets_manager::projects::ProjectsDeleteResponse) +type ProjectsCommand struct { + Get *ProjectGetRequest `json:"get,omitempty"` + Create *ProjectCreateRequest `json:"create,omitempty"` + List *ProjectsListRequest `json:"list,omitempty"` + Update *ProjectPutRequest `json:"update,omitempty"` + Delete *ProjectsDeleteRequest `json:"delete,omitempty"` +} + +type ProjectCreateRequest struct { + Name string `json:"name"` + // Organization where the project will be created + OrganizationID string `json:"organizationId"` +} + +type ProjectsDeleteRequest struct { + // IDs of the projects to delete + IDS []string `json:"ids"` +} + +type ProjectGetRequest struct { + // ID of the project to retrieve + ID string `json:"id"` +} + +type ProjectsListRequest struct { + // Organization to retrieve all the projects from + OrganizationID string `json:"organizationId"` +} + +type ProjectPutRequest struct { + // ID of the project to modify + ID string `json:"id"` + Name string `json:"name"` + // Organization ID of the project to modify + OrganizationID string `json:"organizationId"` +} + +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Retrieve a secret by the provided identifier +// +// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Retrieve secrets by the provided identifiers +// +// Returns: [SecretsResponse](bitwarden::secrets_manager::secrets::SecretsResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Creates a new secret in the provided organization using the given data +// +// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Lists all secret identifiers of the given organization, to then retrieve each +// secret, use `CreateSecret` +// +// Returns: +// [SecretIdentifiersResponse](bitwarden::secrets_manager::secrets::SecretIdentifiersResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Updates an existing secret with the provided ID using the given data +// +// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) +// +// > Requires Authentication > Requires using an Access Token for login or calling Sync at +// least once Deletes all the secrets whose IDs match the provided ones +// +// Returns: +// [SecretsDeleteResponse](bitwarden::secrets_manager::secrets::SecretsDeleteResponse) +type SecretsCommand struct { + Get *SecretGetRequest `json:"get,omitempty"` + GetByIDS *SecretsGetRequest `json:"getByIds,omitempty"` + Create *SecretCreateRequest `json:"create,omitempty"` + List *SecretIdentifiersRequest `json:"list,omitempty"` + Update *SecretPutRequest `json:"update,omitempty"` + Delete *SecretsDeleteRequest `json:"delete,omitempty"` +} + +type SecretCreateRequest struct { + Key string `json:"key"` + Note string `json:"note"` + // Organization where the secret will be created + OrganizationID string `json:"organizationId"` + // IDs of the projects that this secret will belong to + ProjectIDS []string `json:"projectIds"` + Value string `json:"value"` +} + +type SecretsDeleteRequest struct { + // IDs of the secrets to delete + IDS []string `json:"ids"` +} + +type SecretGetRequest struct { + // ID of the secret to retrieve + ID string `json:"id"` +} + +type SecretsGetRequest struct { + // IDs of the secrets to retrieve + IDS []string `json:"ids"` +} + +type SecretIdentifiersRequest struct { + // Organization to retrieve all the secrets from + OrganizationID string `json:"organizationId"` +} + +type SecretPutRequest struct { + // ID of the secret to modify + ID string `json:"id"` + Key string `json:"key"` + Note string `json:"note"` + // Organization ID of the secret to modify + OrganizationID string `json:"organizationId"` + ProjectIDS []string `json:"projectIds"` + Value string `json:"value"` +} + +type SyncRequest struct { + // Exclude the subdomains from the response, defaults to false + ExcludeSubdomains *bool `json:"excludeSubdomains"` +} + +type DocRef struct { + Cipher *Cipher `json:"Cipher,omitempty"` + CipherView *CipherView `json:"CipherView,omitempty"` + Collection *Collection `json:"Collection,omitempty"` + Folder *Folder `json:"Folder,omitempty"` + FolderView *FolderView `json:"FolderView,omitempty"` + InitCryptoRequest *InitCryptoRequest `json:"InitCryptoRequest,omitempty"` + PasswordGeneratorRequest *PasswordGeneratorRequest `json:"PasswordGeneratorRequest,omitempty"` + PassphraseGeneratorRequest *PassphraseGeneratorRequest `json:"PassphraseGeneratorRequest,omitempty"` + MasterPasswordPolicyOptions *MasterPasswordPolicyOptions `json:"MasterPasswordPolicyOptions,omitempty"` + Kdf *Kdf `json:"Kdf,omitempty"` +} + +type Cipher struct { + Attachments []Attachment `json:"attachments"` + Card *Card `json:"card"` + CollectionIDS []string `json:"collectionIds"` + CreationDate string `json:"creationDate"` + DeletedDate *string `json:"deletedDate"` + Edit bool `json:"edit"` + Favorite bool `json:"favorite"` + Fields []Field `json:"fields"` + FolderID *string `json:"folderId"` + ID *string `json:"id"` + Identity *Identity `json:"identity"` + LocalData *LocalData `json:"localData"` + Login *Login `json:"login"` + Name string `json:"name"` + Notes string `json:"notes"` + OrganizationID *string `json:"organizationId"` + OrganizationUseTotp bool `json:"organizationUseTotp"` + PasswordHistory []PasswordHistory `json:"passwordHistory"` + Reprompt CipherRepromptType `json:"reprompt"` + RevisionDate string `json:"revisionDate"` + SecureNote *SecureNote `json:"secureNote"` + Type CipherType `json:"type"` + ViewPassword bool `json:"viewPassword"` +} + +type Attachment struct { + FileName *string `json:"fileName"` + ID *string `json:"id"` + Key *string `json:"key"` + Size *string `json:"size"` + // Readable size, ex: "4.2 KB" or "1.43 GB" + SizeName *string `json:"sizeName"` + URL *string `json:"url"` +} + +type Card struct { + Brand *string `json:"brand"` + CardholderName *string `json:"cardholderName"` + Code *string `json:"code"` + ExpMonth *string `json:"expMonth"` + ExpYear *string `json:"expYear"` + Number *string `json:"number"` +} + +type Field struct { + LinkedID *LinkedIDType `json:"linkedId"` + Name string `json:"name"` + Type FieldType `json:"type"` + Value string `json:"value"` +} + +type Identity struct { + Address1 *string `json:"address1"` + Address2 *string `json:"address2"` + Address3 *string `json:"address3"` + City *string `json:"city"` + Company *string `json:"company"` + Country *string `json:"country"` + Email *string `json:"email"` + FirstName *string `json:"firstName"` + LastName *string `json:"lastName"` + LicenseNumber *string `json:"licenseNumber"` + MiddleName *string `json:"middleName"` + PassportNumber *string `json:"passportNumber"` + Phone *string `json:"phone"` + PostalCode *string `json:"postalCode"` + Ssn *string `json:"ssn"` + State *string `json:"state"` + Title *string `json:"title"` + Username *string `json:"username"` +} + +type LocalData struct { + LastLaunched *int64 `json:"lastLaunched"` + LastUsedDate *int64 `json:"lastUsedDate"` +} + +type Login struct { + AutofillOnPageLoad *bool `json:"autofillOnPageLoad"` + Password string `json:"password"` + PasswordRevisionDate *string `json:"passwordRevisionDate"` + Totp *string `json:"totp"` + Uris []LoginURI `json:"uris"` + Username string `json:"username"` +} + +type LoginURI struct { + Match *URIMatchType `json:"match"` + URI string `json:"uri"` +} + +type PasswordHistory struct { + LastUsedDate string `json:"lastUsedDate"` + Password string `json:"password"` +} + +type SecureNote struct { + Type SecureNoteType `json:"type"` +} + +type CipherView struct { + Attachments []AttachmentView `json:"attachments"` + Card *CardView `json:"card"` + CollectionIDS []string `json:"collectionIds"` + CreationDate string `json:"creationDate"` + DeletedDate *string `json:"deletedDate"` + Edit bool `json:"edit"` + Favorite bool `json:"favorite"` + Fields []FieldView `json:"fields"` + FolderID *string `json:"folderId"` + ID *string `json:"id"` + Identity *IdentityView `json:"identity"` + LocalData *LocalDataView `json:"localData"` + Login *LoginView `json:"login"` + Name string `json:"name"` + Notes string `json:"notes"` + OrganizationID *string `json:"organizationId"` + OrganizationUseTotp bool `json:"organizationUseTotp"` + PasswordHistory []PasswordHistoryView `json:"passwordHistory"` + Reprompt CipherRepromptType `json:"reprompt"` + RevisionDate string `json:"revisionDate"` + SecureNote *SecureNoteView `json:"secureNote"` + Type CipherType `json:"type"` + ViewPassword bool `json:"viewPassword"` +} + +type AttachmentView struct { + FileName *string `json:"fileName"` + ID *string `json:"id"` + Key *string `json:"key"` + Size *string `json:"size"` + SizeName *string `json:"sizeName"` + URL *string `json:"url"` +} + +type CardView struct { + Brand *string `json:"brand"` + CardholderName *string `json:"cardholderName"` + Code *string `json:"code"` + ExpMonth *string `json:"expMonth"` + ExpYear *string `json:"expYear"` + Number *string `json:"number"` +} + +type FieldView struct { + LinkedID *LinkedIDType `json:"linkedId"` + Name string `json:"name"` + Type FieldType `json:"type"` + Value string `json:"value"` +} + +type IdentityView struct { + Address1 *string `json:"address1"` + Address2 *string `json:"address2"` + Address3 *string `json:"address3"` + City *string `json:"city"` + Company *string `json:"company"` + Country *string `json:"country"` + Email *string `json:"email"` + FirstName *string `json:"firstName"` + LastName *string `json:"lastName"` + LicenseNumber *string `json:"licenseNumber"` + MiddleName *string `json:"middleName"` + PassportNumber *string `json:"passportNumber"` + Phone *string `json:"phone"` + PostalCode *string `json:"postalCode"` + Ssn *string `json:"ssn"` + State *string `json:"state"` + Title *string `json:"title"` + Username *string `json:"username"` +} + +type LocalDataView struct { + LastLaunched *int64 `json:"lastLaunched"` + LastUsedDate *int64 `json:"lastUsedDate"` +} + +type LoginView struct { + AutofillOnPageLoad *bool `json:"autofillOnPageLoad"` + Password string `json:"password"` + PasswordRevisionDate *string `json:"passwordRevisionDate"` + Totp *string `json:"totp"` + Uris []LoginURIView `json:"uris"` + Username string `json:"username"` +} + +type LoginURIView struct { + Match *URIMatchType `json:"match"` + URI string `json:"uri"` +} + +type PasswordHistoryView struct { + LastUsedDate string `json:"lastUsedDate"` + Password string `json:"password"` +} + +type SecureNoteView struct { + Type SecureNoteType `json:"type"` +} + +type Collection struct { + ExternalID *string `json:"externalId"` + HidePasswords bool `json:"hidePasswords"` + ID string `json:"id"` + Name string `json:"name"` + OrganizationID string `json:"organizationId"` + ReadOnly bool `json:"readOnly"` +} + +type Folder struct { + ID string `json:"id"` + Name string `json:"name"` + RevisionDate string `json:"revisionDate"` +} + +type FolderView struct { + ID string `json:"id"` + Name string `json:"name"` + RevisionDate string `json:"revisionDate"` +} + +type InitCryptoRequest struct { + // The user's email address + Email string `json:"email"` + // The user's KDF parameters, as received from the prelogin request + KdfParams Kdf `json:"kdfParams"` + // The encryption keys for all the organizations the user is a part of + OrganizationKeys map[string]string `json:"organizationKeys"` + // The user's master password + Password string `json:"password"` + // The user's encryptred private key + PrivateKey string `json:"privateKey"` + // The user's encrypted symmetric crypto key + UserKey string `json:"userKey"` +} + +// The user's KDF parameters, as received from the prelogin request +type Kdf struct { + PBKDF2 *PBKDF2 `json:"pBKDF2,omitempty"` + Argon2ID *Argon2ID `json:"argon2id,omitempty"` +} + +type Argon2ID struct { + Iterations int64 `json:"iterations"` + Memory int64 `json:"memory"` + Parallelism int64 `json:"parallelism"` +} + +type PBKDF2 struct { + Iterations int64 `json:"iterations"` +} + +type MasterPasswordPolicyOptions struct { + // Flag to indicate if the policy should be enforced on login. If true, and the user's + // password does not meet the policy requirements, the user will be forced to update their + // password. + EnforceOnLogin bool `json:"enforce_on_login"` + MinComplexity int64 `json:"min_complexity"` + MinLength int64 `json:"min_length"` + RequireLower bool `json:"require_lower"` + RequireNumbers bool `json:"require_numbers"` + RequireSpecial bool `json:"require_special"` + RequireUpper bool `json:"require_upper"` +} + +// Passphrase generator request. +// +// The default separator is `-` and default number of words is 3. +type PassphraseGeneratorRequest struct { + Capitalize *bool `json:"capitalize"` + IncludeNumber *bool `json:"includeNumber"` + NumWords *int64 `json:"numWords"` + WordSeparator *string `json:"wordSeparator"` +} + +// Password generator request. If all options are false, the default is to generate a +// password with: - lowercase - uppercase - numbers +// +// The default length is 16. +type PasswordGeneratorRequest struct { + AvoidAmbiguous *bool `json:"avoidAmbiguous"` + Length *int64 `json:"length"` + Lowercase bool `json:"lowercase"` + MinLowercase *bool `json:"minLowercase"` + MinNumber *bool `json:"minNumber"` + MinSpecial *bool `json:"minSpecial"` + MinUppercase *bool `json:"minUppercase"` + Numbers bool `json:"numbers"` + Special bool `json:"special"` + Uppercase bool `json:"uppercase"` +} + +type ResponseForAPIKeyLoginResponse struct { + // The response data. Populated if `success` is true. + Data *APIKeyLoginResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type APIKeyLoginResponse struct { + Authenticated bool `json:"authenticated"` + // Whether or not the user is required to update their master password + ForcePasswordReset bool `json:"forcePasswordReset"` + // TODO: What does this do? + ResetMasterPassword bool `json:"resetMasterPassword"` + TwoFactor *APIKeyLoginResponseTwoFactorProviders `json:"twoFactor"` +} + +type APIKeyLoginResponseTwoFactorProviders struct { + Authenticator *PurpleAuthenticator `json:"authenticator"` + // Duo-backed 2fa + Duo *PurpleDuo `json:"duo"` + // Email 2fa + Email *PurpleEmail `json:"email"` + // Duo-backed 2fa operated by an organization the user is a member of + OrganizationDuo *PurpleDuo `json:"organizationDuo"` + // Presence indicates the user has stored this device as bypassing 2fa + Remember *PurpleRemember `json:"remember"` + // WebAuthn-backed 2fa + WebAuthn *PurpleWebAuthn `json:"webAuthn"` + // Yubikey-backed 2fa + YubiKey *PurpleYubiKey `json:"yubiKey"` +} + +type PurpleAuthenticator struct { +} + +type PurpleDuo struct { + Host string `json:"host"` + Signature string `json:"signature"` +} + +type PurpleEmail struct { + // The email to request a 2fa TOTP for + Email string `json:"email"` +} + +type PurpleRemember struct { +} + +type PurpleWebAuthn struct { +} + +type PurpleYubiKey struct { + // Whether the stored yubikey supports near field communication + NFC bool `json:"nfc"` +} + +type ResponseForFingerprintResponse struct { + // The response data. Populated if `success` is true. + Data *FingerprintResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type FingerprintResponse struct { + Fingerprint string `json:"fingerprint"` +} + +type ResponseForPasswordLoginResponse struct { + // The response data. Populated if `success` is true. + Data *PasswordLoginResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type PasswordLoginResponse struct { + Authenticated bool `json:"authenticated"` + // The information required to present the user with a captcha challenge. Only present when + // authentication fails due to requiring validation of a captcha challenge. + CAPTCHA *CAPTCHAResponse `json:"captcha"` + // Whether or not the user is required to update their master password + ForcePasswordReset bool `json:"forcePasswordReset"` + // TODO: What does this do? + ResetMasterPassword bool `json:"resetMasterPassword"` + // The available two factor authentication options. Present only when authentication fails + // due to requiring a second authentication factor. + TwoFactor *PasswordLoginResponseTwoFactorProviders `json:"twoFactor"` +} + +type CAPTCHAResponse struct { + // hcaptcha site key + SiteKey string `json:"siteKey"` +} + +type PasswordLoginResponseTwoFactorProviders struct { + Authenticator *FluffyAuthenticator `json:"authenticator"` + // Duo-backed 2fa + Duo *FluffyDuo `json:"duo"` + // Email 2fa + Email *FluffyEmail `json:"email"` + // Duo-backed 2fa operated by an organization the user is a member of + OrganizationDuo *FluffyDuo `json:"organizationDuo"` + // Presence indicates the user has stored this device as bypassing 2fa + Remember *FluffyRemember `json:"remember"` + // WebAuthn-backed 2fa + WebAuthn *FluffyWebAuthn `json:"webAuthn"` + // Yubikey-backed 2fa + YubiKey *FluffyYubiKey `json:"yubiKey"` +} + +type FluffyAuthenticator struct { +} + +type FluffyDuo struct { + Host string `json:"host"` + Signature string `json:"signature"` +} + +type FluffyEmail struct { + // The email to request a 2fa TOTP for + Email string `json:"email"` +} + +type FluffyRemember struct { +} + +type FluffyWebAuthn struct { +} + +type FluffyYubiKey struct { + // Whether the stored yubikey supports near field communication + NFC bool `json:"nfc"` +} + +type ResponseForProjectResponse struct { + // The response data. Populated if `success` is true. + Data *ProjectResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type ProjectResponse struct { + CreationDate string `json:"creationDate"` + ID string `json:"id"` + Name string `json:"name"` + Object string `json:"object"` + OrganizationID string `json:"organizationId"` + RevisionDate string `json:"revisionDate"` +} + +type ResponseForProjectsDeleteResponse struct { + // The response data. Populated if `success` is true. + Data *ProjectsDeleteResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type ProjectsDeleteResponse struct { + Data []ProjectDeleteResponse `json:"data"` +} + +type ProjectDeleteResponse struct { + Error *string `json:"error"` + ID string `json:"id"` +} + +type ResponseForProjectsResponse struct { + // The response data. Populated if `success` is true. + Data *ProjectsResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type ProjectsResponse struct { + Data []DatumElement `json:"data"` +} + +type DatumElement struct { + CreationDate string `json:"creationDate"` + ID string `json:"id"` + Name string `json:"name"` + Object string `json:"object"` + OrganizationID string `json:"organizationId"` + RevisionDate string `json:"revisionDate"` +} + +type ResponseForSecretIdentifiersResponse struct { + // The response data. Populated if `success` is true. + Data *SecretIdentifiersResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type SecretIdentifiersResponse struct { + Data []SecretIdentifierResponse `json:"data"` +} + +type SecretIdentifierResponse struct { + ID string `json:"id"` + Key string `json:"key"` + OrganizationID string `json:"organizationId"` +} + +type ResponseForSecretResponse struct { + // The response data. Populated if `success` is true. + Data *SecretResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type SecretResponse struct { + CreationDate string `json:"creationDate"` + ID string `json:"id"` + Key string `json:"key"` + Note string `json:"note"` + Object string `json:"object"` + OrganizationID string `json:"organizationId"` + ProjectID *string `json:"projectId"` + RevisionDate string `json:"revisionDate"` + Value string `json:"value"` +} + +type ResponseForSecretsDeleteResponse struct { + // The response data. Populated if `success` is true. + Data *SecretsDeleteResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type SecretsDeleteResponse struct { + Data []SecretDeleteResponse `json:"data"` +} + +type SecretDeleteResponse struct { + Error *string `json:"error"` + ID string `json:"id"` +} + +type ResponseForSecretsResponse struct { + // The response data. Populated if `success` is true. + Data *SecretsResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type SecretsResponse struct { + Data []DatumClass `json:"data"` +} + +type DatumClass struct { + CreationDate string `json:"creationDate"` + ID string `json:"id"` + Key string `json:"key"` + Note string `json:"note"` + Object string `json:"object"` + OrganizationID string `json:"organizationId"` + ProjectID *string `json:"projectId"` + RevisionDate string `json:"revisionDate"` + Value string `json:"value"` +} + +type ResponseForSyncResponse struct { + // The response data. Populated if `success` is true. + Data *SyncResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type SyncResponse struct { + // List of ciphers accesible by the user + Ciphers []CipherDetailsResponse `json:"ciphers"` + // Data about the user, including their encryption keys and the organizations they are a + // part of + Profile ProfileResponse `json:"profile"` +} + +type CipherDetailsResponse struct { +} + +// Data about the user, including their encryption keys and the organizations they are a +// part of +type ProfileResponse struct { + Email string `json:"email"` + ID string `json:"id"` + Name string `json:"name"` + Organizations []ProfileOrganizationResponse `json:"organizations"` +} + +type ProfileOrganizationResponse struct { + ID string `json:"id"` +} + +type ResponseForUserAPIKeyResponse struct { + // The response data. Populated if `success` is true. + Data *UserAPIKeyResponse `json:"data"` + // A message for any error that may occur. Populated if `success` is false. + ErrorMessage *string `json:"errorMessage"` + // Whether or not the SDK request succeeded. + Success bool `json:"success"` +} + +type UserAPIKeyResponse struct { + // The user's API key, which represents the client_secret portion of an oauth request. + APIKey string `json:"apiKey"` +} + +// Device type to send to Bitwarden. Defaults to SDK +type DeviceType string + +const ( + Android DeviceType = "Android" + AndroidAmazon DeviceType = "AndroidAmazon" + ChromeBrowser DeviceType = "ChromeBrowser" + ChromeExtension DeviceType = "ChromeExtension" + EdgeBrowser DeviceType = "EdgeBrowser" + EdgeExtension DeviceType = "EdgeExtension" + FirefoxBrowser DeviceType = "FirefoxBrowser" + FirefoxExtension DeviceType = "FirefoxExtension" + IEBrowser DeviceType = "IEBrowser" + IOS DeviceType = "iOS" + LinuxDesktop DeviceType = "LinuxDesktop" + MACOSDesktop DeviceType = "MacOsDesktop" + OperaBrowser DeviceType = "OperaBrowser" + OperaExtension DeviceType = "OperaExtension" + SDK DeviceType = "SDK" + SafariBrowser DeviceType = "SafariBrowser" + SafariExtension DeviceType = "SafariExtension" + UWP DeviceType = "UWP" + UnknownBrowser DeviceType = "UnknownBrowser" + VivaldiBrowser DeviceType = "VivaldiBrowser" + VivaldiExtension DeviceType = "VivaldiExtension" + WindowsDesktop DeviceType = "WindowsDesktop" +) + +// Two-factor provider +type TwoFactorProvider string + +const ( + Authenticator TwoFactorProvider = "Authenticator" + Duo TwoFactorProvider = "Duo" + OrganizationDuo TwoFactorProvider = "OrganizationDuo" + Remember TwoFactorProvider = "Remember" + TwoFactorProviderEmail TwoFactorProvider = "Email" + U2F TwoFactorProvider = "U2f" + WebAuthn TwoFactorProvider = "WebAuthn" + Yubikey TwoFactorProvider = "Yubikey" +) + +type LinkedIDType string + +const ( + Address1 LinkedIDType = "Address1" + Address2 LinkedIDType = "Address2" + Address3 LinkedIDType = "Address3" + Brand LinkedIDType = "Brand" + CardholderName LinkedIDType = "CardholderName" + City LinkedIDType = "City" + Code LinkedIDType = "Code" + Company LinkedIDType = "Company" + Country LinkedIDType = "Country" + ExpMonth LinkedIDType = "ExpMonth" + ExpYear LinkedIDType = "ExpYear" + FirstName LinkedIDType = "FirstName" + FullName LinkedIDType = "FullName" + LastName LinkedIDType = "LastName" + LicenseNumber LinkedIDType = "LicenseNumber" + LinkedIDTypeEmail LinkedIDType = "Email" + LinkedIDTypePassword LinkedIDType = "Password" + MiddleName LinkedIDType = "MiddleName" + Number LinkedIDType = "Number" + PassportNumber LinkedIDType = "PassportNumber" + Phone LinkedIDType = "Phone" + PostalCode LinkedIDType = "PostalCode" + Ssn LinkedIDType = "Ssn" + State LinkedIDType = "State" + Title LinkedIDType = "Title" + Username LinkedIDType = "Username" +) + +type FieldType string + +const ( + Boolean FieldType = "Boolean" + Hidden FieldType = "Hidden" + Linked FieldType = "Linked" + Text FieldType = "Text" +) + +type URIMatchType string + +const ( + Domain URIMatchType = "domain" + Exact URIMatchType = "exact" + Host URIMatchType = "host" + Never URIMatchType = "never" + RegularExpression URIMatchType = "regularExpression" + StartsWith URIMatchType = "startsWith" +) + +type CipherRepromptType string + +const ( + CipherRepromptTypePassword CipherRepromptType = "Password" + None CipherRepromptType = "None" +) + +type SecureNoteType string + +const ( + Generic SecureNoteType = "Generic" +) + +type CipherType string + +const ( + CipherTypeCard CipherType = "Card" + CipherTypeIdentity CipherType = "Identity" + CipherTypeLogin CipherType = "Login" + CipherTypeSecureNote CipherType = "SecureNote" +) + diff --git a/languages/go/secrets.go b/languages/go/secrets.go new file mode 100644 index 000000000..bbffe3938 --- /dev/null +++ b/languages/go/secrets.go @@ -0,0 +1,109 @@ +package main + +import ( + "encoding/json" + "fmt" +) + +type SecretsInterface interface { + Create(key, value, note string, organizationID string, projectIDs []string) (ResponseForSecretResponse, error) + List(organizationID string) (ResponseForSecretIdentifiersResponse, error) + Get(secretID string) (ResponseForSecretResponse, error) + Update(secretID string, key, value, note string, organizationID string, projectIDs []string) (ResponseForSecretResponse, error) + Delete(secretIDs []string) (ResponseForSecretsDeleteResponse, error) +} + +type Secrets struct { + CommandRunner CommandRunnerInterface +} + +func NewSecrets(commandRunner CommandRunnerInterface) *Secrets { + return &Secrets{CommandRunner: commandRunner} +} + +func (s *Secrets) Get(id string) (ResponseForSecretResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + Get: &SecretGetRequest{ + ID: id, + }, + }, + } + return s.executeCommand(command) +} + +func (s *Secrets) Create(key, value, note string, organizationId string, projectIds []string) (ResponseForSecretResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + Create: &SecretCreateRequest{ + Key: key, + Value: value, + Note: note, + OrganizationID: organizationId, + ProjectIDS: projectIds, + }, + }, + } + return s.executeCommand(command) +} + +func (s *Secrets) Update(id string, key, value, note string, organizationId string, projectIds []string) (ResponseForSecretResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + Update: &SecretPutRequest{ + ID: id, + Key: key, + Value: value, + Note: note, + OrganizationID: organizationId, + ProjectIDS: projectIds, + }, + }, + } + return s.executeCommand(command) +} + +func (s *Secrets) Delete(ids []string) (ResponseForSecretsDeleteResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + Delete: &SecretsDeleteRequest{ + IDS: ids, + }, + }, + } + responseStr := s.CommandRunner.RunCommand(command) + var response ResponseForSecretsDeleteResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForSecretsDeleteResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + return response, nil +} + +func (s *Secrets) List(organizationId string) (ResponseForSecretIdentifiersResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + List: &SecretIdentifiersRequest{ + OrganizationID: organizationId, + }, + }, + } + responseStr := s.CommandRunner.RunCommand(command) + var response ResponseForSecretIdentifiersResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForSecretIdentifiersResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + return response, nil +} + +// Helper method for common command execution and response handling +func (s *Secrets) executeCommand(command Command) (ResponseForSecretResponse, error) { + responseStr := s.CommandRunner.RunCommand(command) + var response ResponseForSecretResponse + err := json.Unmarshal([]byte(responseStr), &response) + if err != nil { + return ResponseForSecretResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + } + return response, nil +} diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index f5d5bce4e..818e0c3bd 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -62,6 +62,16 @@ async function main() { }); writeToFile("./languages/csharp/schemas.cs", csharp.lines); + + const go = await quicktype({ + inputData, + lang: "go", + rendererOptions: { + "package": "main", + }, + }); + + writeToFile("./languages/go/schema.go", go.lines); } main(); From 9c5c1f161096b4fbce172a2b287ff63630b3c599 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 4 Sep 2023 19:30:12 +0200 Subject: [PATCH 02/30] Adding basic readme --- languages/go/README.md | 116 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 languages/go/README.md diff --git a/languages/go/README.md b/languages/go/README.md new file mode 100644 index 000000000..c7450087b --- /dev/null +++ b/languages/go/README.md @@ -0,0 +1,116 @@ +# Bitwarden SDK in Go + +This SDK is designed to interact with Bitwarden services in Go. It includes implementations for managing projects and secrets, as well as a client interface to facilitate operations like login. + +## Prerequisites + +- Go installed +- C environment to run CGO + +## Installation + +Download the SDK files and place them in your Go project directory. + +## Table of Contents + +- [Initialization](#initialization) +- [Login](#login) +- [Projects](#projects) +- [Secrets](#secrets) +- [Close Client](#close-client) + +--- + +### Initialization + +To initialize the client, you need to import the SDK and create a new `BitwardenClient` instance. + +```go +import "github.com/bitwarden/sdk" + +settings := ClientSettings{ + // Your settings here +} +lib := BitwardenLibraryImpl{} +client := NewBitwardenClient(settings, lib) +``` + +--- + +### Login + +To login using an access token: + +```go +response := client.AccessTokenLogin("your_access_token_here") +``` + +--- + +### Projects + +#### Create a Project + +```go +response, err := client.Projects.Create("organization_id", "project_name") +``` + +#### List Projects + +```go +response, err := client.Projects.List("organization_id") +``` + +#### Update a Project + +```go +response, err := client.Projects.Update("project_id", "organization_id", "new_project_name") +``` + +#### Delete Projects + +```go +response, err := client.Projects.Delete([]string{"project_id_1", "project_id_2"}) +``` + +--- + +### Secrets + +#### Create a Secret + +```go +response, err := client.Secrets.Create("key", "value", "note", "organization_id", []string{"project_id"}) +``` + +#### List Secrets + +```go +response, err := client.Secrets.List("organization_id") +``` + +#### Update a Secret + +```go +response, err := client.Secrets.Update("secret_id", "new_key", "new_value", "new_note", "organization_id", []string{"project_id"}) +``` + +#### Delete Secrets + +```go +response, err := client.Secrets.Delete([]string{"secret_id_1", "secret_id_2"}) +``` + +--- + +### Close Client + +To free up resources: + +```go +client.Close() +``` + +--- + +For more detailed information, refer to the code comments and method signatures. From 706122186ab0eeebe4aad08d42ac6478ab238417 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Tue, 5 Sep 2023 12:01:21 +0200 Subject: [PATCH 03/30] Renaming go package --- languages/go/README.md | 2 +- languages/go/go.mod | 2 +- languages/go/schema.go | 156 +++++++++++++++++++++++++++++++++++++ support/scripts/schemas.ts | 1 - 4 files changed, 158 insertions(+), 3 deletions(-) diff --git a/languages/go/README.md b/languages/go/README.md index c7450087b..117840ffb 100644 --- a/languages/go/README.md +++ b/languages/go/README.md @@ -26,7 +26,7 @@ Download the SDK files and place them in your Go project directory. To initialize the client, you need to import the SDK and create a new `BitwardenClient` instance. ```go -import "github.com/bitwarden/sdk" +import "github.com/bitwarden/sdk/languages/go" settings := ClientSettings{ // Your settings here diff --git a/languages/go/go.mod b/languages/go/go.mod index 47a65a149..a2acc8fef 100644 --- a/languages/go/go.mod +++ b/languages/go/go.mod @@ -1,4 +1,4 @@ -module github.com/bitwarden/sdk +module github.com/bitwarden/sdk/languages/go go 1.20 diff --git a/languages/go/schema.go b/languages/go/schema.go index 6768f9fc5..b6d29fecc 100644 --- a/languages/go/schema.go +++ b/languages/go/schema.go @@ -48,6 +48,8 @@ package main +import "bytes" +import "errors" import "encoding/json" func UnmarshalClientSettings(data []byte) (ClientSettings, error) { @@ -480,6 +482,7 @@ type DocRef struct { InitCryptoRequest *InitCryptoRequest `json:"InitCryptoRequest,omitempty"` PasswordGeneratorRequest *PasswordGeneratorRequest `json:"PasswordGeneratorRequest,omitempty"` PassphraseGeneratorRequest *PassphraseGeneratorRequest `json:"PassphraseGeneratorRequest,omitempty"` + ExportFormat *ExportFormat `json:"ExportFormat"` MasterPasswordPolicyOptions *MasterPasswordPolicyOptions `json:"MasterPasswordPolicyOptions,omitempty"` Kdf *Kdf `json:"Kdf,omitempty"` } @@ -694,6 +697,14 @@ type Collection struct { ReadOnly bool `json:"readOnly"` } +type ExportFormatClass struct { + EncryptedJSON EncryptedJSON `json:"EncryptedJson"` +} + +type EncryptedJSON struct { + Password string `json:"password"` +} + type Folder struct { ID string `json:"id"` Name string `json:"name"` @@ -1219,3 +1230,148 @@ const ( CipherTypeSecureNote CipherType = "SecureNote" ) +type ExportFormatEnum string + +const ( + AccountEncryptedJSON ExportFormatEnum = "AccountEncryptedJson" + CSV ExportFormatEnum = "Csv" + JSON ExportFormatEnum = "Json" +) + +type ExportFormat struct { + Enum *ExportFormatEnum + ExportFormatClass *ExportFormatClass +} + +func (x *ExportFormat) UnmarshalJSON(data []byte) error { + x.ExportFormatClass = nil + x.Enum = nil + var c ExportFormatClass + object, err := unmarshalUnion(data, nil, nil, nil, nil, false, nil, true, &c, false, nil, true, &x.Enum, false) + if err != nil { + return err + } + if object { + x.ExportFormatClass = &c + } + return nil +} + +func (x *ExportFormat) MarshalJSON() ([]byte, error) { + return marshalUnion(nil, nil, nil, nil, false, nil, x.ExportFormatClass != nil, x.ExportFormatClass, false, nil, x.Enum != nil, x.Enum, false) +} + +func unmarshalUnion(data []byte, pi **int64, pf **float64, pb **bool, ps **string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) (bool, error) { + if pi != nil { + *pi = nil + } + if pf != nil { + *pf = nil + } + if pb != nil { + *pb = nil + } + if ps != nil { + *ps = nil + } + + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + tok, err := dec.Token() + if err != nil { + return false, err + } + + switch v := tok.(type) { + case json.Number: + if pi != nil { + i, err := v.Int64() + if err == nil { + *pi = &i + return false, nil + } + } + if pf != nil { + f, err := v.Float64() + if err == nil { + *pf = &f + return false, nil + } + return false, errors.New("Unparsable number") + } + return false, errors.New("Union does not contain number") + case float64: + return false, errors.New("Decoder should not return float64") + case bool: + if pb != nil { + *pb = &v + return false, nil + } + return false, errors.New("Union does not contain bool") + case string: + if haveEnum { + return false, json.Unmarshal(data, pe) + } + if ps != nil { + *ps = &v + return false, nil + } + return false, errors.New("Union does not contain string") + case nil: + if nullable { + return false, nil + } + return false, errors.New("Union does not contain null") + case json.Delim: + if v == '{' { + if haveObject { + return true, json.Unmarshal(data, pc) + } + if haveMap { + return false, json.Unmarshal(data, pm) + } + return false, errors.New("Union does not contain object") + } + if v == '[' { + if haveArray { + return false, json.Unmarshal(data, pa) + } + return false, errors.New("Union does not contain array") + } + return false, errors.New("Cannot handle delimiter") + } + return false, errors.New("Cannot unmarshal union") + +} + +func marshalUnion(pi *int64, pf *float64, pb *bool, ps *string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) ([]byte, error) { + if pi != nil { + return json.Marshal(*pi) + } + if pf != nil { + return json.Marshal(*pf) + } + if pb != nil { + return json.Marshal(*pb) + } + if ps != nil { + return json.Marshal(*ps) + } + if haveArray { + return json.Marshal(pa) + } + if haveObject { + return json.Marshal(pc) + } + if haveMap { + return json.Marshal(pm) + } + if haveEnum { + return json.Marshal(pe) + } + if nullable { + return json.Marshal(nil) + } + return nil, errors.New("Union must not be null") +} + diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index 818e0c3bd..ba420cd95 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -70,7 +70,6 @@ async function main() { "package": "main", }, }); - writeToFile("./languages/go/schema.go", go.lines); } From a277dfde597cab5fffcd4b69792088ab63f7e6dd Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Wed, 6 Sep 2023 10:15:38 +0200 Subject: [PATCH 04/30] ignoring auto-generated schema --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9e450f9ab..17f121cc3 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ crates/bitwarden-napi/src-ts/bitwarden_client/schemas.ts languages/csharp/schemas.cs languages/js_webassembly/bitwarden_client/schemas.ts languages/python/BitwardenClient/schemas.py +languages/go/schema.go From 4742e1cad6f074211da1ac3fc8a4ec354a7a71dd Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Wed, 6 Sep 2023 21:09:01 +0200 Subject: [PATCH 05/30] ignoring auto-generated schema --- languages/go/schema.go | 1377 ---------------------------------------- 1 file changed, 1377 deletions(-) delete mode 100644 languages/go/schema.go diff --git a/languages/go/schema.go b/languages/go/schema.go deleted file mode 100644 index b6d29fecc..000000000 --- a/languages/go/schema.go +++ /dev/null @@ -1,1377 +0,0 @@ -// This file was generated from JSON Schema using quicktype, do not modify it directly. -// To parse and unparse this JSON data, add this code to your project and do: -// -// clientSettings, err := UnmarshalClientSettings(bytes) -// bytes, err = clientSettings.Marshal() -// -// command, err := UnmarshalCommand(bytes) -// bytes, err = command.Marshal() -// -// docRef, err := UnmarshalDocRef(bytes) -// bytes, err = docRef.Marshal() -// -// responseForAPIKeyLoginResponse, err := UnmarshalResponseForAPIKeyLoginResponse(bytes) -// bytes, err = responseForAPIKeyLoginResponse.Marshal() -// -// responseForFingerprintResponse, err := UnmarshalResponseForFingerprintResponse(bytes) -// bytes, err = responseForFingerprintResponse.Marshal() -// -// responseForPasswordLoginResponse, err := UnmarshalResponseForPasswordLoginResponse(bytes) -// bytes, err = responseForPasswordLoginResponse.Marshal() -// -// responseForProjectResponse, err := UnmarshalResponseForProjectResponse(bytes) -// bytes, err = responseForProjectResponse.Marshal() -// -// responseForProjectsDeleteResponse, err := UnmarshalResponseForProjectsDeleteResponse(bytes) -// bytes, err = responseForProjectsDeleteResponse.Marshal() -// -// responseForProjectsResponse, err := UnmarshalResponseForProjectsResponse(bytes) -// bytes, err = responseForProjectsResponse.Marshal() -// -// responseForSecretIdentifiersResponse, err := UnmarshalResponseForSecretIdentifiersResponse(bytes) -// bytes, err = responseForSecretIdentifiersResponse.Marshal() -// -// responseForSecretResponse, err := UnmarshalResponseForSecretResponse(bytes) -// bytes, err = responseForSecretResponse.Marshal() -// -// responseForSecretsDeleteResponse, err := UnmarshalResponseForSecretsDeleteResponse(bytes) -// bytes, err = responseForSecretsDeleteResponse.Marshal() -// -// responseForSecretsResponse, err := UnmarshalResponseForSecretsResponse(bytes) -// bytes, err = responseForSecretsResponse.Marshal() -// -// responseForSyncResponse, err := UnmarshalResponseForSyncResponse(bytes) -// bytes, err = responseForSyncResponse.Marshal() -// -// responseForUserAPIKeyResponse, err := UnmarshalResponseForUserAPIKeyResponse(bytes) -// bytes, err = responseForUserAPIKeyResponse.Marshal() - -package main - -import "bytes" -import "errors" -import "encoding/json" - -func UnmarshalClientSettings(data []byte) (ClientSettings, error) { - var r ClientSettings - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ClientSettings) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalCommand(data []byte) (Command, error) { - var r Command - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *Command) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalDocRef(data []byte) (DocRef, error) { - var r DocRef - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *DocRef) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForAPIKeyLoginResponse(data []byte) (ResponseForAPIKeyLoginResponse, error) { - var r ResponseForAPIKeyLoginResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForAPIKeyLoginResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForFingerprintResponse(data []byte) (ResponseForFingerprintResponse, error) { - var r ResponseForFingerprintResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForFingerprintResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForPasswordLoginResponse(data []byte) (ResponseForPasswordLoginResponse, error) { - var r ResponseForPasswordLoginResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForPasswordLoginResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForProjectResponse(data []byte) (ResponseForProjectResponse, error) { - var r ResponseForProjectResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForProjectResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForProjectsDeleteResponse(data []byte) (ResponseForProjectsDeleteResponse, error) { - var r ResponseForProjectsDeleteResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForProjectsDeleteResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForProjectsResponse(data []byte) (ResponseForProjectsResponse, error) { - var r ResponseForProjectsResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForProjectsResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForSecretIdentifiersResponse(data []byte) (ResponseForSecretIdentifiersResponse, error) { - var r ResponseForSecretIdentifiersResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForSecretIdentifiersResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForSecretResponse(data []byte) (ResponseForSecretResponse, error) { - var r ResponseForSecretResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForSecretResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForSecretsDeleteResponse(data []byte) (ResponseForSecretsDeleteResponse, error) { - var r ResponseForSecretsDeleteResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForSecretsDeleteResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForSecretsResponse(data []byte) (ResponseForSecretsResponse, error) { - var r ResponseForSecretsResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForSecretsResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForSyncResponse(data []byte) (ResponseForSyncResponse, error) { - var r ResponseForSyncResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForSyncResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -func UnmarshalResponseForUserAPIKeyResponse(data []byte) (ResponseForUserAPIKeyResponse, error) { - var r ResponseForUserAPIKeyResponse - err := json.Unmarshal(data, &r) - return r, err -} - -func (r *ResponseForUserAPIKeyResponse) Marshal() ([]byte, error) { - return json.Marshal(r) -} - -// Basic client behavior settings. These settings specify the various targets and behavior -// of the Bitwarden Client. They are optional and uneditable once the client is -// initialized. -// -// Defaults to -// -// ``` # use bitwarden::client::client_settings::{ClientSettings, DeviceType}; # use -// assert_matches::assert_matches; let settings = ClientSettings { identity_url: -// "https://identity.bitwarden.com".to_string(), api_url: -// "https://api.bitwarden.com".to_string(), user_agent: "Bitwarden Rust-SDK".to_string(), -// device_type: DeviceType::SDK, }; let default = ClientSettings::default(); -// assert_matches!(settings, default); ``` -// -// Targets `localhost:8080` for debug builds. -type ClientSettings struct { - // The api url of the targeted Bitwarden instance. Defaults to `https://api.bitwarden.com` - APIURL string `json:"apiUrl"` - // Device type to send to Bitwarden. Defaults to SDK - DeviceType DeviceType `json:"deviceType"` - // The identity url of the targeted Bitwarden instance. Defaults to - // `https://identity.bitwarden.com` - IdentityURL string `json:"identityUrl"` - // The user_agent to sent to Bitwarden. Defaults to `Bitwarden Rust-SDK` - UserAgent string `json:"userAgent"` -} - -// Login with username and password -// -// This command is for initiating an authentication handshake with Bitwarden. Authorization -// may fail due to requiring 2fa or captcha challenge completion despite accurate -// credentials. -// -// This command is not capable of handling authentication requiring 2fa or captcha. -// -// Returns: [PasswordLoginResponse](bitwarden::auth::login::PasswordLoginResponse) -// -// Login with API Key -// -// This command is for initiating an authentication handshake with Bitwarden. -// -// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) -// -// Login with Secrets Manager Access Token -// -// This command is for initiating an authentication handshake with Bitwarden. -// -// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) -// -// > Requires Authentication Get the API key of the currently authenticated user -// -// Returns: [UserApiKeyResponse](bitwarden::platform::UserApiKeyResponse) -// -// Get the user's passphrase -// -// Returns: String -// -// > Requires Authentication Retrieve all user data, ciphers and organizations the user is a -// part of -// -// Returns: [SyncResponse](bitwarden::platform::SyncResponse) -type Command struct { - PasswordLogin *PasswordLoginRequest `json:"passwordLogin,omitempty"` - APIKeyLogin *APIKeyLoginRequest `json:"apiKeyLogin,omitempty"` - AccessTokenLogin *AccessTokenLoginRequest `json:"accessTokenLogin,omitempty"` - GetUserAPIKey *SecretVerificationRequest `json:"getUserApiKey,omitempty"` - Fingerprint *FingerprintRequest `json:"fingerprint,omitempty"` - Sync *SyncRequest `json:"sync,omitempty"` - Secrets *SecretsCommand `json:"secrets,omitempty"` - Projects *ProjectsCommand `json:"projects,omitempty"` -} - -// Login to Bitwarden with Api Key -type APIKeyLoginRequest struct { - // Bitwarden account client_id - ClientID string `json:"clientId"` - // Bitwarden account client_secret - ClientSecret string `json:"clientSecret"` - // Bitwarden account master password - Password string `json:"password"` -} - -// Login to Bitwarden with access token -type AccessTokenLoginRequest struct { - // Bitwarden service API access token - AccessToken string `json:"accessToken"` -} - -type FingerprintRequest struct { - // The input material, used in the fingerprint generation process. - FingerprintMaterial string `json:"fingerprintMaterial"` - // The user's public key encoded with base64. - PublicKey string `json:"publicKey"` -} - -type SecretVerificationRequest struct { - // The user's master password to use for user verification. If supplied, this will be used - // for verification purposes. - MasterPassword *string `json:"masterPassword"` - // Alternate user verification method through OTP. This is provided for users who have no - // master password due to use of Customer Managed Encryption. Must be present and valid if - // master_password is absent. - Otp *string `json:"otp"` -} - -// Login to Bitwarden with Username and Password -type PasswordLoginRequest struct { - // Bitwarden account email address - Email string `json:"email"` - // Bitwarden account master password - Password string `json:"password"` - TwoFactor *TwoFactorRequest `json:"twoFactor"` -} - -type TwoFactorRequest struct { - // Two-factor provider - Provider TwoFactorProvider `json:"provider"` - // Two-factor remember - Remember bool `json:"remember"` - // Two-factor Token - Token string `json:"token"` -} - -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Retrieve a project by the provided identifier -// -// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Creates a new project in the provided organization using the given data -// -// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Lists all projects of the given organization -// -// Returns: [ProjectsResponse](bitwarden::secrets_manager::projects::ProjectsResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Updates an existing project with the provided ID using the given data -// -// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Deletes all the projects whose IDs match the provided ones -// -// Returns: -// [ProjectsDeleteResponse](bitwarden::secrets_manager::projects::ProjectsDeleteResponse) -type ProjectsCommand struct { - Get *ProjectGetRequest `json:"get,omitempty"` - Create *ProjectCreateRequest `json:"create,omitempty"` - List *ProjectsListRequest `json:"list,omitempty"` - Update *ProjectPutRequest `json:"update,omitempty"` - Delete *ProjectsDeleteRequest `json:"delete,omitempty"` -} - -type ProjectCreateRequest struct { - Name string `json:"name"` - // Organization where the project will be created - OrganizationID string `json:"organizationId"` -} - -type ProjectsDeleteRequest struct { - // IDs of the projects to delete - IDS []string `json:"ids"` -} - -type ProjectGetRequest struct { - // ID of the project to retrieve - ID string `json:"id"` -} - -type ProjectsListRequest struct { - // Organization to retrieve all the projects from - OrganizationID string `json:"organizationId"` -} - -type ProjectPutRequest struct { - // ID of the project to modify - ID string `json:"id"` - Name string `json:"name"` - // Organization ID of the project to modify - OrganizationID string `json:"organizationId"` -} - -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Retrieve a secret by the provided identifier -// -// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Retrieve secrets by the provided identifiers -// -// Returns: [SecretsResponse](bitwarden::secrets_manager::secrets::SecretsResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Creates a new secret in the provided organization using the given data -// -// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Lists all secret identifiers of the given organization, to then retrieve each -// secret, use `CreateSecret` -// -// Returns: -// [SecretIdentifiersResponse](bitwarden::secrets_manager::secrets::SecretIdentifiersResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Updates an existing secret with the provided ID using the given data -// -// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) -// -// > Requires Authentication > Requires using an Access Token for login or calling Sync at -// least once Deletes all the secrets whose IDs match the provided ones -// -// Returns: -// [SecretsDeleteResponse](bitwarden::secrets_manager::secrets::SecretsDeleteResponse) -type SecretsCommand struct { - Get *SecretGetRequest `json:"get,omitempty"` - GetByIDS *SecretsGetRequest `json:"getByIds,omitempty"` - Create *SecretCreateRequest `json:"create,omitempty"` - List *SecretIdentifiersRequest `json:"list,omitempty"` - Update *SecretPutRequest `json:"update,omitempty"` - Delete *SecretsDeleteRequest `json:"delete,omitempty"` -} - -type SecretCreateRequest struct { - Key string `json:"key"` - Note string `json:"note"` - // Organization where the secret will be created - OrganizationID string `json:"organizationId"` - // IDs of the projects that this secret will belong to - ProjectIDS []string `json:"projectIds"` - Value string `json:"value"` -} - -type SecretsDeleteRequest struct { - // IDs of the secrets to delete - IDS []string `json:"ids"` -} - -type SecretGetRequest struct { - // ID of the secret to retrieve - ID string `json:"id"` -} - -type SecretsGetRequest struct { - // IDs of the secrets to retrieve - IDS []string `json:"ids"` -} - -type SecretIdentifiersRequest struct { - // Organization to retrieve all the secrets from - OrganizationID string `json:"organizationId"` -} - -type SecretPutRequest struct { - // ID of the secret to modify - ID string `json:"id"` - Key string `json:"key"` - Note string `json:"note"` - // Organization ID of the secret to modify - OrganizationID string `json:"organizationId"` - ProjectIDS []string `json:"projectIds"` - Value string `json:"value"` -} - -type SyncRequest struct { - // Exclude the subdomains from the response, defaults to false - ExcludeSubdomains *bool `json:"excludeSubdomains"` -} - -type DocRef struct { - Cipher *Cipher `json:"Cipher,omitempty"` - CipherView *CipherView `json:"CipherView,omitempty"` - Collection *Collection `json:"Collection,omitempty"` - Folder *Folder `json:"Folder,omitempty"` - FolderView *FolderView `json:"FolderView,omitempty"` - InitCryptoRequest *InitCryptoRequest `json:"InitCryptoRequest,omitempty"` - PasswordGeneratorRequest *PasswordGeneratorRequest `json:"PasswordGeneratorRequest,omitempty"` - PassphraseGeneratorRequest *PassphraseGeneratorRequest `json:"PassphraseGeneratorRequest,omitempty"` - ExportFormat *ExportFormat `json:"ExportFormat"` - MasterPasswordPolicyOptions *MasterPasswordPolicyOptions `json:"MasterPasswordPolicyOptions,omitempty"` - Kdf *Kdf `json:"Kdf,omitempty"` -} - -type Cipher struct { - Attachments []Attachment `json:"attachments"` - Card *Card `json:"card"` - CollectionIDS []string `json:"collectionIds"` - CreationDate string `json:"creationDate"` - DeletedDate *string `json:"deletedDate"` - Edit bool `json:"edit"` - Favorite bool `json:"favorite"` - Fields []Field `json:"fields"` - FolderID *string `json:"folderId"` - ID *string `json:"id"` - Identity *Identity `json:"identity"` - LocalData *LocalData `json:"localData"` - Login *Login `json:"login"` - Name string `json:"name"` - Notes string `json:"notes"` - OrganizationID *string `json:"organizationId"` - OrganizationUseTotp bool `json:"organizationUseTotp"` - PasswordHistory []PasswordHistory `json:"passwordHistory"` - Reprompt CipherRepromptType `json:"reprompt"` - RevisionDate string `json:"revisionDate"` - SecureNote *SecureNote `json:"secureNote"` - Type CipherType `json:"type"` - ViewPassword bool `json:"viewPassword"` -} - -type Attachment struct { - FileName *string `json:"fileName"` - ID *string `json:"id"` - Key *string `json:"key"` - Size *string `json:"size"` - // Readable size, ex: "4.2 KB" or "1.43 GB" - SizeName *string `json:"sizeName"` - URL *string `json:"url"` -} - -type Card struct { - Brand *string `json:"brand"` - CardholderName *string `json:"cardholderName"` - Code *string `json:"code"` - ExpMonth *string `json:"expMonth"` - ExpYear *string `json:"expYear"` - Number *string `json:"number"` -} - -type Field struct { - LinkedID *LinkedIDType `json:"linkedId"` - Name string `json:"name"` - Type FieldType `json:"type"` - Value string `json:"value"` -} - -type Identity struct { - Address1 *string `json:"address1"` - Address2 *string `json:"address2"` - Address3 *string `json:"address3"` - City *string `json:"city"` - Company *string `json:"company"` - Country *string `json:"country"` - Email *string `json:"email"` - FirstName *string `json:"firstName"` - LastName *string `json:"lastName"` - LicenseNumber *string `json:"licenseNumber"` - MiddleName *string `json:"middleName"` - PassportNumber *string `json:"passportNumber"` - Phone *string `json:"phone"` - PostalCode *string `json:"postalCode"` - Ssn *string `json:"ssn"` - State *string `json:"state"` - Title *string `json:"title"` - Username *string `json:"username"` -} - -type LocalData struct { - LastLaunched *int64 `json:"lastLaunched"` - LastUsedDate *int64 `json:"lastUsedDate"` -} - -type Login struct { - AutofillOnPageLoad *bool `json:"autofillOnPageLoad"` - Password string `json:"password"` - PasswordRevisionDate *string `json:"passwordRevisionDate"` - Totp *string `json:"totp"` - Uris []LoginURI `json:"uris"` - Username string `json:"username"` -} - -type LoginURI struct { - Match *URIMatchType `json:"match"` - URI string `json:"uri"` -} - -type PasswordHistory struct { - LastUsedDate string `json:"lastUsedDate"` - Password string `json:"password"` -} - -type SecureNote struct { - Type SecureNoteType `json:"type"` -} - -type CipherView struct { - Attachments []AttachmentView `json:"attachments"` - Card *CardView `json:"card"` - CollectionIDS []string `json:"collectionIds"` - CreationDate string `json:"creationDate"` - DeletedDate *string `json:"deletedDate"` - Edit bool `json:"edit"` - Favorite bool `json:"favorite"` - Fields []FieldView `json:"fields"` - FolderID *string `json:"folderId"` - ID *string `json:"id"` - Identity *IdentityView `json:"identity"` - LocalData *LocalDataView `json:"localData"` - Login *LoginView `json:"login"` - Name string `json:"name"` - Notes string `json:"notes"` - OrganizationID *string `json:"organizationId"` - OrganizationUseTotp bool `json:"organizationUseTotp"` - PasswordHistory []PasswordHistoryView `json:"passwordHistory"` - Reprompt CipherRepromptType `json:"reprompt"` - RevisionDate string `json:"revisionDate"` - SecureNote *SecureNoteView `json:"secureNote"` - Type CipherType `json:"type"` - ViewPassword bool `json:"viewPassword"` -} - -type AttachmentView struct { - FileName *string `json:"fileName"` - ID *string `json:"id"` - Key *string `json:"key"` - Size *string `json:"size"` - SizeName *string `json:"sizeName"` - URL *string `json:"url"` -} - -type CardView struct { - Brand *string `json:"brand"` - CardholderName *string `json:"cardholderName"` - Code *string `json:"code"` - ExpMonth *string `json:"expMonth"` - ExpYear *string `json:"expYear"` - Number *string `json:"number"` -} - -type FieldView struct { - LinkedID *LinkedIDType `json:"linkedId"` - Name string `json:"name"` - Type FieldType `json:"type"` - Value string `json:"value"` -} - -type IdentityView struct { - Address1 *string `json:"address1"` - Address2 *string `json:"address2"` - Address3 *string `json:"address3"` - City *string `json:"city"` - Company *string `json:"company"` - Country *string `json:"country"` - Email *string `json:"email"` - FirstName *string `json:"firstName"` - LastName *string `json:"lastName"` - LicenseNumber *string `json:"licenseNumber"` - MiddleName *string `json:"middleName"` - PassportNumber *string `json:"passportNumber"` - Phone *string `json:"phone"` - PostalCode *string `json:"postalCode"` - Ssn *string `json:"ssn"` - State *string `json:"state"` - Title *string `json:"title"` - Username *string `json:"username"` -} - -type LocalDataView struct { - LastLaunched *int64 `json:"lastLaunched"` - LastUsedDate *int64 `json:"lastUsedDate"` -} - -type LoginView struct { - AutofillOnPageLoad *bool `json:"autofillOnPageLoad"` - Password string `json:"password"` - PasswordRevisionDate *string `json:"passwordRevisionDate"` - Totp *string `json:"totp"` - Uris []LoginURIView `json:"uris"` - Username string `json:"username"` -} - -type LoginURIView struct { - Match *URIMatchType `json:"match"` - URI string `json:"uri"` -} - -type PasswordHistoryView struct { - LastUsedDate string `json:"lastUsedDate"` - Password string `json:"password"` -} - -type SecureNoteView struct { - Type SecureNoteType `json:"type"` -} - -type Collection struct { - ExternalID *string `json:"externalId"` - HidePasswords bool `json:"hidePasswords"` - ID string `json:"id"` - Name string `json:"name"` - OrganizationID string `json:"organizationId"` - ReadOnly bool `json:"readOnly"` -} - -type ExportFormatClass struct { - EncryptedJSON EncryptedJSON `json:"EncryptedJson"` -} - -type EncryptedJSON struct { - Password string `json:"password"` -} - -type Folder struct { - ID string `json:"id"` - Name string `json:"name"` - RevisionDate string `json:"revisionDate"` -} - -type FolderView struct { - ID string `json:"id"` - Name string `json:"name"` - RevisionDate string `json:"revisionDate"` -} - -type InitCryptoRequest struct { - // The user's email address - Email string `json:"email"` - // The user's KDF parameters, as received from the prelogin request - KdfParams Kdf `json:"kdfParams"` - // The encryption keys for all the organizations the user is a part of - OrganizationKeys map[string]string `json:"organizationKeys"` - // The user's master password - Password string `json:"password"` - // The user's encryptred private key - PrivateKey string `json:"privateKey"` - // The user's encrypted symmetric crypto key - UserKey string `json:"userKey"` -} - -// The user's KDF parameters, as received from the prelogin request -type Kdf struct { - PBKDF2 *PBKDF2 `json:"pBKDF2,omitempty"` - Argon2ID *Argon2ID `json:"argon2id,omitempty"` -} - -type Argon2ID struct { - Iterations int64 `json:"iterations"` - Memory int64 `json:"memory"` - Parallelism int64 `json:"parallelism"` -} - -type PBKDF2 struct { - Iterations int64 `json:"iterations"` -} - -type MasterPasswordPolicyOptions struct { - // Flag to indicate if the policy should be enforced on login. If true, and the user's - // password does not meet the policy requirements, the user will be forced to update their - // password. - EnforceOnLogin bool `json:"enforce_on_login"` - MinComplexity int64 `json:"min_complexity"` - MinLength int64 `json:"min_length"` - RequireLower bool `json:"require_lower"` - RequireNumbers bool `json:"require_numbers"` - RequireSpecial bool `json:"require_special"` - RequireUpper bool `json:"require_upper"` -} - -// Passphrase generator request. -// -// The default separator is `-` and default number of words is 3. -type PassphraseGeneratorRequest struct { - Capitalize *bool `json:"capitalize"` - IncludeNumber *bool `json:"includeNumber"` - NumWords *int64 `json:"numWords"` - WordSeparator *string `json:"wordSeparator"` -} - -// Password generator request. If all options are false, the default is to generate a -// password with: - lowercase - uppercase - numbers -// -// The default length is 16. -type PasswordGeneratorRequest struct { - AvoidAmbiguous *bool `json:"avoidAmbiguous"` - Length *int64 `json:"length"` - Lowercase bool `json:"lowercase"` - MinLowercase *bool `json:"minLowercase"` - MinNumber *bool `json:"minNumber"` - MinSpecial *bool `json:"minSpecial"` - MinUppercase *bool `json:"minUppercase"` - Numbers bool `json:"numbers"` - Special bool `json:"special"` - Uppercase bool `json:"uppercase"` -} - -type ResponseForAPIKeyLoginResponse struct { - // The response data. Populated if `success` is true. - Data *APIKeyLoginResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type APIKeyLoginResponse struct { - Authenticated bool `json:"authenticated"` - // Whether or not the user is required to update their master password - ForcePasswordReset bool `json:"forcePasswordReset"` - // TODO: What does this do? - ResetMasterPassword bool `json:"resetMasterPassword"` - TwoFactor *APIKeyLoginResponseTwoFactorProviders `json:"twoFactor"` -} - -type APIKeyLoginResponseTwoFactorProviders struct { - Authenticator *PurpleAuthenticator `json:"authenticator"` - // Duo-backed 2fa - Duo *PurpleDuo `json:"duo"` - // Email 2fa - Email *PurpleEmail `json:"email"` - // Duo-backed 2fa operated by an organization the user is a member of - OrganizationDuo *PurpleDuo `json:"organizationDuo"` - // Presence indicates the user has stored this device as bypassing 2fa - Remember *PurpleRemember `json:"remember"` - // WebAuthn-backed 2fa - WebAuthn *PurpleWebAuthn `json:"webAuthn"` - // Yubikey-backed 2fa - YubiKey *PurpleYubiKey `json:"yubiKey"` -} - -type PurpleAuthenticator struct { -} - -type PurpleDuo struct { - Host string `json:"host"` - Signature string `json:"signature"` -} - -type PurpleEmail struct { - // The email to request a 2fa TOTP for - Email string `json:"email"` -} - -type PurpleRemember struct { -} - -type PurpleWebAuthn struct { -} - -type PurpleYubiKey struct { - // Whether the stored yubikey supports near field communication - NFC bool `json:"nfc"` -} - -type ResponseForFingerprintResponse struct { - // The response data. Populated if `success` is true. - Data *FingerprintResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type FingerprintResponse struct { - Fingerprint string `json:"fingerprint"` -} - -type ResponseForPasswordLoginResponse struct { - // The response data. Populated if `success` is true. - Data *PasswordLoginResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type PasswordLoginResponse struct { - Authenticated bool `json:"authenticated"` - // The information required to present the user with a captcha challenge. Only present when - // authentication fails due to requiring validation of a captcha challenge. - CAPTCHA *CAPTCHAResponse `json:"captcha"` - // Whether or not the user is required to update their master password - ForcePasswordReset bool `json:"forcePasswordReset"` - // TODO: What does this do? - ResetMasterPassword bool `json:"resetMasterPassword"` - // The available two factor authentication options. Present only when authentication fails - // due to requiring a second authentication factor. - TwoFactor *PasswordLoginResponseTwoFactorProviders `json:"twoFactor"` -} - -type CAPTCHAResponse struct { - // hcaptcha site key - SiteKey string `json:"siteKey"` -} - -type PasswordLoginResponseTwoFactorProviders struct { - Authenticator *FluffyAuthenticator `json:"authenticator"` - // Duo-backed 2fa - Duo *FluffyDuo `json:"duo"` - // Email 2fa - Email *FluffyEmail `json:"email"` - // Duo-backed 2fa operated by an organization the user is a member of - OrganizationDuo *FluffyDuo `json:"organizationDuo"` - // Presence indicates the user has stored this device as bypassing 2fa - Remember *FluffyRemember `json:"remember"` - // WebAuthn-backed 2fa - WebAuthn *FluffyWebAuthn `json:"webAuthn"` - // Yubikey-backed 2fa - YubiKey *FluffyYubiKey `json:"yubiKey"` -} - -type FluffyAuthenticator struct { -} - -type FluffyDuo struct { - Host string `json:"host"` - Signature string `json:"signature"` -} - -type FluffyEmail struct { - // The email to request a 2fa TOTP for - Email string `json:"email"` -} - -type FluffyRemember struct { -} - -type FluffyWebAuthn struct { -} - -type FluffyYubiKey struct { - // Whether the stored yubikey supports near field communication - NFC bool `json:"nfc"` -} - -type ResponseForProjectResponse struct { - // The response data. Populated if `success` is true. - Data *ProjectResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type ProjectResponse struct { - CreationDate string `json:"creationDate"` - ID string `json:"id"` - Name string `json:"name"` - Object string `json:"object"` - OrganizationID string `json:"organizationId"` - RevisionDate string `json:"revisionDate"` -} - -type ResponseForProjectsDeleteResponse struct { - // The response data. Populated if `success` is true. - Data *ProjectsDeleteResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type ProjectsDeleteResponse struct { - Data []ProjectDeleteResponse `json:"data"` -} - -type ProjectDeleteResponse struct { - Error *string `json:"error"` - ID string `json:"id"` -} - -type ResponseForProjectsResponse struct { - // The response data. Populated if `success` is true. - Data *ProjectsResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type ProjectsResponse struct { - Data []DatumElement `json:"data"` -} - -type DatumElement struct { - CreationDate string `json:"creationDate"` - ID string `json:"id"` - Name string `json:"name"` - Object string `json:"object"` - OrganizationID string `json:"organizationId"` - RevisionDate string `json:"revisionDate"` -} - -type ResponseForSecretIdentifiersResponse struct { - // The response data. Populated if `success` is true. - Data *SecretIdentifiersResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type SecretIdentifiersResponse struct { - Data []SecretIdentifierResponse `json:"data"` -} - -type SecretIdentifierResponse struct { - ID string `json:"id"` - Key string `json:"key"` - OrganizationID string `json:"organizationId"` -} - -type ResponseForSecretResponse struct { - // The response data. Populated if `success` is true. - Data *SecretResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type SecretResponse struct { - CreationDate string `json:"creationDate"` - ID string `json:"id"` - Key string `json:"key"` - Note string `json:"note"` - Object string `json:"object"` - OrganizationID string `json:"organizationId"` - ProjectID *string `json:"projectId"` - RevisionDate string `json:"revisionDate"` - Value string `json:"value"` -} - -type ResponseForSecretsDeleteResponse struct { - // The response data. Populated if `success` is true. - Data *SecretsDeleteResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type SecretsDeleteResponse struct { - Data []SecretDeleteResponse `json:"data"` -} - -type SecretDeleteResponse struct { - Error *string `json:"error"` - ID string `json:"id"` -} - -type ResponseForSecretsResponse struct { - // The response data. Populated if `success` is true. - Data *SecretsResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type SecretsResponse struct { - Data []DatumClass `json:"data"` -} - -type DatumClass struct { - CreationDate string `json:"creationDate"` - ID string `json:"id"` - Key string `json:"key"` - Note string `json:"note"` - Object string `json:"object"` - OrganizationID string `json:"organizationId"` - ProjectID *string `json:"projectId"` - RevisionDate string `json:"revisionDate"` - Value string `json:"value"` -} - -type ResponseForSyncResponse struct { - // The response data. Populated if `success` is true. - Data *SyncResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type SyncResponse struct { - // List of ciphers accesible by the user - Ciphers []CipherDetailsResponse `json:"ciphers"` - // Data about the user, including their encryption keys and the organizations they are a - // part of - Profile ProfileResponse `json:"profile"` -} - -type CipherDetailsResponse struct { -} - -// Data about the user, including their encryption keys and the organizations they are a -// part of -type ProfileResponse struct { - Email string `json:"email"` - ID string `json:"id"` - Name string `json:"name"` - Organizations []ProfileOrganizationResponse `json:"organizations"` -} - -type ProfileOrganizationResponse struct { - ID string `json:"id"` -} - -type ResponseForUserAPIKeyResponse struct { - // The response data. Populated if `success` is true. - Data *UserAPIKeyResponse `json:"data"` - // A message for any error that may occur. Populated if `success` is false. - ErrorMessage *string `json:"errorMessage"` - // Whether or not the SDK request succeeded. - Success bool `json:"success"` -} - -type UserAPIKeyResponse struct { - // The user's API key, which represents the client_secret portion of an oauth request. - APIKey string `json:"apiKey"` -} - -// Device type to send to Bitwarden. Defaults to SDK -type DeviceType string - -const ( - Android DeviceType = "Android" - AndroidAmazon DeviceType = "AndroidAmazon" - ChromeBrowser DeviceType = "ChromeBrowser" - ChromeExtension DeviceType = "ChromeExtension" - EdgeBrowser DeviceType = "EdgeBrowser" - EdgeExtension DeviceType = "EdgeExtension" - FirefoxBrowser DeviceType = "FirefoxBrowser" - FirefoxExtension DeviceType = "FirefoxExtension" - IEBrowser DeviceType = "IEBrowser" - IOS DeviceType = "iOS" - LinuxDesktop DeviceType = "LinuxDesktop" - MACOSDesktop DeviceType = "MacOsDesktop" - OperaBrowser DeviceType = "OperaBrowser" - OperaExtension DeviceType = "OperaExtension" - SDK DeviceType = "SDK" - SafariBrowser DeviceType = "SafariBrowser" - SafariExtension DeviceType = "SafariExtension" - UWP DeviceType = "UWP" - UnknownBrowser DeviceType = "UnknownBrowser" - VivaldiBrowser DeviceType = "VivaldiBrowser" - VivaldiExtension DeviceType = "VivaldiExtension" - WindowsDesktop DeviceType = "WindowsDesktop" -) - -// Two-factor provider -type TwoFactorProvider string - -const ( - Authenticator TwoFactorProvider = "Authenticator" - Duo TwoFactorProvider = "Duo" - OrganizationDuo TwoFactorProvider = "OrganizationDuo" - Remember TwoFactorProvider = "Remember" - TwoFactorProviderEmail TwoFactorProvider = "Email" - U2F TwoFactorProvider = "U2f" - WebAuthn TwoFactorProvider = "WebAuthn" - Yubikey TwoFactorProvider = "Yubikey" -) - -type LinkedIDType string - -const ( - Address1 LinkedIDType = "Address1" - Address2 LinkedIDType = "Address2" - Address3 LinkedIDType = "Address3" - Brand LinkedIDType = "Brand" - CardholderName LinkedIDType = "CardholderName" - City LinkedIDType = "City" - Code LinkedIDType = "Code" - Company LinkedIDType = "Company" - Country LinkedIDType = "Country" - ExpMonth LinkedIDType = "ExpMonth" - ExpYear LinkedIDType = "ExpYear" - FirstName LinkedIDType = "FirstName" - FullName LinkedIDType = "FullName" - LastName LinkedIDType = "LastName" - LicenseNumber LinkedIDType = "LicenseNumber" - LinkedIDTypeEmail LinkedIDType = "Email" - LinkedIDTypePassword LinkedIDType = "Password" - MiddleName LinkedIDType = "MiddleName" - Number LinkedIDType = "Number" - PassportNumber LinkedIDType = "PassportNumber" - Phone LinkedIDType = "Phone" - PostalCode LinkedIDType = "PostalCode" - Ssn LinkedIDType = "Ssn" - State LinkedIDType = "State" - Title LinkedIDType = "Title" - Username LinkedIDType = "Username" -) - -type FieldType string - -const ( - Boolean FieldType = "Boolean" - Hidden FieldType = "Hidden" - Linked FieldType = "Linked" - Text FieldType = "Text" -) - -type URIMatchType string - -const ( - Domain URIMatchType = "domain" - Exact URIMatchType = "exact" - Host URIMatchType = "host" - Never URIMatchType = "never" - RegularExpression URIMatchType = "regularExpression" - StartsWith URIMatchType = "startsWith" -) - -type CipherRepromptType string - -const ( - CipherRepromptTypePassword CipherRepromptType = "Password" - None CipherRepromptType = "None" -) - -type SecureNoteType string - -const ( - Generic SecureNoteType = "Generic" -) - -type CipherType string - -const ( - CipherTypeCard CipherType = "Card" - CipherTypeIdentity CipherType = "Identity" - CipherTypeLogin CipherType = "Login" - CipherTypeSecureNote CipherType = "SecureNote" -) - -type ExportFormatEnum string - -const ( - AccountEncryptedJSON ExportFormatEnum = "AccountEncryptedJson" - CSV ExportFormatEnum = "Csv" - JSON ExportFormatEnum = "Json" -) - -type ExportFormat struct { - Enum *ExportFormatEnum - ExportFormatClass *ExportFormatClass -} - -func (x *ExportFormat) UnmarshalJSON(data []byte) error { - x.ExportFormatClass = nil - x.Enum = nil - var c ExportFormatClass - object, err := unmarshalUnion(data, nil, nil, nil, nil, false, nil, true, &c, false, nil, true, &x.Enum, false) - if err != nil { - return err - } - if object { - x.ExportFormatClass = &c - } - return nil -} - -func (x *ExportFormat) MarshalJSON() ([]byte, error) { - return marshalUnion(nil, nil, nil, nil, false, nil, x.ExportFormatClass != nil, x.ExportFormatClass, false, nil, x.Enum != nil, x.Enum, false) -} - -func unmarshalUnion(data []byte, pi **int64, pf **float64, pb **bool, ps **string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) (bool, error) { - if pi != nil { - *pi = nil - } - if pf != nil { - *pf = nil - } - if pb != nil { - *pb = nil - } - if ps != nil { - *ps = nil - } - - dec := json.NewDecoder(bytes.NewReader(data)) - dec.UseNumber() - tok, err := dec.Token() - if err != nil { - return false, err - } - - switch v := tok.(type) { - case json.Number: - if pi != nil { - i, err := v.Int64() - if err == nil { - *pi = &i - return false, nil - } - } - if pf != nil { - f, err := v.Float64() - if err == nil { - *pf = &f - return false, nil - } - return false, errors.New("Unparsable number") - } - return false, errors.New("Union does not contain number") - case float64: - return false, errors.New("Decoder should not return float64") - case bool: - if pb != nil { - *pb = &v - return false, nil - } - return false, errors.New("Union does not contain bool") - case string: - if haveEnum { - return false, json.Unmarshal(data, pe) - } - if ps != nil { - *ps = &v - return false, nil - } - return false, errors.New("Union does not contain string") - case nil: - if nullable { - return false, nil - } - return false, errors.New("Union does not contain null") - case json.Delim: - if v == '{' { - if haveObject { - return true, json.Unmarshal(data, pc) - } - if haveMap { - return false, json.Unmarshal(data, pm) - } - return false, errors.New("Union does not contain object") - } - if v == '[' { - if haveArray { - return false, json.Unmarshal(data, pa) - } - return false, errors.New("Union does not contain array") - } - return false, errors.New("Cannot handle delimiter") - } - return false, errors.New("Cannot unmarshal union") - -} - -func marshalUnion(pi *int64, pf *float64, pb *bool, ps *string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) ([]byte, error) { - if pi != nil { - return json.Marshal(*pi) - } - if pf != nil { - return json.Marshal(*pf) - } - if pb != nil { - return json.Marshal(*pb) - } - if ps != nil { - return json.Marshal(*ps) - } - if haveArray { - return json.Marshal(pa) - } - if haveObject { - return json.Marshal(pc) - } - if haveMap { - return json.Marshal(pm) - } - if haveEnum { - return json.Marshal(pe) - } - if nullable { - return json.Marshal(nil) - } - return nil, errors.New("Union must not be null") -} - From c19b5edf000a569da920f3a9f389a7dab5705c6c Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 09:03:35 +0200 Subject: [PATCH 06/30] Do not expose Impl to consumers --- languages/go/bitwarden_libary.go | 4 ++++ languages/go/bitwarden_libary_custom.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/languages/go/bitwarden_libary.go b/languages/go/bitwarden_libary.go index 887a64ae3..49edad6c4 100644 --- a/languages/go/bitwarden_libary.go +++ b/languages/go/bitwarden_libary.go @@ -32,6 +32,10 @@ type BitwardenLibrary interface { type BitwardenLibraryImpl struct{} +func NewBitwardenLibrary() BitwardenLibrary { + return &BitwardenLibraryImpl{} +} + func (b *BitwardenLibraryImpl) Init(clientSettings string) (ClientPointer, error) { ptr := C.init(C.CString(clientSettings)) if ptr == nil { diff --git a/languages/go/bitwarden_libary_custom.go b/languages/go/bitwarden_libary_custom.go index b57020fda..d698fb583 100644 --- a/languages/go/bitwarden_libary_custom.go +++ b/languages/go/bitwarden_libary_custom.go @@ -32,6 +32,10 @@ type BitwardenLibrary interface { type BitwardenLibraryImpl struct{} +func NewBitwardenLibrary() BitwardenLibrary { + return &BitwardenLibraryImpl{} +} + func (b *BitwardenLibraryImpl) Init(clientSettings string) (ClientPointer, error) { ptr := C.init(C.CString(clientSettings)) if ptr == nil { From 64dbda5b1aa83dfa37196eb5250dd930b3594bd5 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 09:04:00 +0200 Subject: [PATCH 07/30] Clearly denote file as example --- languages/go/{main.go => example.go} | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) rename languages/go/{main.go => example.go} (89%) diff --git a/languages/go/main.go b/languages/go/example.go similarity index 89% rename from languages/go/main.go rename to languages/go/example.go index d016a295a..76d84bfd4 100644 --- a/languages/go/main.go +++ b/languages/go/example.go @@ -9,17 +9,8 @@ import ( func main() { apiURL := os.Getenv("API_URL") - if apiURL == "" { - apiURL = "https://api.bitwarden.com" // Default - } identityURL := os.Getenv("IDENTITY_URL") - if identityURL == "" { - identityURL = "https://identity.bitwarden.com" // Default - } userAgent := os.Getenv("USER_AGENT") - if userAgent == "" { - userAgent = "Bitwarden SDK" // Default - } clientSettings := ClientSettings{ APIURL: apiURL, @@ -28,7 +19,7 @@ func main() { UserAgent: userAgent, } - lib := &BitwardenLibraryImpl{} + lib := NewBitwardenLibrary() bitwardenClient := NewBitwardenClient(clientSettings, lib) accessToken := os.Getenv("ACCESS_TOKEN") From 4f30dacb8ad28962862baa9f035bc81577fac3e7 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 09:10:38 +0200 Subject: [PATCH 08/30] modify package name from main to sdk --- languages/go/bitwarden_client.go | 2 +- languages/go/bitwarden_libary.go | 2 +- languages/go/bitwarden_libary_custom.go | 2 +- languages/go/command_runner.go | 2 +- languages/go/example.go | 2 +- languages/go/project.go | 2 +- languages/go/secrets.go | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index 25ec18569..be550d1fa 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -1,4 +1,4 @@ -package main +package sdk import "encoding/json" diff --git a/languages/go/bitwarden_libary.go b/languages/go/bitwarden_libary.go index 49edad6c4..2fbaa8b9d 100644 --- a/languages/go/bitwarden_libary.go +++ b/languages/go/bitwarden_libary.go @@ -1,7 +1,7 @@ //go:build !custom // +build !custom -package main +package sdk import ( "fmt" diff --git a/languages/go/bitwarden_libary_custom.go b/languages/go/bitwarden_libary_custom.go index d698fb583..558724e2b 100644 --- a/languages/go/bitwarden_libary_custom.go +++ b/languages/go/bitwarden_libary_custom.go @@ -1,7 +1,7 @@ //go:build custom // +build custom -package main +package sdk import ( "fmt" diff --git a/languages/go/command_runner.go b/languages/go/command_runner.go index 5578b5ac1..75f89a1a1 100644 --- a/languages/go/command_runner.go +++ b/languages/go/command_runner.go @@ -1,4 +1,4 @@ -package main +package sdk import ( "encoding/json" diff --git a/languages/go/example.go b/languages/go/example.go index 76d84bfd4..dd69118bd 100644 --- a/languages/go/example.go +++ b/languages/go/example.go @@ -1,4 +1,4 @@ -package main +package sdk import ( "fmt" diff --git a/languages/go/project.go b/languages/go/project.go index c96ca595a..e3fe4cc29 100644 --- a/languages/go/project.go +++ b/languages/go/project.go @@ -1,4 +1,4 @@ -package main +package sdk import ( "encoding/json" diff --git a/languages/go/secrets.go b/languages/go/secrets.go index bbffe3938..39adcafb0 100644 --- a/languages/go/secrets.go +++ b/languages/go/secrets.go @@ -1,4 +1,4 @@ -package main +package sdk import ( "encoding/json" From 35f160165b5d54fbe264ca87db99b9c95c3ce5dd Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 09:16:13 +0200 Subject: [PATCH 09/30] Moving c interface to internal package --- languages/go/bitwarden_client.go | 12 ++++++++---- languages/go/command_runner.go | 8 +++++--- .../go/{ => internal/cinterface}/bitwarden_libary.go | 2 +- .../cinterface}/bitwarden_libary_custom.go | 2 +- 4 files changed, 15 insertions(+), 9 deletions(-) rename languages/go/{ => internal/cinterface}/bitwarden_libary.go (98%) rename languages/go/{ => internal/cinterface}/bitwarden_libary_custom.go (98%) diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index be550d1fa..fc6592486 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -1,16 +1,20 @@ package sdk -import "encoding/json" +import ( + "encoding/json" + + "github.com/bitwarden/sdk/languages/go/internal/cinterface" +) type BitwardenClient struct { - client ClientPointer - lib BitwardenLibrary + client cinterface.ClientPointer + lib cinterface.BitwardenLibrary commandRunner CommandRunnerInterface Projects ProjectsInterface Secrets SecretsInterface } -func NewBitwardenClient(settings ClientSettings, lib BitwardenLibrary) *BitwardenClient { +func NewBitwardenClient(settings ClientSettings, lib cinterface.BitwardenLibrary) *BitwardenClient { settingsJSON, err := json.Marshal(settings) if err != nil { panic(err) diff --git a/languages/go/command_runner.go b/languages/go/command_runner.go index 75f89a1a1..20246a10d 100644 --- a/languages/go/command_runner.go +++ b/languages/go/command_runner.go @@ -2,6 +2,8 @@ package sdk import ( "encoding/json" + + "github.com/bitwarden/sdk/languages/go/internal/cinterface" ) type CommandRunnerInterface interface { @@ -9,11 +11,11 @@ type CommandRunnerInterface interface { } type CommandRunner struct { - client ClientPointer - lib BitwardenLibrary + client cinterface.ClientPointer + lib cinterface.BitwardenLibrary } -func NewCommandRunner(client ClientPointer, lib BitwardenLibrary) *CommandRunner { +func NewCommandRunner(client cinterface.ClientPointer, lib cinterface.BitwardenLibrary) *CommandRunner { return &CommandRunner{ client: client, lib: lib, diff --git a/languages/go/bitwarden_libary.go b/languages/go/internal/cinterface/bitwarden_libary.go similarity index 98% rename from languages/go/bitwarden_libary.go rename to languages/go/internal/cinterface/bitwarden_libary.go index 2fbaa8b9d..6d6b0bb25 100644 --- a/languages/go/bitwarden_libary.go +++ b/languages/go/internal/cinterface/bitwarden_libary.go @@ -1,7 +1,7 @@ //go:build !custom // +build !custom -package sdk +package cinterface import ( "fmt" diff --git a/languages/go/bitwarden_libary_custom.go b/languages/go/internal/cinterface/bitwarden_libary_custom.go similarity index 98% rename from languages/go/bitwarden_libary_custom.go rename to languages/go/internal/cinterface/bitwarden_libary_custom.go index 558724e2b..5acbde67d 100644 --- a/languages/go/bitwarden_libary_custom.go +++ b/languages/go/internal/cinterface/bitwarden_libary_custom.go @@ -1,7 +1,7 @@ //go:build custom // +build custom -package sdk +package cinterface import ( "fmt" From 537e10b6050e3399c919e70c35ef7511748af7fc Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 09:25:07 +0200 Subject: [PATCH 10/30] Exclude unsafe internal impl from examples --- languages/go/README.md | 3 +-- languages/go/bitwarden_client.go | 3 ++- languages/go/example.go | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/languages/go/README.md b/languages/go/README.md index 117840ffb..19979ed2c 100644 --- a/languages/go/README.md +++ b/languages/go/README.md @@ -31,8 +31,7 @@ import "github.com/bitwarden/sdk/languages/go" settings := ClientSettings{ // Your settings here } -lib := BitwardenLibraryImpl{} -client := NewBitwardenClient(settings, lib) +client := NewBitwardenClient(settings) ``` --- diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index fc6592486..6d2da353c 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -14,12 +14,13 @@ type BitwardenClient struct { Secrets SecretsInterface } -func NewBitwardenClient(settings ClientSettings, lib cinterface.BitwardenLibrary) *BitwardenClient { +func NewBitwardenClient(settings ClientSettings) *BitwardenClient { settingsJSON, err := json.Marshal(settings) if err != nil { panic(err) } + lib := cinterface.NewBitwardenLibrary() client, err := lib.Init(string(settingsJSON)) if err != nil { panic(err) diff --git a/languages/go/example.go b/languages/go/example.go index dd69118bd..29e217180 100644 --- a/languages/go/example.go +++ b/languages/go/example.go @@ -19,8 +19,7 @@ func main() { UserAgent: userAgent, } - lib := NewBitwardenLibrary() - bitwardenClient := NewBitwardenClient(clientSettings, lib) + bitwardenClient := NewBitwardenClient(clientSettings) accessToken := os.Getenv("ACCESS_TOKEN") organizationIDStr := os.Getenv("ORGANIZATION_ID") From af0b153fbe15ce6235a9330d7534cdca06cea349 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 10:10:07 +0200 Subject: [PATCH 11/30] lower version requirement --- languages/go/go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/languages/go/go.mod b/languages/go/go.mod index a2acc8fef..a9e125453 100644 --- a/languages/go/go.mod +++ b/languages/go/go.mod @@ -1,5 +1,5 @@ module github.com/bitwarden/sdk/languages/go -go 1.20 +go 1.18 require github.com/gofrs/uuid v4.4.0+incompatible From 8c8bc29d0eef6948096e1de7713eda9794fb73f8 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Mon, 2 Oct 2023 10:10:21 +0200 Subject: [PATCH 12/30] WIP - initial github release action --- .github/workflows/golang-release.yml | 69 ++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 .github/workflows/golang-release.yml diff --git a/.github/workflows/golang-release.yml b/.github/workflows/golang-release.yml new file mode 100644 index 000000000..063d3ae42 --- /dev/null +++ b/.github/workflows/golang-release.yml @@ -0,0 +1,69 @@ +name: Go Release + +on: + workflow_dispatch: + inputs: + version_number: + description: "New Version" + required: true + +env: + GO111MODULE: on + GO_VERSION: '^1.18' + +jobs: + build_rust: + uses: ./.github/workflows/build-rust-cross-platform.yml + + generate-schemas: + uses: ./.github/workflows/generate_schemas.yml + + build: + needs: [build_rust, generate-schemas] + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + + - name: Setup Go environment + uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Build + run: go build -v ./... + + - name: Test + run: go test -v ./... + + release: + needs: [build] + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + + - name: Setup Go environment + uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + + - name: Set release version + run: echo "VERSION=${{ github.event.inputs.version_number }}" >> $GITHUB_ENV + + - name: Install Goreleaser + run: go install github.com/goreleaser/goreleaser@latest + + - name: Run Goreleaser + run: goreleaser release --rm-dist --skip-validate + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ env.VERSION }} From 3da079805b04e8194b553691dfa6f41653665463 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 08:59:02 +0200 Subject: [PATCH 13/30] fix spelling --- .../cinterface/{bitwarden_libary.go => bitwarden_library.go} | 0 .../{bitwarden_libary_custom.go => bitwarden_library_custom.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename languages/go/internal/cinterface/{bitwarden_libary.go => bitwarden_library.go} (100%) rename languages/go/internal/cinterface/{bitwarden_libary_custom.go => bitwarden_library_custom.go} (100%) diff --git a/languages/go/internal/cinterface/bitwarden_libary.go b/languages/go/internal/cinterface/bitwarden_library.go similarity index 100% rename from languages/go/internal/cinterface/bitwarden_libary.go rename to languages/go/internal/cinterface/bitwarden_library.go diff --git a/languages/go/internal/cinterface/bitwarden_libary_custom.go b/languages/go/internal/cinterface/bitwarden_library_custom.go similarity index 100% rename from languages/go/internal/cinterface/bitwarden_libary_custom.go rename to languages/go/internal/cinterface/bitwarden_library_custom.go From e7e6a3c73b9ff9e1df10fda384c7fc4c1ff5c89a Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:20:12 +0200 Subject: [PATCH 14/30] Fix package name in schemas --- languages/csharp/schemas.cs | 3106 +++++++++++++++++++++++++++++++++++ 1 file changed, 3106 insertions(+) create mode 100644 languages/csharp/schemas.cs diff --git a/languages/csharp/schemas.cs b/languages/csharp/schemas.cs new file mode 100644 index 000000000..3e3a6ad0f --- /dev/null +++ b/languages/csharp/schemas.cs @@ -0,0 +1,3106 @@ +// +// +// To parse this JSON data, add NuGet 'System.Text.Json' then do one of these: +// +// using Bitwarden.Sdk; +// +// var clientSettings = ClientSettings.FromJson(jsonString); +// var command = Command.FromJson(jsonString); +// var docRef = DocRef.FromJson(jsonString); +// var responseForApiKeyLoginResponse = ResponseForApiKeyLoginResponse.FromJson(jsonString); +// var responseForFingerprintResponse = ResponseForFingerprintResponse.FromJson(jsonString); +// var responseForPasswordLoginResponse = ResponseForPasswordLoginResponse.FromJson(jsonString); +// var responseForProjectResponse = ResponseForProjectResponse.FromJson(jsonString); +// var responseForProjectsDeleteResponse = ResponseForProjectsDeleteResponse.FromJson(jsonString); +// var responseForProjectsResponse = ResponseForProjectsResponse.FromJson(jsonString); +// var responseForSecretIdentifiersResponse = ResponseForSecretIdentifiersResponse.FromJson(jsonString); +// var responseForSecretResponse = ResponseForSecretResponse.FromJson(jsonString); +// var responseForSecretsDeleteResponse = ResponseForSecretsDeleteResponse.FromJson(jsonString); +// var responseForSecretsResponse = ResponseForSecretsResponse.FromJson(jsonString); +// var responseForSyncResponse = ResponseForSyncResponse.FromJson(jsonString); +// var responseForUserApiKeyResponse = ResponseForUserApiKeyResponse.FromJson(jsonString); +#nullable enable +#pragma warning disable CS8618 +#pragma warning disable CS8601 +#pragma warning disable CS8603 + +namespace Bitwarden.Sdk +{ + using System; + using System.Collections.Generic; + + using System.Text.Json; + using System.Text.Json.Serialization; + using System.Globalization; + + /// + /// Basic client behavior settings. These settings specify the various targets and behavior + /// of the Bitwarden Client. They are optional and uneditable once the client is + /// initialized. + /// + /// Defaults to + /// + /// ``` # use bitwarden::client::client_settings::{ClientSettings, DeviceType}; # use + /// assert_matches::assert_matches; let settings = ClientSettings { identity_url: + /// "https://identity.bitwarden.com".to_string(), api_url: + /// "https://api.bitwarden.com".to_string(), user_agent: "Bitwarden Rust-SDK".to_string(), + /// device_type: DeviceType::SDK, }; let default = ClientSettings::default(); + /// assert_matches!(settings, default); ``` + /// + /// Targets `localhost:8080` for debug builds. + /// + public partial class ClientSettings + { + /// + /// The api url of the targeted Bitwarden instance. Defaults to `https://api.bitwarden.com` + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("apiUrl")] + public string ApiUrl { get; set; } + + /// + /// Device type to send to Bitwarden. Defaults to SDK + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("deviceType")] + public DeviceType? DeviceType { get; set; } + + /// + /// The identity url of the targeted Bitwarden instance. Defaults to + /// `https://identity.bitwarden.com` + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("identityUrl")] + public string IdentityUrl { get; set; } + + /// + /// The user_agent to sent to Bitwarden. Defaults to `Bitwarden Rust-SDK` + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("userAgent")] + public string UserAgent { get; set; } + } + + /// + /// Login with username and password + /// + /// This command is for initiating an authentication handshake with Bitwarden. Authorization + /// may fail due to requiring 2fa or captcha challenge completion despite accurate + /// credentials. + /// + /// This command is not capable of handling authentication requiring 2fa or captcha. + /// + /// Returns: [PasswordLoginResponse](bitwarden::auth::login::PasswordLoginResponse) + /// + /// Login with API Key + /// + /// This command is for initiating an authentication handshake with Bitwarden. + /// + /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) + /// + /// Login with Secrets Manager Access Token + /// + /// This command is for initiating an authentication handshake with Bitwarden. + /// + /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) + /// + /// > Requires Authentication Get the API key of the currently authenticated user + /// + /// Returns: [UserApiKeyResponse](bitwarden::platform::UserApiKeyResponse) + /// + /// Get the user's passphrase + /// + /// Returns: String + /// + /// > Requires Authentication Retrieve all user data, ciphers and organizations the user is a + /// part of + /// + /// Returns: [SyncResponse](bitwarden::platform::SyncResponse) + /// + public partial class Command + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("passwordLogin")] + public PasswordLoginRequest PasswordLogin { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("apiKeyLogin")] + public ApiKeyLoginRequest ApiKeyLogin { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("accessTokenLogin")] + public AccessTokenLoginRequest AccessTokenLogin { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("getUserApiKey")] + public SecretVerificationRequest GetUserApiKey { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("fingerprint")] + public FingerprintRequest Fingerprint { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("sync")] + public SyncRequest Sync { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("secrets")] + public SecretsCommand Secrets { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("projects")] + public ProjectsCommand Projects { get; set; } + } + + /// + /// Login to Bitwarden with access token + /// + public partial class AccessTokenLoginRequest + { + /// + /// Bitwarden service API access token + /// + [JsonPropertyName("accessToken")] + public string AccessToken { get; set; } + } + + /// + /// Login to Bitwarden with Api Key + /// + public partial class ApiKeyLoginRequest + { + /// + /// Bitwarden account client_id + /// + [JsonPropertyName("clientId")] + public string ClientId { get; set; } + + /// + /// Bitwarden account client_secret + /// + [JsonPropertyName("clientSecret")] + public string ClientSecret { get; set; } + + /// + /// Bitwarden account master password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + } + + public partial class FingerprintRequest + { + /// + /// The input material, used in the fingerprint generation process. + /// + [JsonPropertyName("fingerprintMaterial")] + public string FingerprintMaterial { get; set; } + + /// + /// The user's public key encoded with base64. + /// + [JsonPropertyName("publicKey")] + public string PublicKey { get; set; } + } + + public partial class SecretVerificationRequest + { + /// + /// The user's master password to use for user verification. If supplied, this will be used + /// for verification purposes. + /// + [JsonPropertyName("masterPassword")] + public string MasterPassword { get; set; } + + /// + /// Alternate user verification method through OTP. This is provided for users who have no + /// master password due to use of Customer Managed Encryption. Must be present and valid if + /// master_password is absent. + /// + [JsonPropertyName("otp")] + public string Otp { get; set; } + } + + /// + /// Login to Bitwarden with Username and Password + /// + public partial class PasswordLoginRequest + { + /// + /// Bitwarden account email address + /// + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// Bitwarden account master password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + [JsonPropertyName("twoFactor")] + public TwoFactorRequest TwoFactor { get; set; } + } + + public partial class TwoFactorRequest + { + /// + /// Two-factor provider + /// + [JsonPropertyName("provider")] + public TwoFactorProvider Provider { get; set; } + + /// + /// Two-factor remember + /// + [JsonPropertyName("remember")] + public bool Remember { get; set; } + + /// + /// Two-factor Token + /// + [JsonPropertyName("token")] + public string Token { get; set; } + } + + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Retrieve a project by the provided identifier + /// + /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Creates a new project in the provided organization using the given data + /// + /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Lists all projects of the given organization + /// + /// Returns: [ProjectsResponse](bitwarden::secrets_manager::projects::ProjectsResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Updates an existing project with the provided ID using the given data + /// + /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Deletes all the projects whose IDs match the provided ones + /// + /// Returns: + /// [ProjectsDeleteResponse](bitwarden::secrets_manager::projects::ProjectsDeleteResponse) + /// + public partial class ProjectsCommand + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("get")] + public ProjectGetRequest Get { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("create")] + public ProjectCreateRequest Create { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("list")] + public ProjectsListRequest List { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("update")] + public ProjectPutRequest Update { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("delete")] + public ProjectsDeleteRequest Delete { get; set; } + } + + public partial class ProjectCreateRequest + { + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Organization where the project will be created + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + } + + public partial class ProjectsDeleteRequest + { + /// + /// IDs of the projects to delete + /// + [JsonPropertyName("ids")] + public Guid[] Ids { get; set; } + } + + public partial class ProjectGetRequest + { + /// + /// ID of the project to retrieve + /// + [JsonPropertyName("id")] + public Guid Id { get; set; } + } + + public partial class ProjectsListRequest + { + /// + /// Organization to retrieve all the projects from + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + } + + public partial class ProjectPutRequest + { + /// + /// ID of the project to modify + /// + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Organization ID of the project to modify + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + } + + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Retrieve a secret by the provided identifier + /// + /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Retrieve secrets by the provided identifiers + /// + /// Returns: [SecretsResponse](bitwarden::secrets_manager::secrets::SecretsResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Creates a new secret in the provided organization using the given data + /// + /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Lists all secret identifiers of the given organization, to then retrieve each + /// secret, use `CreateSecret` + /// + /// Returns: + /// [SecretIdentifiersResponse](bitwarden::secrets_manager::secrets::SecretIdentifiersResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Updates an existing secret with the provided ID using the given data + /// + /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) + /// + /// > Requires Authentication > Requires using an Access Token for login or calling Sync at + /// least once Deletes all the secrets whose IDs match the provided ones + /// + /// Returns: + /// [SecretsDeleteResponse](bitwarden::secrets_manager::secrets::SecretsDeleteResponse) + /// + public partial class SecretsCommand + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("get")] + public SecretGetRequest Get { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("getByIds")] + public SecretsGetRequest GetByIds { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("create")] + public SecretCreateRequest Create { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("list")] + public SecretIdentifiersRequest List { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("update")] + public SecretPutRequest Update { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("delete")] + public SecretsDeleteRequest Delete { get; set; } + } + + public partial class SecretCreateRequest + { + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("note")] + public string Note { get; set; } + + /// + /// Organization where the secret will be created + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + /// + /// IDs of the projects that this secret will belong to + /// + [JsonPropertyName("projectIds")] + public Guid[] ProjectIds { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class SecretsDeleteRequest + { + /// + /// IDs of the secrets to delete + /// + [JsonPropertyName("ids")] + public Guid[] Ids { get; set; } + } + + public partial class SecretGetRequest + { + /// + /// ID of the secret to retrieve + /// + [JsonPropertyName("id")] + public Guid Id { get; set; } + } + + public partial class SecretsGetRequest + { + /// + /// IDs of the secrets to retrieve + /// + [JsonPropertyName("ids")] + public Guid[] Ids { get; set; } + } + + public partial class SecretIdentifiersRequest + { + /// + /// Organization to retrieve all the secrets from + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + } + + public partial class SecretPutRequest + { + /// + /// ID of the secret to modify + /// + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("note")] + public string Note { get; set; } + + /// + /// Organization ID of the secret to modify + /// + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("projectIds")] + public Guid[] ProjectIds { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class SyncRequest + { + /// + /// Exclude the subdomains from the response, defaults to false + /// + [JsonPropertyName("excludeSubdomains")] + public bool? ExcludeSubdomains { get; set; } + } + + public partial class DocRef + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("Cipher")] + public Cipher Cipher { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("CipherView")] + public CipherView CipherView { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("Collection")] + public Collection Collection { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("Folder")] + public Folder Folder { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("FolderView")] + public FolderView FolderView { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("Send")] + public Send Send { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("SendView")] + public SendView SendView { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("SendListView")] + public SendListView SendListView { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("InitCryptoRequest")] + public InitCryptoRequest InitCryptoRequest { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("PasswordGeneratorRequest")] + public PasswordGeneratorRequest PasswordGeneratorRequest { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("PassphraseGeneratorRequest")] + public PassphraseGeneratorRequest PassphraseGeneratorRequest { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("ExportFormat")] + public ExportFormat? ExportFormat { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("MasterPasswordPolicyOptions")] + public MasterPasswordPolicyOptions MasterPasswordPolicyOptions { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("Kdf")] + public Kdf Kdf { get; set; } + } + + public partial class Cipher + { + [JsonPropertyName("attachments")] + public Attachment[] Attachments { get; set; } + + [JsonPropertyName("card")] + public Card Card { get; set; } + + [JsonPropertyName("collectionIds")] + public Guid[] CollectionIds { get; set; } + + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("deletedDate")] + public DateTimeOffset? DeletedDate { get; set; } + + [JsonPropertyName("edit")] + public bool Edit { get; set; } + + [JsonPropertyName("favorite")] + public bool Favorite { get; set; } + + [JsonPropertyName("fields")] + public Field[] Fields { get; set; } + + [JsonPropertyName("folderId")] + public Guid? FolderId { get; set; } + + [JsonPropertyName("id")] + public Guid? Id { get; set; } + + [JsonPropertyName("identity")] + public Identity Identity { get; set; } + + [JsonPropertyName("localData")] + public LocalData LocalData { get; set; } + + [JsonPropertyName("login")] + public Login Login { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("notes")] + public string Notes { get; set; } + + [JsonPropertyName("organizationId")] + public Guid? OrganizationId { get; set; } + + [JsonPropertyName("organizationUseTotp")] + public bool OrganizationUseTotp { get; set; } + + [JsonPropertyName("passwordHistory")] + public PasswordHistory[] PasswordHistory { get; set; } + + [JsonPropertyName("reprompt")] + public CipherRepromptType Reprompt { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("secureNote")] + public SecureNote SecureNote { get; set; } + + [JsonPropertyName("type")] + public CipherType Type { get; set; } + + [JsonPropertyName("viewPassword")] + public bool ViewPassword { get; set; } + } + + public partial class Attachment + { + [JsonPropertyName("fileName")] + public string FileName { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("size")] + public string Size { get; set; } + + /// + /// Readable size, ex: "4.2 KB" or "1.43 GB" + /// + [JsonPropertyName("sizeName")] + public string SizeName { get; set; } + + [JsonPropertyName("url")] + public string Url { get; set; } + } + + public partial class Card + { + [JsonPropertyName("brand")] + public string Brand { get; set; } + + [JsonPropertyName("cardholderName")] + public string CardholderName { get; set; } + + [JsonPropertyName("code")] + public string Code { get; set; } + + [JsonPropertyName("expMonth")] + public string ExpMonth { get; set; } + + [JsonPropertyName("expYear")] + public string ExpYear { get; set; } + + [JsonPropertyName("number")] + public string Number { get; set; } + } + + public partial class Field + { + [JsonPropertyName("linkedId")] + public LinkedIdType? LinkedId { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("type")] + public FieldType Type { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class Identity + { + [JsonPropertyName("address1")] + public string Address1 { get; set; } + + [JsonPropertyName("address2")] + public string Address2 { get; set; } + + [JsonPropertyName("address3")] + public string Address3 { get; set; } + + [JsonPropertyName("city")] + public string City { get; set; } + + [JsonPropertyName("company")] + public string Company { get; set; } + + [JsonPropertyName("country")] + public string Country { get; set; } + + [JsonPropertyName("email")] + public string Email { get; set; } + + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + [JsonPropertyName("licenseNumber")] + public string LicenseNumber { get; set; } + + [JsonPropertyName("middleName")] + public string MiddleName { get; set; } + + [JsonPropertyName("passportNumber")] + public string PassportNumber { get; set; } + + [JsonPropertyName("phone")] + public string Phone { get; set; } + + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + [JsonPropertyName("ssn")] + public string Ssn { get; set; } + + [JsonPropertyName("state")] + public string State { get; set; } + + [JsonPropertyName("title")] + public string Title { get; set; } + + [JsonPropertyName("username")] + public string Username { get; set; } + } + + public partial class LocalData + { + [JsonPropertyName("lastLaunched")] + public long? LastLaunched { get; set; } + + [JsonPropertyName("lastUsedDate")] + public long? LastUsedDate { get; set; } + } + + public partial class Login + { + [JsonPropertyName("autofillOnPageLoad")] + public bool? AutofillOnPageLoad { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + + [JsonPropertyName("passwordRevisionDate")] + public DateTimeOffset? PasswordRevisionDate { get; set; } + + [JsonPropertyName("totp")] + public string Totp { get; set; } + + [JsonPropertyName("uris")] + public LoginUri[] Uris { get; set; } + + [JsonPropertyName("username")] + public string Username { get; set; } + } + + public partial class LoginUri + { + [JsonPropertyName("match")] + public UriMatchType? Match { get; set; } + + [JsonPropertyName("uri")] + public string Uri { get; set; } + } + + public partial class PasswordHistory + { + [JsonPropertyName("lastUsedDate")] + public DateTimeOffset LastUsedDate { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + } + + public partial class SecureNote + { + [JsonPropertyName("type")] + public SecureNoteType Type { get; set; } + } + + public partial class CipherView + { + [JsonPropertyName("attachments")] + public AttachmentView[] Attachments { get; set; } + + [JsonPropertyName("card")] + public CardView Card { get; set; } + + [JsonPropertyName("collectionIds")] + public Guid[] CollectionIds { get; set; } + + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("deletedDate")] + public DateTimeOffset? DeletedDate { get; set; } + + [JsonPropertyName("edit")] + public bool Edit { get; set; } + + [JsonPropertyName("favorite")] + public bool Favorite { get; set; } + + [JsonPropertyName("fields")] + public FieldView[] Fields { get; set; } + + [JsonPropertyName("folderId")] + public Guid? FolderId { get; set; } + + [JsonPropertyName("id")] + public Guid? Id { get; set; } + + [JsonPropertyName("identity")] + public IdentityView Identity { get; set; } + + [JsonPropertyName("localData")] + public LocalDataView LocalData { get; set; } + + [JsonPropertyName("login")] + public LoginView Login { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("notes")] + public string Notes { get; set; } + + [JsonPropertyName("organizationId")] + public Guid? OrganizationId { get; set; } + + [JsonPropertyName("organizationUseTotp")] + public bool OrganizationUseTotp { get; set; } + + [JsonPropertyName("passwordHistory")] + public PasswordHistoryView[] PasswordHistory { get; set; } + + [JsonPropertyName("reprompt")] + public CipherRepromptType Reprompt { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("secureNote")] + public SecureNoteView SecureNote { get; set; } + + [JsonPropertyName("type")] + public CipherType Type { get; set; } + + [JsonPropertyName("viewPassword")] + public bool ViewPassword { get; set; } + } + + public partial class AttachmentView + { + [JsonPropertyName("fileName")] + public string FileName { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("size")] + public string Size { get; set; } + + [JsonPropertyName("sizeName")] + public string SizeName { get; set; } + + [JsonPropertyName("url")] + public string Url { get; set; } + } + + public partial class CardView + { + [JsonPropertyName("brand")] + public string Brand { get; set; } + + [JsonPropertyName("cardholderName")] + public string CardholderName { get; set; } + + [JsonPropertyName("code")] + public string Code { get; set; } + + [JsonPropertyName("expMonth")] + public string ExpMonth { get; set; } + + [JsonPropertyName("expYear")] + public string ExpYear { get; set; } + + [JsonPropertyName("number")] + public string Number { get; set; } + } + + public partial class FieldView + { + [JsonPropertyName("linkedId")] + public LinkedIdType? LinkedId { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("type")] + public FieldType Type { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class IdentityView + { + [JsonPropertyName("address1")] + public string Address1 { get; set; } + + [JsonPropertyName("address2")] + public string Address2 { get; set; } + + [JsonPropertyName("address3")] + public string Address3 { get; set; } + + [JsonPropertyName("city")] + public string City { get; set; } + + [JsonPropertyName("company")] + public string Company { get; set; } + + [JsonPropertyName("country")] + public string Country { get; set; } + + [JsonPropertyName("email")] + public string Email { get; set; } + + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + [JsonPropertyName("licenseNumber")] + public string LicenseNumber { get; set; } + + [JsonPropertyName("middleName")] + public string MiddleName { get; set; } + + [JsonPropertyName("passportNumber")] + public string PassportNumber { get; set; } + + [JsonPropertyName("phone")] + public string Phone { get; set; } + + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + [JsonPropertyName("ssn")] + public string Ssn { get; set; } + + [JsonPropertyName("state")] + public string State { get; set; } + + [JsonPropertyName("title")] + public string Title { get; set; } + + [JsonPropertyName("username")] + public string Username { get; set; } + } + + public partial class LocalDataView + { + [JsonPropertyName("lastLaunched")] + public long? LastLaunched { get; set; } + + [JsonPropertyName("lastUsedDate")] + public long? LastUsedDate { get; set; } + } + + public partial class LoginView + { + [JsonPropertyName("autofillOnPageLoad")] + public bool? AutofillOnPageLoad { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + + [JsonPropertyName("passwordRevisionDate")] + public DateTimeOffset? PasswordRevisionDate { get; set; } + + [JsonPropertyName("totp")] + public string Totp { get; set; } + + [JsonPropertyName("uris")] + public LoginUriView[] Uris { get; set; } + + [JsonPropertyName("username")] + public string Username { get; set; } + } + + public partial class LoginUriView + { + [JsonPropertyName("match")] + public UriMatchType? Match { get; set; } + + [JsonPropertyName("uri")] + public string Uri { get; set; } + } + + public partial class PasswordHistoryView + { + [JsonPropertyName("lastUsedDate")] + public DateTimeOffset LastUsedDate { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + } + + public partial class SecureNoteView + { + [JsonPropertyName("type")] + public SecureNoteType Type { get; set; } + } + + public partial class Collection + { + [JsonPropertyName("externalId")] + public string ExternalId { get; set; } + + [JsonPropertyName("hidePasswords")] + public bool HidePasswords { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("readOnly")] + public bool ReadOnly { get; set; } + } + + public partial class ExportFormatClass + { + [JsonPropertyName("EncryptedJson")] + public EncryptedJson EncryptedJson { get; set; } + } + + public partial class EncryptedJson + { + [JsonPropertyName("password")] + public string Password { get; set; } + } + + public partial class Folder + { + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + } + + public partial class FolderView + { + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + } + + public partial class InitCryptoRequest + { + /// + /// The user's email address + /// + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// The user's KDF parameters, as received from the prelogin request + /// + [JsonPropertyName("kdfParams")] + public Kdf KdfParams { get; set; } + + /// + /// The encryption keys for all the organizations the user is a part of + /// + [JsonPropertyName("organizationKeys")] + public Dictionary OrganizationKeys { get; set; } + + /// + /// The user's master password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// The user's encryptred private key + /// + [JsonPropertyName("privateKey")] + public string PrivateKey { get; set; } + + /// + /// The user's encrypted symmetric crypto key + /// + [JsonPropertyName("userKey")] + public string UserKey { get; set; } + } + + /// + /// The user's KDF parameters, as received from the prelogin request + /// + public partial class Kdf + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("pBKDF2")] + public PBkdf2 PBkdf2 { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("argon2id")] + public Argon2Id Argon2Id { get; set; } + } + + public partial class Argon2Id + { + [JsonPropertyName("iterations")] + public long Iterations { get; set; } + + [JsonPropertyName("memory")] + public long Memory { get; set; } + + [JsonPropertyName("parallelism")] + public long Parallelism { get; set; } + } + + public partial class PBkdf2 + { + [JsonPropertyName("iterations")] + public long Iterations { get; set; } + } + + public partial class MasterPasswordPolicyOptions + { + /// + /// Flag to indicate if the policy should be enforced on login. If true, and the user's + /// password does not meet the policy requirements, the user will be forced to update their + /// password. + /// + [JsonPropertyName("enforce_on_login")] + public bool EnforceOnLogin { get; set; } + + [JsonPropertyName("min_complexity")] + public long MinComplexity { get; set; } + + [JsonPropertyName("min_length")] + public long MinLength { get; set; } + + [JsonPropertyName("require_lower")] + public bool RequireLower { get; set; } + + [JsonPropertyName("require_numbers")] + public bool RequireNumbers { get; set; } + + [JsonPropertyName("require_special")] + public bool RequireSpecial { get; set; } + + [JsonPropertyName("require_upper")] + public bool RequireUpper { get; set; } + } + + /// + /// Passphrase generator request. + /// + /// The default separator is `-` and default number of words is 3. + /// + public partial class PassphraseGeneratorRequest + { + [JsonPropertyName("capitalize")] + public bool? Capitalize { get; set; } + + [JsonPropertyName("includeNumber")] + public bool? IncludeNumber { get; set; } + + [JsonPropertyName("numWords")] + public long? NumWords { get; set; } + + [JsonPropertyName("wordSeparator")] + public string WordSeparator { get; set; } + } + + /// + /// Password generator request. If all options are false, the default is to generate a + /// password with: - lowercase - uppercase - numbers + /// + /// The default length is 16. + /// + public partial class PasswordGeneratorRequest + { + [JsonPropertyName("avoidAmbiguous")] + public bool? AvoidAmbiguous { get; set; } + + [JsonPropertyName("length")] + public long? Length { get; set; } + + [JsonPropertyName("lowercase")] + public bool Lowercase { get; set; } + + [JsonPropertyName("minLowercase")] + public bool? MinLowercase { get; set; } + + [JsonPropertyName("minNumber")] + public bool? MinNumber { get; set; } + + [JsonPropertyName("minSpecial")] + public bool? MinSpecial { get; set; } + + [JsonPropertyName("minUppercase")] + public bool? MinUppercase { get; set; } + + [JsonPropertyName("numbers")] + public bool Numbers { get; set; } + + [JsonPropertyName("special")] + public bool Special { get; set; } + + [JsonPropertyName("uppercase")] + public bool Uppercase { get; set; } + } + + public partial class Send + { + [JsonPropertyName("accessCount")] + public long AccessCount { get; set; } + + [JsonPropertyName("accessId")] + public string AccessId { get; set; } + + [JsonPropertyName("deletionDate")] + public DateTimeOffset DeletionDate { get; set; } + + [JsonPropertyName("disabled")] + public bool Disabled { get; set; } + + [JsonPropertyName("expirationDate")] + public DateTimeOffset? ExpirationDate { get; set; } + + [JsonPropertyName("file")] + public SendFile File { get; set; } + + [JsonPropertyName("hideEmail")] + public bool HideEmail { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("maxAccessCount")] + public long? MaxAccessCount { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("notes")] + public string Notes { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("text")] + public SendText Text { get; set; } + + [JsonPropertyName("type")] + public SendType Type { get; set; } + } + + public partial class SendFile + { + [JsonPropertyName("fileName")] + public string FileName { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("size")] + public string Size { get; set; } + + /// + /// Readable size, ex: "4.2 KB" or "1.43 GB" + /// + [JsonPropertyName("sizeName")] + public string SizeName { get; set; } + } + + public partial class SendText + { + [JsonPropertyName("hidden")] + public bool Hidden { get; set; } + + [JsonPropertyName("text")] + public string Text { get; set; } + } + + public partial class SendListView + { + [JsonPropertyName("accessId")] + public string AccessId { get; set; } + + [JsonPropertyName("deletionDate")] + public DateTimeOffset DeletionDate { get; set; } + + [JsonPropertyName("disabled")] + public bool Disabled { get; set; } + + [JsonPropertyName("expirationDate")] + public DateTimeOffset? ExpirationDate { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("type")] + public SendType Type { get; set; } + } + + public partial class SendView + { + [JsonPropertyName("accessCount")] + public long AccessCount { get; set; } + + [JsonPropertyName("accessId")] + public string AccessId { get; set; } + + [JsonPropertyName("deletionDate")] + public DateTimeOffset DeletionDate { get; set; } + + [JsonPropertyName("disabled")] + public bool Disabled { get; set; } + + [JsonPropertyName("expirationDate")] + public DateTimeOffset? ExpirationDate { get; set; } + + [JsonPropertyName("file")] + public SendFileView File { get; set; } + + [JsonPropertyName("hideEmail")] + public bool HideEmail { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("maxAccessCount")] + public long? MaxAccessCount { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("notes")] + public string Notes { get; set; } + + [JsonPropertyName("password")] + public string Password { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("text")] + public SendTextView Text { get; set; } + + [JsonPropertyName("type")] + public SendType Type { get; set; } + } + + public partial class SendFileView + { + [JsonPropertyName("fileName")] + public string FileName { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("size")] + public string Size { get; set; } + + /// + /// Readable size, ex: "4.2 KB" or "1.43 GB" + /// + [JsonPropertyName("sizeName")] + public string SizeName { get; set; } + } + + public partial class SendTextView + { + [JsonPropertyName("hidden")] + public bool Hidden { get; set; } + + [JsonPropertyName("text")] + public string Text { get; set; } + } + + public partial class ResponseForApiKeyLoginResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public ApiKeyLoginResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class ApiKeyLoginResponse + { + [JsonPropertyName("authenticated")] + public bool Authenticated { get; set; } + + /// + /// Whether or not the user is required to update their master password + /// + [JsonPropertyName("forcePasswordReset")] + public bool ForcePasswordReset { get; set; } + + /// + /// TODO: What does this do? + /// + [JsonPropertyName("resetMasterPassword")] + public bool ResetMasterPassword { get; set; } + + [JsonPropertyName("twoFactor")] + public ApiKeyLoginResponseTwoFactorProviders TwoFactor { get; set; } + } + + public partial class ApiKeyLoginResponseTwoFactorProviders + { + [JsonPropertyName("authenticator")] + public PurpleAuthenticator Authenticator { get; set; } + + /// + /// Duo-backed 2fa + /// + [JsonPropertyName("duo")] + public PurpleDuo Duo { get; set; } + + /// + /// Email 2fa + /// + [JsonPropertyName("email")] + public PurpleEmail Email { get; set; } + + /// + /// Duo-backed 2fa operated by an organization the user is a member of + /// + [JsonPropertyName("organizationDuo")] + public PurpleDuo OrganizationDuo { get; set; } + + /// + /// Presence indicates the user has stored this device as bypassing 2fa + /// + [JsonPropertyName("remember")] + public PurpleRemember Remember { get; set; } + + /// + /// WebAuthn-backed 2fa + /// + [JsonPropertyName("webAuthn")] + public PurpleWebAuthn WebAuthn { get; set; } + + /// + /// Yubikey-backed 2fa + /// + [JsonPropertyName("yubiKey")] + public PurpleYubiKey YubiKey { get; set; } + } + + public partial class PurpleAuthenticator + { + } + + public partial class PurpleDuo + { + [JsonPropertyName("host")] + public string Host { get; set; } + + [JsonPropertyName("signature")] + public string Signature { get; set; } + } + + public partial class PurpleEmail + { + /// + /// The email to request a 2fa TOTP for + /// + [JsonPropertyName("email")] + public string Email { get; set; } + } + + public partial class PurpleRemember + { + } + + public partial class PurpleWebAuthn + { + } + + public partial class PurpleYubiKey + { + /// + /// Whether the stored yubikey supports near field communication + /// + [JsonPropertyName("nfc")] + public bool Nfc { get; set; } + } + + public partial class ResponseForFingerprintResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public FingerprintResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class FingerprintResponse + { + [JsonPropertyName("fingerprint")] + public string Fingerprint { get; set; } + } + + public partial class ResponseForPasswordLoginResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public PasswordLoginResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class PasswordLoginResponse + { + [JsonPropertyName("authenticated")] + public bool Authenticated { get; set; } + + /// + /// The information required to present the user with a captcha challenge. Only present when + /// authentication fails due to requiring validation of a captcha challenge. + /// + [JsonPropertyName("captcha")] + public CaptchaResponse Captcha { get; set; } + + /// + /// Whether or not the user is required to update their master password + /// + [JsonPropertyName("forcePasswordReset")] + public bool ForcePasswordReset { get; set; } + + /// + /// TODO: What does this do? + /// + [JsonPropertyName("resetMasterPassword")] + public bool ResetMasterPassword { get; set; } + + /// + /// The available two factor authentication options. Present only when authentication fails + /// due to requiring a second authentication factor. + /// + [JsonPropertyName("twoFactor")] + public PasswordLoginResponseTwoFactorProviders TwoFactor { get; set; } + } + + public partial class CaptchaResponse + { + /// + /// hcaptcha site key + /// + [JsonPropertyName("siteKey")] + public string SiteKey { get; set; } + } + + public partial class PasswordLoginResponseTwoFactorProviders + { + [JsonPropertyName("authenticator")] + public FluffyAuthenticator Authenticator { get; set; } + + /// + /// Duo-backed 2fa + /// + [JsonPropertyName("duo")] + public FluffyDuo Duo { get; set; } + + /// + /// Email 2fa + /// + [JsonPropertyName("email")] + public FluffyEmail Email { get; set; } + + /// + /// Duo-backed 2fa operated by an organization the user is a member of + /// + [JsonPropertyName("organizationDuo")] + public FluffyDuo OrganizationDuo { get; set; } + + /// + /// Presence indicates the user has stored this device as bypassing 2fa + /// + [JsonPropertyName("remember")] + public FluffyRemember Remember { get; set; } + + /// + /// WebAuthn-backed 2fa + /// + [JsonPropertyName("webAuthn")] + public FluffyWebAuthn WebAuthn { get; set; } + + /// + /// Yubikey-backed 2fa + /// + [JsonPropertyName("yubiKey")] + public FluffyYubiKey YubiKey { get; set; } + } + + public partial class FluffyAuthenticator + { + } + + public partial class FluffyDuo + { + [JsonPropertyName("host")] + public string Host { get; set; } + + [JsonPropertyName("signature")] + public string Signature { get; set; } + } + + public partial class FluffyEmail + { + /// + /// The email to request a 2fa TOTP for + /// + [JsonPropertyName("email")] + public string Email { get; set; } + } + + public partial class FluffyRemember + { + } + + public partial class FluffyWebAuthn + { + } + + public partial class FluffyYubiKey + { + /// + /// Whether the stored yubikey supports near field communication + /// + [JsonPropertyName("nfc")] + public bool Nfc { get; set; } + } + + public partial class ResponseForProjectResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public ProjectResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class ProjectResponse + { + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + } + + public partial class ResponseForProjectsDeleteResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public ProjectsDeleteResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class ProjectsDeleteResponse + { + [JsonPropertyName("data")] + public ProjectDeleteResponse[] Data { get; set; } + } + + public partial class ProjectDeleteResponse + { + [JsonPropertyName("error")] + public string Error { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + } + + public partial class ResponseForProjectsResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public ProjectsResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class ProjectsResponse + { + [JsonPropertyName("data")] + public DatumElement[] Data { get; set; } + } + + public partial class DatumElement + { + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + } + + public partial class ResponseForSecretIdentifiersResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public SecretIdentifiersResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class SecretIdentifiersResponse + { + [JsonPropertyName("data")] + public SecretIdentifierResponse[] Data { get; set; } + } + + public partial class SecretIdentifierResponse + { + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + } + + public partial class ResponseForSecretResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public SecretResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class SecretResponse + { + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("note")] + public string Note { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("projectId")] + public Guid? ProjectId { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class ResponseForSecretsDeleteResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public SecretsDeleteResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class SecretsDeleteResponse + { + [JsonPropertyName("data")] + public SecretDeleteResponse[] Data { get; set; } + } + + public partial class SecretDeleteResponse + { + [JsonPropertyName("error")] + public string Error { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + } + + public partial class ResponseForSecretsResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public SecretsResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class SecretsResponse + { + [JsonPropertyName("data")] + public DatumClass[] Data { get; set; } + } + + public partial class DatumClass + { + [JsonPropertyName("creationDate")] + public DateTimeOffset CreationDate { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("key")] + public string Key { get; set; } + + [JsonPropertyName("note")] + public string Note { get; set; } + + [JsonPropertyName("organizationId")] + public Guid OrganizationId { get; set; } + + [JsonPropertyName("projectId")] + public Guid? ProjectId { get; set; } + + [JsonPropertyName("revisionDate")] + public DateTimeOffset RevisionDate { get; set; } + + [JsonPropertyName("value")] + public string Value { get; set; } + } + + public partial class ResponseForSyncResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public SyncResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class SyncResponse + { + /// + /// List of ciphers accesible by the user + /// + [JsonPropertyName("ciphers")] + public CipherDetailsResponse[] Ciphers { get; set; } + + /// + /// Data about the user, including their encryption keys and the organizations they are a + /// part of + /// + [JsonPropertyName("profile")] + public ProfileResponse Profile { get; set; } + } + + public partial class CipherDetailsResponse + { + } + + /// + /// Data about the user, including their encryption keys and the organizations they are a + /// part of + /// + public partial class ProfileResponse + { + [JsonPropertyName("email")] + public string Email { get; set; } + + [JsonPropertyName("id")] + public Guid Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("organizations")] + public ProfileOrganizationResponse[] Organizations { get; set; } + } + + public partial class ProfileOrganizationResponse + { + [JsonPropertyName("id")] + public Guid Id { get; set; } + } + + public partial class ResponseForUserApiKeyResponse + { + /// + /// The response data. Populated if `success` is true. + /// + [JsonPropertyName("data")] + public UserApiKeyResponse Data { get; set; } + + /// + /// A message for any error that may occur. Populated if `success` is false. + /// + [JsonPropertyName("errorMessage")] + public string ErrorMessage { get; set; } + + /// + /// Whether or not the SDK request succeeded. + /// + [JsonPropertyName("success")] + public bool Success { get; set; } + } + + public partial class UserApiKeyResponse + { + /// + /// The user's API key, which represents the client_secret portion of an oauth request. + /// + [JsonPropertyName("apiKey")] + public string ApiKey { get; set; } + } + + /// + /// Device type to send to Bitwarden. Defaults to SDK + /// + public enum DeviceType { Android, AndroidAmazon, ChromeBrowser, ChromeExtension, EdgeBrowser, EdgeExtension, FirefoxBrowser, FirefoxExtension, IOs, IeBrowser, LinuxDesktop, MacOsDesktop, OperaBrowser, OperaExtension, SafariBrowser, SafariExtension, Sdk, UnknownBrowser, Uwp, VivaldiBrowser, VivaldiExtension, WindowsDesktop }; + + /// + /// Two-factor provider + /// + public enum TwoFactorProvider { Authenticator, Duo, Email, OrganizationDuo, Remember, U2F, WebAuthn, Yubikey }; + + public enum LinkedIdType { Address1, Address2, Address3, Brand, CardholderName, City, Code, Company, Country, Email, ExpMonth, ExpYear, FirstName, FullName, LastName, LicenseNumber, MiddleName, Number, PassportNumber, Password, Phone, PostalCode, Ssn, State, Title, Username }; + + public enum FieldType { Boolean, Hidden, Linked, Text }; + + public enum UriMatchType { Domain, Exact, Host, Never, RegularExpression, StartsWith }; + + public enum CipherRepromptType { None, Password }; + + public enum SecureNoteType { Generic }; + + public enum CipherType { Card, Identity, Login, SecureNote }; + + public enum ExportFormatEnum { AccountEncryptedJson, Csv, Json }; + + public enum SendType { File, Text }; + + public partial struct ExportFormat + { + public ExportFormatEnum? Enum; + public ExportFormatClass ExportFormatClass; + + public static implicit operator ExportFormat(ExportFormatEnum Enum) => new ExportFormat { Enum = Enum }; + public static implicit operator ExportFormat(ExportFormatClass ExportFormatClass) => new ExportFormat { ExportFormatClass = ExportFormatClass }; + } + + public partial class ClientSettings + { + public static ClientSettings FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class Command + { + public static Command FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class DocRef + { + public static DocRef FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForApiKeyLoginResponse + { + public static ResponseForApiKeyLoginResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForFingerprintResponse + { + public static ResponseForFingerprintResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForPasswordLoginResponse + { + public static ResponseForPasswordLoginResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForProjectResponse + { + public static ResponseForProjectResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForProjectsDeleteResponse + { + public static ResponseForProjectsDeleteResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForProjectsResponse + { + public static ResponseForProjectsResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForSecretIdentifiersResponse + { + public static ResponseForSecretIdentifiersResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForSecretResponse + { + public static ResponseForSecretResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForSecretsDeleteResponse + { + public static ResponseForSecretsDeleteResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForSecretsResponse + { + public static ResponseForSecretsResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForSyncResponse + { + public static ResponseForSyncResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public partial class ResponseForUserApiKeyResponse + { + public static ResponseForUserApiKeyResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); + } + + public static class Serialize + { + public static string ToJson(this ClientSettings self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this Command self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this DocRef self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForApiKeyLoginResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForFingerprintResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForPasswordLoginResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForProjectResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForProjectsDeleteResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForProjectsResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForSecretIdentifiersResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForSecretResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForSecretsDeleteResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForSecretsResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForSyncResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + public static string ToJson(this ResponseForUserApiKeyResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); + } + + internal static class Converter + { + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) + { + Converters = + { + DeviceTypeConverter.Singleton, + TwoFactorProviderConverter.Singleton, + LinkedIdTypeConverter.Singleton, + FieldTypeConverter.Singleton, + UriMatchTypeConverter.Singleton, + CipherRepromptTypeConverter.Singleton, + SecureNoteTypeConverter.Singleton, + CipherTypeConverter.Singleton, + ExportFormatConverter.Singleton, + ExportFormatEnumConverter.Singleton, + SendTypeConverter.Singleton, + new DateOnlyConverter(), + new TimeOnlyConverter(), + IsoDateTimeOffsetConverter.Singleton + }, + }; + } + + internal class DeviceTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(DeviceType); + + public override DeviceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "Android": + return DeviceType.Android; + case "AndroidAmazon": + return DeviceType.AndroidAmazon; + case "ChromeBrowser": + return DeviceType.ChromeBrowser; + case "ChromeExtension": + return DeviceType.ChromeExtension; + case "EdgeBrowser": + return DeviceType.EdgeBrowser; + case "EdgeExtension": + return DeviceType.EdgeExtension; + case "FirefoxBrowser": + return DeviceType.FirefoxBrowser; + case "FirefoxExtension": + return DeviceType.FirefoxExtension; + case "IEBrowser": + return DeviceType.IeBrowser; + case "LinuxDesktop": + return DeviceType.LinuxDesktop; + case "MacOsDesktop": + return DeviceType.MacOsDesktop; + case "OperaBrowser": + return DeviceType.OperaBrowser; + case "OperaExtension": + return DeviceType.OperaExtension; + case "SDK": + return DeviceType.Sdk; + case "SafariBrowser": + return DeviceType.SafariBrowser; + case "SafariExtension": + return DeviceType.SafariExtension; + case "UWP": + return DeviceType.Uwp; + case "UnknownBrowser": + return DeviceType.UnknownBrowser; + case "VivaldiBrowser": + return DeviceType.VivaldiBrowser; + case "VivaldiExtension": + return DeviceType.VivaldiExtension; + case "WindowsDesktop": + return DeviceType.WindowsDesktop; + case "iOS": + return DeviceType.IOs; + } + throw new Exception("Cannot unmarshal type DeviceType"); + } + + public override void Write(Utf8JsonWriter writer, DeviceType value, JsonSerializerOptions options) + { + switch (value) + { + case DeviceType.Android: + JsonSerializer.Serialize(writer, "Android", options); + return; + case DeviceType.AndroidAmazon: + JsonSerializer.Serialize(writer, "AndroidAmazon", options); + return; + case DeviceType.ChromeBrowser: + JsonSerializer.Serialize(writer, "ChromeBrowser", options); + return; + case DeviceType.ChromeExtension: + JsonSerializer.Serialize(writer, "ChromeExtension", options); + return; + case DeviceType.EdgeBrowser: + JsonSerializer.Serialize(writer, "EdgeBrowser", options); + return; + case DeviceType.EdgeExtension: + JsonSerializer.Serialize(writer, "EdgeExtension", options); + return; + case DeviceType.FirefoxBrowser: + JsonSerializer.Serialize(writer, "FirefoxBrowser", options); + return; + case DeviceType.FirefoxExtension: + JsonSerializer.Serialize(writer, "FirefoxExtension", options); + return; + case DeviceType.IeBrowser: + JsonSerializer.Serialize(writer, "IEBrowser", options); + return; + case DeviceType.LinuxDesktop: + JsonSerializer.Serialize(writer, "LinuxDesktop", options); + return; + case DeviceType.MacOsDesktop: + JsonSerializer.Serialize(writer, "MacOsDesktop", options); + return; + case DeviceType.OperaBrowser: + JsonSerializer.Serialize(writer, "OperaBrowser", options); + return; + case DeviceType.OperaExtension: + JsonSerializer.Serialize(writer, "OperaExtension", options); + return; + case DeviceType.Sdk: + JsonSerializer.Serialize(writer, "SDK", options); + return; + case DeviceType.SafariBrowser: + JsonSerializer.Serialize(writer, "SafariBrowser", options); + return; + case DeviceType.SafariExtension: + JsonSerializer.Serialize(writer, "SafariExtension", options); + return; + case DeviceType.Uwp: + JsonSerializer.Serialize(writer, "UWP", options); + return; + case DeviceType.UnknownBrowser: + JsonSerializer.Serialize(writer, "UnknownBrowser", options); + return; + case DeviceType.VivaldiBrowser: + JsonSerializer.Serialize(writer, "VivaldiBrowser", options); + return; + case DeviceType.VivaldiExtension: + JsonSerializer.Serialize(writer, "VivaldiExtension", options); + return; + case DeviceType.WindowsDesktop: + JsonSerializer.Serialize(writer, "WindowsDesktop", options); + return; + case DeviceType.IOs: + JsonSerializer.Serialize(writer, "iOS", options); + return; + } + throw new Exception("Cannot marshal type DeviceType"); + } + + public static readonly DeviceTypeConverter Singleton = new DeviceTypeConverter(); + } + + internal class TwoFactorProviderConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(TwoFactorProvider); + + public override TwoFactorProvider Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "Authenticator": + return TwoFactorProvider.Authenticator; + case "Duo": + return TwoFactorProvider.Duo; + case "Email": + return TwoFactorProvider.Email; + case "OrganizationDuo": + return TwoFactorProvider.OrganizationDuo; + case "Remember": + return TwoFactorProvider.Remember; + case "U2f": + return TwoFactorProvider.U2F; + case "WebAuthn": + return TwoFactorProvider.WebAuthn; + case "Yubikey": + return TwoFactorProvider.Yubikey; + } + throw new Exception("Cannot unmarshal type TwoFactorProvider"); + } + + public override void Write(Utf8JsonWriter writer, TwoFactorProvider value, JsonSerializerOptions options) + { + switch (value) + { + case TwoFactorProvider.Authenticator: + JsonSerializer.Serialize(writer, "Authenticator", options); + return; + case TwoFactorProvider.Duo: + JsonSerializer.Serialize(writer, "Duo", options); + return; + case TwoFactorProvider.Email: + JsonSerializer.Serialize(writer, "Email", options); + return; + case TwoFactorProvider.OrganizationDuo: + JsonSerializer.Serialize(writer, "OrganizationDuo", options); + return; + case TwoFactorProvider.Remember: + JsonSerializer.Serialize(writer, "Remember", options); + return; + case TwoFactorProvider.U2F: + JsonSerializer.Serialize(writer, "U2f", options); + return; + case TwoFactorProvider.WebAuthn: + JsonSerializer.Serialize(writer, "WebAuthn", options); + return; + case TwoFactorProvider.Yubikey: + JsonSerializer.Serialize(writer, "Yubikey", options); + return; + } + throw new Exception("Cannot marshal type TwoFactorProvider"); + } + + public static readonly TwoFactorProviderConverter Singleton = new TwoFactorProviderConverter(); + } + + internal class LinkedIdTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(LinkedIdType); + + public override LinkedIdType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "Address1": + return LinkedIdType.Address1; + case "Address2": + return LinkedIdType.Address2; + case "Address3": + return LinkedIdType.Address3; + case "Brand": + return LinkedIdType.Brand; + case "CardholderName": + return LinkedIdType.CardholderName; + case "City": + return LinkedIdType.City; + case "Code": + return LinkedIdType.Code; + case "Company": + return LinkedIdType.Company; + case "Country": + return LinkedIdType.Country; + case "Email": + return LinkedIdType.Email; + case "ExpMonth": + return LinkedIdType.ExpMonth; + case "ExpYear": + return LinkedIdType.ExpYear; + case "FirstName": + return LinkedIdType.FirstName; + case "FullName": + return LinkedIdType.FullName; + case "LastName": + return LinkedIdType.LastName; + case "LicenseNumber": + return LinkedIdType.LicenseNumber; + case "MiddleName": + return LinkedIdType.MiddleName; + case "Number": + return LinkedIdType.Number; + case "PassportNumber": + return LinkedIdType.PassportNumber; + case "Password": + return LinkedIdType.Password; + case "Phone": + return LinkedIdType.Phone; + case "PostalCode": + return LinkedIdType.PostalCode; + case "Ssn": + return LinkedIdType.Ssn; + case "State": + return LinkedIdType.State; + case "Title": + return LinkedIdType.Title; + case "Username": + return LinkedIdType.Username; + } + throw new Exception("Cannot unmarshal type LinkedIdType"); + } + + public override void Write(Utf8JsonWriter writer, LinkedIdType value, JsonSerializerOptions options) + { + switch (value) + { + case LinkedIdType.Address1: + JsonSerializer.Serialize(writer, "Address1", options); + return; + case LinkedIdType.Address2: + JsonSerializer.Serialize(writer, "Address2", options); + return; + case LinkedIdType.Address3: + JsonSerializer.Serialize(writer, "Address3", options); + return; + case LinkedIdType.Brand: + JsonSerializer.Serialize(writer, "Brand", options); + return; + case LinkedIdType.CardholderName: + JsonSerializer.Serialize(writer, "CardholderName", options); + return; + case LinkedIdType.City: + JsonSerializer.Serialize(writer, "City", options); + return; + case LinkedIdType.Code: + JsonSerializer.Serialize(writer, "Code", options); + return; + case LinkedIdType.Company: + JsonSerializer.Serialize(writer, "Company", options); + return; + case LinkedIdType.Country: + JsonSerializer.Serialize(writer, "Country", options); + return; + case LinkedIdType.Email: + JsonSerializer.Serialize(writer, "Email", options); + return; + case LinkedIdType.ExpMonth: + JsonSerializer.Serialize(writer, "ExpMonth", options); + return; + case LinkedIdType.ExpYear: + JsonSerializer.Serialize(writer, "ExpYear", options); + return; + case LinkedIdType.FirstName: + JsonSerializer.Serialize(writer, "FirstName", options); + return; + case LinkedIdType.FullName: + JsonSerializer.Serialize(writer, "FullName", options); + return; + case LinkedIdType.LastName: + JsonSerializer.Serialize(writer, "LastName", options); + return; + case LinkedIdType.LicenseNumber: + JsonSerializer.Serialize(writer, "LicenseNumber", options); + return; + case LinkedIdType.MiddleName: + JsonSerializer.Serialize(writer, "MiddleName", options); + return; + case LinkedIdType.Number: + JsonSerializer.Serialize(writer, "Number", options); + return; + case LinkedIdType.PassportNumber: + JsonSerializer.Serialize(writer, "PassportNumber", options); + return; + case LinkedIdType.Password: + JsonSerializer.Serialize(writer, "Password", options); + return; + case LinkedIdType.Phone: + JsonSerializer.Serialize(writer, "Phone", options); + return; + case LinkedIdType.PostalCode: + JsonSerializer.Serialize(writer, "PostalCode", options); + return; + case LinkedIdType.Ssn: + JsonSerializer.Serialize(writer, "Ssn", options); + return; + case LinkedIdType.State: + JsonSerializer.Serialize(writer, "State", options); + return; + case LinkedIdType.Title: + JsonSerializer.Serialize(writer, "Title", options); + return; + case LinkedIdType.Username: + JsonSerializer.Serialize(writer, "Username", options); + return; + } + throw new Exception("Cannot marshal type LinkedIdType"); + } + + public static readonly LinkedIdTypeConverter Singleton = new LinkedIdTypeConverter(); + } + + internal class FieldTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(FieldType); + + public override FieldType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "Boolean": + return FieldType.Boolean; + case "Hidden": + return FieldType.Hidden; + case "Linked": + return FieldType.Linked; + case "Text": + return FieldType.Text; + } + throw new Exception("Cannot unmarshal type FieldType"); + } + + public override void Write(Utf8JsonWriter writer, FieldType value, JsonSerializerOptions options) + { + switch (value) + { + case FieldType.Boolean: + JsonSerializer.Serialize(writer, "Boolean", options); + return; + case FieldType.Hidden: + JsonSerializer.Serialize(writer, "Hidden", options); + return; + case FieldType.Linked: + JsonSerializer.Serialize(writer, "Linked", options); + return; + case FieldType.Text: + JsonSerializer.Serialize(writer, "Text", options); + return; + } + throw new Exception("Cannot marshal type FieldType"); + } + + public static readonly FieldTypeConverter Singleton = new FieldTypeConverter(); + } + + internal class UriMatchTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(UriMatchType); + + public override UriMatchType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "domain": + return UriMatchType.Domain; + case "exact": + return UriMatchType.Exact; + case "host": + return UriMatchType.Host; + case "never": + return UriMatchType.Never; + case "regularExpression": + return UriMatchType.RegularExpression; + case "startsWith": + return UriMatchType.StartsWith; + } + throw new Exception("Cannot unmarshal type UriMatchType"); + } + + public override void Write(Utf8JsonWriter writer, UriMatchType value, JsonSerializerOptions options) + { + switch (value) + { + case UriMatchType.Domain: + JsonSerializer.Serialize(writer, "domain", options); + return; + case UriMatchType.Exact: + JsonSerializer.Serialize(writer, "exact", options); + return; + case UriMatchType.Host: + JsonSerializer.Serialize(writer, "host", options); + return; + case UriMatchType.Never: + JsonSerializer.Serialize(writer, "never", options); + return; + case UriMatchType.RegularExpression: + JsonSerializer.Serialize(writer, "regularExpression", options); + return; + case UriMatchType.StartsWith: + JsonSerializer.Serialize(writer, "startsWith", options); + return; + } + throw new Exception("Cannot marshal type UriMatchType"); + } + + public static readonly UriMatchTypeConverter Singleton = new UriMatchTypeConverter(); + } + + internal class CipherRepromptTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(CipherRepromptType); + + public override CipherRepromptType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "None": + return CipherRepromptType.None; + case "Password": + return CipherRepromptType.Password; + } + throw new Exception("Cannot unmarshal type CipherRepromptType"); + } + + public override void Write(Utf8JsonWriter writer, CipherRepromptType value, JsonSerializerOptions options) + { + switch (value) + { + case CipherRepromptType.None: + JsonSerializer.Serialize(writer, "None", options); + return; + case CipherRepromptType.Password: + JsonSerializer.Serialize(writer, "Password", options); + return; + } + throw new Exception("Cannot marshal type CipherRepromptType"); + } + + public static readonly CipherRepromptTypeConverter Singleton = new CipherRepromptTypeConverter(); + } + + internal class SecureNoteTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(SecureNoteType); + + public override SecureNoteType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + if (value == "Generic") + { + return SecureNoteType.Generic; + } + throw new Exception("Cannot unmarshal type SecureNoteType"); + } + + public override void Write(Utf8JsonWriter writer, SecureNoteType value, JsonSerializerOptions options) + { + if (value == SecureNoteType.Generic) + { + JsonSerializer.Serialize(writer, "Generic", options); + return; + } + throw new Exception("Cannot marshal type SecureNoteType"); + } + + public static readonly SecureNoteTypeConverter Singleton = new SecureNoteTypeConverter(); + } + + internal class CipherTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(CipherType); + + public override CipherType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "Card": + return CipherType.Card; + case "Identity": + return CipherType.Identity; + case "Login": + return CipherType.Login; + case "SecureNote": + return CipherType.SecureNote; + } + throw new Exception("Cannot unmarshal type CipherType"); + } + + public override void Write(Utf8JsonWriter writer, CipherType value, JsonSerializerOptions options) + { + switch (value) + { + case CipherType.Card: + JsonSerializer.Serialize(writer, "Card", options); + return; + case CipherType.Identity: + JsonSerializer.Serialize(writer, "Identity", options); + return; + case CipherType.Login: + JsonSerializer.Serialize(writer, "Login", options); + return; + case CipherType.SecureNote: + JsonSerializer.Serialize(writer, "SecureNote", options); + return; + } + throw new Exception("Cannot marshal type CipherType"); + } + + public static readonly CipherTypeConverter Singleton = new CipherTypeConverter(); + } + + internal class ExportFormatConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(ExportFormat); + + public override ExportFormat Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.String: + var stringValue = reader.GetString(); + switch (stringValue) + { + case "AccountEncryptedJson": + return new ExportFormat { Enum = ExportFormatEnum.AccountEncryptedJson }; + case "Csv": + return new ExportFormat { Enum = ExportFormatEnum.Csv }; + case "Json": + return new ExportFormat { Enum = ExportFormatEnum.Json }; + } + break; + case JsonTokenType.StartObject: + var objectValue = JsonSerializer.Deserialize(ref reader, options); + return new ExportFormat { ExportFormatClass = objectValue }; + } + throw new Exception("Cannot unmarshal type ExportFormat"); + } + + public override void Write(Utf8JsonWriter writer, ExportFormat value, JsonSerializerOptions options) + { + if (value.Enum != null) + { + switch (value.Enum) + { + case ExportFormatEnum.AccountEncryptedJson: + JsonSerializer.Serialize(writer, "AccountEncryptedJson", options); + return; + case ExportFormatEnum.Csv: + JsonSerializer.Serialize(writer, "Csv", options); + return; + case ExportFormatEnum.Json: + JsonSerializer.Serialize(writer, "Json", options); + return; + } + } + if (value.ExportFormatClass != null) + { + JsonSerializer.Serialize(writer, value.ExportFormatClass, options); + return; + } + throw new Exception("Cannot marshal type ExportFormat"); + } + + public static readonly ExportFormatConverter Singleton = new ExportFormatConverter(); + } + + internal class ExportFormatEnumConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(ExportFormatEnum); + + public override ExportFormatEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "AccountEncryptedJson": + return ExportFormatEnum.AccountEncryptedJson; + case "Csv": + return ExportFormatEnum.Csv; + case "Json": + return ExportFormatEnum.Json; + } + throw new Exception("Cannot unmarshal type ExportFormatEnum"); + } + + public override void Write(Utf8JsonWriter writer, ExportFormatEnum value, JsonSerializerOptions options) + { + switch (value) + { + case ExportFormatEnum.AccountEncryptedJson: + JsonSerializer.Serialize(writer, "AccountEncryptedJson", options); + return; + case ExportFormatEnum.Csv: + JsonSerializer.Serialize(writer, "Csv", options); + return; + case ExportFormatEnum.Json: + JsonSerializer.Serialize(writer, "Json", options); + return; + } + throw new Exception("Cannot marshal type ExportFormatEnum"); + } + + public static readonly ExportFormatEnumConverter Singleton = new ExportFormatEnumConverter(); + } + + internal class SendTypeConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(SendType); + + public override SendType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + switch (value) + { + case "File": + return SendType.File; + case "Text": + return SendType.Text; + } + throw new Exception("Cannot unmarshal type SendType"); + } + + public override void Write(Utf8JsonWriter writer, SendType value, JsonSerializerOptions options) + { + switch (value) + { + case SendType.File: + JsonSerializer.Serialize(writer, "File", options); + return; + case SendType.Text: + JsonSerializer.Serialize(writer, "Text", options); + return; + } + throw new Exception("Cannot marshal type SendType"); + } + + public static readonly SendTypeConverter Singleton = new SendTypeConverter(); + } + + public class DateOnlyConverter : JsonConverter + { + private readonly string serializationFormat; + public DateOnlyConverter() : this(null) { } + + public DateOnlyConverter(string? serializationFormat) + { + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; + } + + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + return DateOnly.Parse(value!); + } + + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString(serializationFormat)); + } + + public class TimeOnlyConverter : JsonConverter + { + private readonly string serializationFormat; + + public TimeOnlyConverter() : this(null) { } + + public TimeOnlyConverter(string? serializationFormat) + { + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; + } + + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var value = reader.GetString(); + return TimeOnly.Parse(value!); + } + + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString(serializationFormat)); + } + + internal class IsoDateTimeOffsetConverter : JsonConverter + { + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); + + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; + + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; + private string? _dateTimeFormat; + private CultureInfo? _culture; + + public DateTimeStyles DateTimeStyles + { + get => _dateTimeStyles; + set => _dateTimeStyles = value; + } + + public string? DateTimeFormat + { + get => _dateTimeFormat ?? string.Empty; + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; + } + + public CultureInfo Culture + { + get => _culture ?? CultureInfo.CurrentCulture; + set => _culture = value; + } + + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) + { + string text; + + + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) + { + value = value.ToUniversalTime(); + } + + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); + + writer.WriteStringValue(text); + } + + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? dateText = reader.GetString(); + + if (string.IsNullOrEmpty(dateText) == false) + { + if (!string.IsNullOrEmpty(_dateTimeFormat)) + { + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); + } + else + { + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); + } + } + else + { + return default(DateTimeOffset); + } + } + + + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); + } +} +#pragma warning restore CS8618 +#pragma warning restore CS8601 +#pragma warning restore CS8603 + From 93eadd14b84774ffcea38891f7f30a57c8e9e6e4 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:21:02 +0200 Subject: [PATCH 15/30] Update example, remove hard dependency on schemas --- languages/go/bitwarden_client.go | 11 +++++++++-- languages/go/build.sh | 2 +- languages/go/{ => example}/example.go | 12 +++--------- .../go/internal/cinterface/bitwarden_library.go | 4 ++-- support/scripts/schemas.ts | 2 +- 5 files changed, 16 insertions(+), 15 deletions(-) rename languages/go/{ => example}/example.go (90%) diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index 6d2da353c..297193c93 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -14,8 +14,15 @@ type BitwardenClient struct { Secrets SecretsInterface } -func NewBitwardenClient(settings ClientSettings) *BitwardenClient { - settingsJSON, err := json.Marshal(settings) +func NewBitwardenClient(apiURL *string, identityURL *string, userAgent *string) *BitwardenClient { + + clientSettings := ClientSettings{ + APIURL: apiURL, + IdentityURL: identityURL, + UserAgent: userAgent, + } + + settingsJSON, err := json.Marshal(clientSettings) if err != nil { panic(err) } diff --git a/languages/go/build.sh b/languages/go/build.sh index f3a5125f3..0735ead6c 100755 --- a/languages/go/build.sh +++ b/languages/go/build.sh @@ -1,7 +1,7 @@ #!/bin/bash if [ -n "$BITWARDEN_LIB_PATH" ]; then - sed "s/{{.LibPath}}/$BITWARDEN_LIB_PATH/g" bitwarden_library.go > bitwarden_library.go + sed "s/{{.LibPath}}/$BITWARDEN_LIB_PATH/g" internal/cinterface/bitwarden_library.go > internal/cinterface/bitwarden_library.go go build -tags custom else go build diff --git a/languages/go/example.go b/languages/go/example/example.go similarity index 90% rename from languages/go/example.go rename to languages/go/example/example.go index 29e217180..28ea29604 100644 --- a/languages/go/example.go +++ b/languages/go/example/example.go @@ -1,9 +1,10 @@ -package sdk +package example import ( "fmt" "os" + sdk "github.com/bitwarden/sdk/languages/go" "github.com/gofrs/uuid" ) @@ -12,14 +13,7 @@ func main() { identityURL := os.Getenv("IDENTITY_URL") userAgent := os.Getenv("USER_AGENT") - clientSettings := ClientSettings{ - APIURL: apiURL, - IdentityURL: identityURL, - DeviceType: "SDK", - UserAgent: userAgent, - } - - bitwardenClient := NewBitwardenClient(clientSettings) + bitwardenClient := sdk.NewBitwardenClient(&apiURL, &identityURL, &userAgent) accessToken := os.Getenv("ACCESS_TOKEN") organizationIDStr := os.Getenv("ORGANIZATION_ID") diff --git a/languages/go/internal/cinterface/bitwarden_library.go b/languages/go/internal/cinterface/bitwarden_library.go index 6d6b0bb25..7e50272b6 100644 --- a/languages/go/internal/cinterface/bitwarden_library.go +++ b/languages/go/internal/cinterface/bitwarden_library.go @@ -10,8 +10,8 @@ import ( /* #cgo LDFLAGS: -lbitwarden_c -#cgo linux LDFLAGS: -L/usr/local/lib -L/usr/lib -#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/lib +#cgo linux LDFLAGS: -L/usr/local/lib -L/usr/lib -L ./lib +#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/lib -L ./lib #include typedef void* ClientPtr; extern char* run_command(const char *command, ClientPtr client); diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index 2ca74d447..8d228a036 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -70,7 +70,7 @@ async function main() { inputData, lang: "go", rendererOptions: { - "package": "main", + package: "sdk", }, }); writeToFile("./languages/go/schema.go", go.lines); From 9b4359a711449880f636d902d5ff4ef1b2198f41 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:27:53 +0200 Subject: [PATCH 16/30] initialize example main module --- languages/go/bitwarden_client.go | 3 ++- languages/go/example/example.go | 2 +- languages/go/example/go.mod | 10 ++++++++++ languages/go/example/go.sum | 2 ++ 4 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 languages/go/example/go.mod create mode 100644 languages/go/example/go.sum diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index 297193c93..a417f16af 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -15,11 +15,12 @@ type BitwardenClient struct { } func NewBitwardenClient(apiURL *string, identityURL *string, userAgent *string) *BitwardenClient { - + deviceType := DeviceType("SDK") clientSettings := ClientSettings{ APIURL: apiURL, IdentityURL: identityURL, UserAgent: userAgent, + DeviceType: &deviceType, } settingsJSON, err := json.Marshal(clientSettings) diff --git a/languages/go/example/example.go b/languages/go/example/example.go index 28ea29604..201b200ef 100644 --- a/languages/go/example/example.go +++ b/languages/go/example/example.go @@ -1,4 +1,4 @@ -package example +package main import ( "fmt" diff --git a/languages/go/example/go.mod b/languages/go/example/go.mod new file mode 100644 index 000000000..bbde28fd5 --- /dev/null +++ b/languages/go/example/go.mod @@ -0,0 +1,10 @@ +module example + +replace github.com/bitwarden/sdk/languages/go => ../ + +go 1.20 + +require ( + github.com/bitwarden/sdk/languages/go v0.0.0-00010101000000-000000000000 + github.com/gofrs/uuid v4.4.0+incompatible +) diff --git a/languages/go/example/go.sum b/languages/go/example/go.sum new file mode 100644 index 000000000..c0ad68738 --- /dev/null +++ b/languages/go/example/go.sum @@ -0,0 +1,2 @@ +github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= +github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= From f8342c2f58bf5d0ccc604d47212221bc42dbb827 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:35:56 +0200 Subject: [PATCH 17/30] Be friendly to IDE - add .work --- go.work | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 go.work diff --git a/go.work b/go.work new file mode 100644 index 000000000..b88c248ae --- /dev/null +++ b/go.work @@ -0,0 +1,2 @@ +go 1.20 +go work use ./go/ ./languages/go/ From 574a8329456876566e88aa98b627ee34c74383b1 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:44:30 +0200 Subject: [PATCH 18/30] Unwrap the responses --- languages/go/project.go | 121 +++++++++++++++++++++++----------------- 1 file changed, 69 insertions(+), 52 deletions(-) diff --git a/languages/go/project.go b/languages/go/project.go index e3fe4cc29..a3d56d0eb 100644 --- a/languages/go/project.go +++ b/languages/go/project.go @@ -6,22 +6,48 @@ import ( ) type ProjectsInterface interface { - Create(organizationID string, name string) (ResponseForProjectResponse, error) - List(organizationID string) (ResponseForProjectsResponse, error) - Get(projectID string) (ResponseForProjectResponse, error) - Update(projectID string, organizationID string, name string) (ResponseForProjectResponse, error) - Delete(projectIDs []string) (ResponseForProjectsDeleteResponse, error) + Create(organizationID string, name string) (*ProjectResponse, error) + List(organizationID string) (*ProjectsResponse, error) + Get(projectID string) (*ProjectResponse, error) + Update(projectID string, organizationID string, name string) (*ProjectResponse, error) + Delete(projectIDs []string) (*ProjectsDeleteResponse, error) } type Projects struct { CommandRunner CommandRunnerInterface } +func checkSuccessAndError(responseStr string, v interface{}) error { + var wrapper struct { + Success bool `json:"success"` + ErrorMessage *string `json:"errorMessage"` + } + + err := json.Unmarshal([]byte(responseStr), &wrapper) + if err != nil { + return fmt.Errorf("failed to unmarshal wrapper response: %v", err) + } + + if !wrapper.Success { + if wrapper.ErrorMessage != nil { + return fmt.Errorf("API error: %s", *wrapper.ErrorMessage) + } + return fmt.Errorf("API error: unknown") + } + + err = json.Unmarshal([]byte(responseStr), &v) + if err != nil { + return fmt.Errorf("failed to unmarshal response: %v", err) + } + + return nil +} + func NewProjects(commandRunner CommandRunnerInterface) *Projects { return &Projects{CommandRunner: commandRunner} } -func (p *Projects) Get(id string) (ResponseForProjectResponse, error) { +func (p *Projects) Get(id string) (*ProjectResponse, error) { command := Command{ Projects: &ProjectsCommand{ Get: &ProjectGetRequest{ @@ -29,90 +55,81 @@ func (p *Projects) Get(id string) (ResponseForProjectResponse, error) { }, }, } - - responseStr := p.CommandRunner.RunCommand(command) - var response ResponseForProjectResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForProjectResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + var response ProjectResponse + if err := p.executeCommand(command, &response); err != nil { + return nil, err } - - return response, nil + return &response, nil } -func (p *Projects) Create(organizationId string, name string) (ResponseForProjectResponse, error) { +func (p *Projects) Create(organizationID string, name string) (*ProjectResponse, error) { command := Command{ Projects: &ProjectsCommand{ Create: &ProjectCreateRequest{ - OrganizationID: organizationId, + OrganizationID: organizationID, Name: name, }, }, } - return p.executeCommand(command) + var response ProjectResponse + if err := p.executeCommand(command, &response); err != nil { + return nil, err + } + return &response, nil } -func (p *Projects) Update(id, organizationId string, name string) (ResponseForProjectResponse, error) { +func (p *Projects) List(organizationID string) (*ProjectsResponse, error) { command := Command{ Projects: &ProjectsCommand{ - Update: &ProjectPutRequest{ - ID: id, - OrganizationID: organizationId, - Name: name, + List: &ProjectsListRequest{ + OrganizationID: organizationID, }, }, } - return p.executeCommand(command) + var response ProjectResponse + if err := p.executeCommand(command, &response); err != nil { + return nil, err + } + return &response, nil } -func (p *Projects) Delete(ids []string) (ResponseForProjectsDeleteResponse, error) { +func (p *Projects) Update(projectID, organizationID, name string) (*ProjectResponse, error) { command := Command{ Projects: &ProjectsCommand{ - Delete: &ProjectsDeleteRequest{ - IDS: ids, + Update: &ProjectPutRequest{ + ID: projectID, + OrganizationID: organizationID, + Name: name, }, }, } - responseStr := p.CommandRunner.RunCommand(command) - var response ResponseForProjectsDeleteResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForProjectsDeleteResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + var response ProjectResponse + if err := p.executeCommand(command, &response); err != nil { + return nil, err } - - return response, nil + return &response, nil } -func (p *Projects) List(organizationId string) (ResponseForProjectsResponse, error) { +func (p *Projects) Delete(projectIDs []string) (*ProjectsDeleteResponse, error) { command := Command{ Projects: &ProjectsCommand{ - List: &ProjectsListRequest{ - OrganizationID: organizationId, + Delete: &ProjectsDeleteRequest{ + IDS: projectIDs, }, }, } - responseStr := p.CommandRunner.RunCommand(command) - var response ResponseForProjectsResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForProjectsResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + var response ProjectResponse + if err := p.executeCommand(command, &response); err != nil { + return nil, err } - - return response, nil + return &response, nil } -// Helper method for common command execution and response handling -func (p *Projects) executeCommand(command Command) (ResponseForProjectResponse, error) { +func (p *Projects) executeCommand(command Command, target interface{}) error { responseStr := p.CommandRunner.RunCommand(command) - var response ResponseForProjectResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForProjectResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) - } - - return response, nil + return checkSuccessAndError(responseStr, target) } From 18cdf6cbc270aec714d3c24fbbdc52d95a058889 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 09:53:07 +0200 Subject: [PATCH 19/30] Unwrap the responses --- languages/go/secrets.go | 137 +++++++++++++++++++++++++--------------- 1 file changed, 85 insertions(+), 52 deletions(-) diff --git a/languages/go/secrets.go b/languages/go/secrets.go index 39adcafb0..f2c11e750 100644 --- a/languages/go/secrets.go +++ b/languages/go/secrets.go @@ -6,11 +6,11 @@ import ( ) type SecretsInterface interface { - Create(key, value, note string, organizationID string, projectIDs []string) (ResponseForSecretResponse, error) - List(organizationID string) (ResponseForSecretIdentifiersResponse, error) - Get(secretID string) (ResponseForSecretResponse, error) - Update(secretID string, key, value, note string, organizationID string, projectIDs []string) (ResponseForSecretResponse, error) - Delete(secretIDs []string) (ResponseForSecretsDeleteResponse, error) + Create(key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) + List(organizationID string) (*SecretIdentifiersResponse, error) + Get(secretID string) (*SecretResponse, error) + Update(secretID string, key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) + Delete(secretIDs []string) (*SecretsDeleteResponse, error) } type Secrets struct { @@ -21,89 +21,122 @@ func NewSecrets(commandRunner CommandRunnerInterface) *Secrets { return &Secrets{CommandRunner: commandRunner} } -func (s *Secrets) Get(id string) (ResponseForSecretResponse, error) { - command := Command{ - Secrets: &SecretsCommand{ - Get: &SecretGetRequest{ - ID: id, - }, - }, +func (s *Secrets) executeCommand(command Command, target interface{}) error { + responseStr := s.CommandRunner.RunCommand(command) + return checkSuccessAndError(responseStr, target) +} + +func checkSuccessAndError(responseStr string, v interface{}) error { + var wrapper struct { + Success bool `json:"success"` + ErrorMessage *string `json:"errorMessage"` + } + + err := json.Unmarshal([]byte(responseStr), &wrapper) + if err != nil { + return fmt.Errorf("failed to unmarshal wrapper response: %v", err) + } + + if !wrapper.Success { + if wrapper.ErrorMessage != nil { + return fmt.Errorf("API error: %s", *wrapper.ErrorMessage) + } + return fmt.Errorf("API error: unknown") } - return s.executeCommand(command) + + err = json.Unmarshal([]byte(responseStr), &v) + if err != nil { + return fmt.Errorf("failed to unmarshal response: %v", err) + } + + return nil } -func (s *Secrets) Create(key, value, note string, organizationId string, projectIds []string) (ResponseForSecretResponse, error) { +func (s *Secrets) Create(key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) { command := Command{ Secrets: &SecretsCommand{ Create: &SecretCreateRequest{ Key: key, Value: value, Note: note, - OrganizationID: organizationId, - ProjectIDS: projectIds, + OrganizationID: organizationID, + ProjectIDS: projectIDs, }, }, } - return s.executeCommand(command) + + var response SecretResponse + if err := s.executeCommand(command, &response); err != nil { + return nil, err + } + return &response, nil } -func (s *Secrets) Update(id string, key, value, note string, organizationId string, projectIds []string) (ResponseForSecretResponse, error) { +func (s *Secrets) List(organizationID string) (*SecretIdentifiersResponse, error) { command := Command{ Secrets: &SecretsCommand{ - Update: &SecretPutRequest{ - ID: id, - Key: key, - Value: value, - Note: note, - OrganizationID: organizationId, - ProjectIDS: projectIds, + List: &SecretIdentifiersRequest{ + OrganizationID: organizationID, }, }, } - return s.executeCommand(command) + + var response SecretIdentifiersResponse + if err := s.executeCommand(command, &response); err != nil { + return nil, err + } + return &response, nil } -func (s *Secrets) Delete(ids []string) (ResponseForSecretsDeleteResponse, error) { +func (s *Secrets) Get(id string) (*SecretResponse, error) { command := Command{ Secrets: &SecretsCommand{ - Delete: &SecretsDeleteRequest{ - IDS: ids, + Get: &SecretGetRequest{ + ID: id, }, }, } - responseStr := s.CommandRunner.RunCommand(command) - var response ResponseForSecretsDeleteResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForSecretsDeleteResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + + var response SecretResponse + if err := s.executeCommand(command, &response); err != nil { + return nil, err } - return response, nil + return &response, nil } -func (s *Secrets) List(organizationId string) (ResponseForSecretIdentifiersResponse, error) { +func (s *Secrets) Update(id string, key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) { command := Command{ Secrets: &SecretsCommand{ - List: &SecretIdentifiersRequest{ - OrganizationID: organizationId, + Update: &SecretPutRequest{ + ID: id, + Key: key, + Value: value, + Note: note, + OrganizationID: organizationID, + ProjectIDS: projectIDs, }, }, } - responseStr := s.CommandRunner.RunCommand(command) - var response ResponseForSecretIdentifiersResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForSecretIdentifiersResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) + + var response SecretResponse + if err := s.executeCommand(command, &response); err != nil { + return nil, err } - return response, nil + return &response, nil } -// Helper method for common command execution and response handling -func (s *Secrets) executeCommand(command Command) (ResponseForSecretResponse, error) { - responseStr := s.CommandRunner.RunCommand(command) - var response ResponseForSecretResponse - err := json.Unmarshal([]byte(responseStr), &response) - if err != nil { - return ResponseForSecretResponse{}, fmt.Errorf("failed to unmarshal response: %v", err) +func (s *Secrets) Delete(ids []string) (*SecretsDeleteResponse, error) { + command := Command{ + Secrets: &SecretsCommand{ + Delete: &SecretsDeleteRequest{ + IDS: ids, + }, + }, + } + + var response SecretsDeleteResponse + if err := s.executeCommand(command, &response); err != nil { + return nil, err } - return response, nil + return &response, nil } From 29a86e63841a39993454ee6c80f3e6516e6783c5 Mon Sep 17 00:00:00 2001 From: Vladimir Cvetic Date: Thu, 26 Oct 2023 10:19:42 +0200 Subject: [PATCH 20/30] Unwrap responses and return native error types --- go.work | 4 +++- languages/go/example/example.go | 10 ++++----- languages/go/project.go | 37 +++------------------------------ languages/go/secrets.go | 31 --------------------------- languages/go/util.go | 32 ++++++++++++++++++++++++++++ 5 files changed, 43 insertions(+), 71 deletions(-) create mode 100644 languages/go/util.go diff --git a/go.work b/go.work index b88c248ae..92e4a4e4e 100644 --- a/go.work +++ b/go.work @@ -1,2 +1,4 @@ go 1.20 -go work use ./go/ ./languages/go/ + +use ./languages/go +use ./languages/go/example diff --git a/languages/go/example/example.go b/languages/go/example/example.go index 201b200ef..a20e6219f 100644 --- a/languages/go/example/example.go +++ b/languages/go/example/example.go @@ -31,12 +31,12 @@ func main() { panic(err) } - responseForProjectResponse, err := bitwardenClient.Projects.Create(organizationID.String(), projectName) + projectResponse, err := bitwardenClient.Projects.Create(organizationID.String(), projectName) if err != nil { panic(err) } - fmt.Println(responseForProjectResponse) - projectID := responseForProjectResponse.Data.ID + fmt.Println(projectResponse) + projectID := projectResponse.ID fmt.Println(projectID) if _, err = bitwardenClient.Projects.List(organizationID.String()); err != nil { @@ -55,11 +55,11 @@ func main() { value := "value" note := "note" - responseForSecretResponse, err := bitwardenClient.Secrets.Create(key, value, note, organizationID.String(), []string{projectID}) + secretResponse, err := bitwardenClient.Secrets.Create(key, value, note, organizationID.String(), []string{projectID}) if err != nil { panic(err) } - secretID := responseForSecretResponse.Data.ID + secretID := secretResponse.ID if _, err = bitwardenClient.Secrets.List(organizationID.String()); err != nil { panic(err) diff --git a/languages/go/project.go b/languages/go/project.go index a3d56d0eb..514420bdd 100644 --- a/languages/go/project.go +++ b/languages/go/project.go @@ -1,48 +1,17 @@ package sdk -import ( - "encoding/json" - "fmt" -) - type ProjectsInterface interface { Create(organizationID string, name string) (*ProjectResponse, error) List(organizationID string) (*ProjectsResponse, error) Get(projectID string) (*ProjectResponse, error) Update(projectID string, organizationID string, name string) (*ProjectResponse, error) - Delete(projectIDs []string) (*ProjectsDeleteResponse, error) + Delete(projectIDs []string) (*ProjectResponse, error) } type Projects struct { CommandRunner CommandRunnerInterface } -func checkSuccessAndError(responseStr string, v interface{}) error { - var wrapper struct { - Success bool `json:"success"` - ErrorMessage *string `json:"errorMessage"` - } - - err := json.Unmarshal([]byte(responseStr), &wrapper) - if err != nil { - return fmt.Errorf("failed to unmarshal wrapper response: %v", err) - } - - if !wrapper.Success { - if wrapper.ErrorMessage != nil { - return fmt.Errorf("API error: %s", *wrapper.ErrorMessage) - } - return fmt.Errorf("API error: unknown") - } - - err = json.Unmarshal([]byte(responseStr), &v) - if err != nil { - return fmt.Errorf("failed to unmarshal response: %v", err) - } - - return nil -} - func NewProjects(commandRunner CommandRunnerInterface) *Projects { return &Projects{CommandRunner: commandRunner} } @@ -88,7 +57,7 @@ func (p *Projects) List(organizationID string) (*ProjectsResponse, error) { }, } - var response ProjectResponse + var response ProjectsResponse if err := p.executeCommand(command, &response); err != nil { return nil, err } @@ -113,7 +82,7 @@ func (p *Projects) Update(projectID, organizationID, name string) (*ProjectRespo return &response, nil } -func (p *Projects) Delete(projectIDs []string) (*ProjectsDeleteResponse, error) { +func (p *Projects) Delete(projectIDs []string) (*ProjectResponse, error) { command := Command{ Projects: &ProjectsCommand{ Delete: &ProjectsDeleteRequest{ diff --git a/languages/go/secrets.go b/languages/go/secrets.go index f2c11e750..c151377f1 100644 --- a/languages/go/secrets.go +++ b/languages/go/secrets.go @@ -1,10 +1,5 @@ package sdk -import ( - "encoding/json" - "fmt" -) - type SecretsInterface interface { Create(key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) List(organizationID string) (*SecretIdentifiersResponse, error) @@ -26,32 +21,6 @@ func (s *Secrets) executeCommand(command Command, target interface{}) error { return checkSuccessAndError(responseStr, target) } -func checkSuccessAndError(responseStr string, v interface{}) error { - var wrapper struct { - Success bool `json:"success"` - ErrorMessage *string `json:"errorMessage"` - } - - err := json.Unmarshal([]byte(responseStr), &wrapper) - if err != nil { - return fmt.Errorf("failed to unmarshal wrapper response: %v", err) - } - - if !wrapper.Success { - if wrapper.ErrorMessage != nil { - return fmt.Errorf("API error: %s", *wrapper.ErrorMessage) - } - return fmt.Errorf("API error: unknown") - } - - err = json.Unmarshal([]byte(responseStr), &v) - if err != nil { - return fmt.Errorf("failed to unmarshal response: %v", err) - } - - return nil -} - func (s *Secrets) Create(key, value, note string, organizationID string, projectIDs []string) (*SecretResponse, error) { command := Command{ Secrets: &SecretsCommand{ diff --git a/languages/go/util.go b/languages/go/util.go new file mode 100644 index 000000000..13879de5f --- /dev/null +++ b/languages/go/util.go @@ -0,0 +1,32 @@ +package sdk + +import ( + "encoding/json" + "fmt" +) + +func checkSuccessAndError(responseStr string, v interface{}) error { + var wrapper struct { + Success bool `json:"success"` + ErrorMessage *string `json:"errorMessage"` + } + + err := json.Unmarshal([]byte(responseStr), &wrapper) + if err != nil { + return fmt.Errorf("failed to unmarshal wrapper response: %v", err) + } + + if !wrapper.Success { + if wrapper.ErrorMessage != nil { + return fmt.Errorf("API error: %s", *wrapper.ErrorMessage) + } + return fmt.Errorf("API error: unknown") + } + + err = json.Unmarshal([]byte(responseStr), &v) + if err != nil { + return fmt.Errorf("failed to unmarshal response: %v", err) + } + + return nil +} From 2f5bd0203d518ddcf0b53ed15f674b7f2bb709ab Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Mon, 30 Oct 2023 21:45:09 +0100 Subject: [PATCH 21/30] address PR comments --- .github/workflows/golang-release.yml | 6 +- languages/csharp/schemas.cs | 3106 -------------------------- languages/go/README.md | 22 +- languages/go/bitwarden_client.go | 22 +- languages/go/command_runner.go | 10 +- languages/go/example/example.go | 22 +- languages/go/project.go | 5 +- languages/go/secrets.go | 5 +- support/scripts/schemas.ts | 4 +- 9 files changed, 54 insertions(+), 3148 deletions(-) delete mode 100644 languages/csharp/schemas.cs diff --git a/.github/workflows/golang-release.yml b/.github/workflows/golang-release.yml index 063d3ae42..7ffdf8381 100644 --- a/.github/workflows/golang-release.yml +++ b/.github/workflows/golang-release.yml @@ -9,7 +9,7 @@ on: env: GO111MODULE: on - GO_VERSION: '^1.18' + GO_VERSION: "^1.18" jobs: build_rust: @@ -17,7 +17,7 @@ jobs: generate-schemas: uses: ./.github/workflows/generate_schemas.yml - + build: needs: [build_rust, generate-schemas] runs-on: ubuntu-latest @@ -29,7 +29,7 @@ jobs: uses: actions/setup-go@v2 with: go-version: ${{ env.GO_VERSION }} - + - name: Cache dependencies uses: actions/cache@v2 with: diff --git a/languages/csharp/schemas.cs b/languages/csharp/schemas.cs deleted file mode 100644 index 3e3a6ad0f..000000000 --- a/languages/csharp/schemas.cs +++ /dev/null @@ -1,3106 +0,0 @@ -// -// -// To parse this JSON data, add NuGet 'System.Text.Json' then do one of these: -// -// using Bitwarden.Sdk; -// -// var clientSettings = ClientSettings.FromJson(jsonString); -// var command = Command.FromJson(jsonString); -// var docRef = DocRef.FromJson(jsonString); -// var responseForApiKeyLoginResponse = ResponseForApiKeyLoginResponse.FromJson(jsonString); -// var responseForFingerprintResponse = ResponseForFingerprintResponse.FromJson(jsonString); -// var responseForPasswordLoginResponse = ResponseForPasswordLoginResponse.FromJson(jsonString); -// var responseForProjectResponse = ResponseForProjectResponse.FromJson(jsonString); -// var responseForProjectsDeleteResponse = ResponseForProjectsDeleteResponse.FromJson(jsonString); -// var responseForProjectsResponse = ResponseForProjectsResponse.FromJson(jsonString); -// var responseForSecretIdentifiersResponse = ResponseForSecretIdentifiersResponse.FromJson(jsonString); -// var responseForSecretResponse = ResponseForSecretResponse.FromJson(jsonString); -// var responseForSecretsDeleteResponse = ResponseForSecretsDeleteResponse.FromJson(jsonString); -// var responseForSecretsResponse = ResponseForSecretsResponse.FromJson(jsonString); -// var responseForSyncResponse = ResponseForSyncResponse.FromJson(jsonString); -// var responseForUserApiKeyResponse = ResponseForUserApiKeyResponse.FromJson(jsonString); -#nullable enable -#pragma warning disable CS8618 -#pragma warning disable CS8601 -#pragma warning disable CS8603 - -namespace Bitwarden.Sdk -{ - using System; - using System.Collections.Generic; - - using System.Text.Json; - using System.Text.Json.Serialization; - using System.Globalization; - - /// - /// Basic client behavior settings. These settings specify the various targets and behavior - /// of the Bitwarden Client. They are optional and uneditable once the client is - /// initialized. - /// - /// Defaults to - /// - /// ``` # use bitwarden::client::client_settings::{ClientSettings, DeviceType}; # use - /// assert_matches::assert_matches; let settings = ClientSettings { identity_url: - /// "https://identity.bitwarden.com".to_string(), api_url: - /// "https://api.bitwarden.com".to_string(), user_agent: "Bitwarden Rust-SDK".to_string(), - /// device_type: DeviceType::SDK, }; let default = ClientSettings::default(); - /// assert_matches!(settings, default); ``` - /// - /// Targets `localhost:8080` for debug builds. - /// - public partial class ClientSettings - { - /// - /// The api url of the targeted Bitwarden instance. Defaults to `https://api.bitwarden.com` - /// - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("apiUrl")] - public string ApiUrl { get; set; } - - /// - /// Device type to send to Bitwarden. Defaults to SDK - /// - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("deviceType")] - public DeviceType? DeviceType { get; set; } - - /// - /// The identity url of the targeted Bitwarden instance. Defaults to - /// `https://identity.bitwarden.com` - /// - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("identityUrl")] - public string IdentityUrl { get; set; } - - /// - /// The user_agent to sent to Bitwarden. Defaults to `Bitwarden Rust-SDK` - /// - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("userAgent")] - public string UserAgent { get; set; } - } - - /// - /// Login with username and password - /// - /// This command is for initiating an authentication handshake with Bitwarden. Authorization - /// may fail due to requiring 2fa or captcha challenge completion despite accurate - /// credentials. - /// - /// This command is not capable of handling authentication requiring 2fa or captcha. - /// - /// Returns: [PasswordLoginResponse](bitwarden::auth::login::PasswordLoginResponse) - /// - /// Login with API Key - /// - /// This command is for initiating an authentication handshake with Bitwarden. - /// - /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) - /// - /// Login with Secrets Manager Access Token - /// - /// This command is for initiating an authentication handshake with Bitwarden. - /// - /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) - /// - /// > Requires Authentication Get the API key of the currently authenticated user - /// - /// Returns: [UserApiKeyResponse](bitwarden::platform::UserApiKeyResponse) - /// - /// Get the user's passphrase - /// - /// Returns: String - /// - /// > Requires Authentication Retrieve all user data, ciphers and organizations the user is a - /// part of - /// - /// Returns: [SyncResponse](bitwarden::platform::SyncResponse) - /// - public partial class Command - { - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("passwordLogin")] - public PasswordLoginRequest PasswordLogin { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("apiKeyLogin")] - public ApiKeyLoginRequest ApiKeyLogin { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("accessTokenLogin")] - public AccessTokenLoginRequest AccessTokenLogin { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("getUserApiKey")] - public SecretVerificationRequest GetUserApiKey { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("fingerprint")] - public FingerprintRequest Fingerprint { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("sync")] - public SyncRequest Sync { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("secrets")] - public SecretsCommand Secrets { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("projects")] - public ProjectsCommand Projects { get; set; } - } - - /// - /// Login to Bitwarden with access token - /// - public partial class AccessTokenLoginRequest - { - /// - /// Bitwarden service API access token - /// - [JsonPropertyName("accessToken")] - public string AccessToken { get; set; } - } - - /// - /// Login to Bitwarden with Api Key - /// - public partial class ApiKeyLoginRequest - { - /// - /// Bitwarden account client_id - /// - [JsonPropertyName("clientId")] - public string ClientId { get; set; } - - /// - /// Bitwarden account client_secret - /// - [JsonPropertyName("clientSecret")] - public string ClientSecret { get; set; } - - /// - /// Bitwarden account master password - /// - [JsonPropertyName("password")] - public string Password { get; set; } - } - - public partial class FingerprintRequest - { - /// - /// The input material, used in the fingerprint generation process. - /// - [JsonPropertyName("fingerprintMaterial")] - public string FingerprintMaterial { get; set; } - - /// - /// The user's public key encoded with base64. - /// - [JsonPropertyName("publicKey")] - public string PublicKey { get; set; } - } - - public partial class SecretVerificationRequest - { - /// - /// The user's master password to use for user verification. If supplied, this will be used - /// for verification purposes. - /// - [JsonPropertyName("masterPassword")] - public string MasterPassword { get; set; } - - /// - /// Alternate user verification method through OTP. This is provided for users who have no - /// master password due to use of Customer Managed Encryption. Must be present and valid if - /// master_password is absent. - /// - [JsonPropertyName("otp")] - public string Otp { get; set; } - } - - /// - /// Login to Bitwarden with Username and Password - /// - public partial class PasswordLoginRequest - { - /// - /// Bitwarden account email address - /// - [JsonPropertyName("email")] - public string Email { get; set; } - - /// - /// Bitwarden account master password - /// - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("twoFactor")] - public TwoFactorRequest TwoFactor { get; set; } - } - - public partial class TwoFactorRequest - { - /// - /// Two-factor provider - /// - [JsonPropertyName("provider")] - public TwoFactorProvider Provider { get; set; } - - /// - /// Two-factor remember - /// - [JsonPropertyName("remember")] - public bool Remember { get; set; } - - /// - /// Two-factor Token - /// - [JsonPropertyName("token")] - public string Token { get; set; } - } - - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Retrieve a project by the provided identifier - /// - /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Creates a new project in the provided organization using the given data - /// - /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Lists all projects of the given organization - /// - /// Returns: [ProjectsResponse](bitwarden::secrets_manager::projects::ProjectsResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Updates an existing project with the provided ID using the given data - /// - /// Returns: [ProjectResponse](bitwarden::secrets_manager::projects::ProjectResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Deletes all the projects whose IDs match the provided ones - /// - /// Returns: - /// [ProjectsDeleteResponse](bitwarden::secrets_manager::projects::ProjectsDeleteResponse) - /// - public partial class ProjectsCommand - { - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("get")] - public ProjectGetRequest Get { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("create")] - public ProjectCreateRequest Create { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("list")] - public ProjectsListRequest List { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("update")] - public ProjectPutRequest Update { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("delete")] - public ProjectsDeleteRequest Delete { get; set; } - } - - public partial class ProjectCreateRequest - { - [JsonPropertyName("name")] - public string Name { get; set; } - - /// - /// Organization where the project will be created - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - } - - public partial class ProjectsDeleteRequest - { - /// - /// IDs of the projects to delete - /// - [JsonPropertyName("ids")] - public Guid[] Ids { get; set; } - } - - public partial class ProjectGetRequest - { - /// - /// ID of the project to retrieve - /// - [JsonPropertyName("id")] - public Guid Id { get; set; } - } - - public partial class ProjectsListRequest - { - /// - /// Organization to retrieve all the projects from - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - } - - public partial class ProjectPutRequest - { - /// - /// ID of the project to modify - /// - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - /// - /// Organization ID of the project to modify - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - } - - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Retrieve a secret by the provided identifier - /// - /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Retrieve secrets by the provided identifiers - /// - /// Returns: [SecretsResponse](bitwarden::secrets_manager::secrets::SecretsResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Creates a new secret in the provided organization using the given data - /// - /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Lists all secret identifiers of the given organization, to then retrieve each - /// secret, use `CreateSecret` - /// - /// Returns: - /// [SecretIdentifiersResponse](bitwarden::secrets_manager::secrets::SecretIdentifiersResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Updates an existing secret with the provided ID using the given data - /// - /// Returns: [SecretResponse](bitwarden::secrets_manager::secrets::SecretResponse) - /// - /// > Requires Authentication > Requires using an Access Token for login or calling Sync at - /// least once Deletes all the secrets whose IDs match the provided ones - /// - /// Returns: - /// [SecretsDeleteResponse](bitwarden::secrets_manager::secrets::SecretsDeleteResponse) - /// - public partial class SecretsCommand - { - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("get")] - public SecretGetRequest Get { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("getByIds")] - public SecretsGetRequest GetByIds { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("create")] - public SecretCreateRequest Create { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("list")] - public SecretIdentifiersRequest List { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("update")] - public SecretPutRequest Update { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("delete")] - public SecretsDeleteRequest Delete { get; set; } - } - - public partial class SecretCreateRequest - { - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("note")] - public string Note { get; set; } - - /// - /// Organization where the secret will be created - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - /// - /// IDs of the projects that this secret will belong to - /// - [JsonPropertyName("projectIds")] - public Guid[] ProjectIds { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class SecretsDeleteRequest - { - /// - /// IDs of the secrets to delete - /// - [JsonPropertyName("ids")] - public Guid[] Ids { get; set; } - } - - public partial class SecretGetRequest - { - /// - /// ID of the secret to retrieve - /// - [JsonPropertyName("id")] - public Guid Id { get; set; } - } - - public partial class SecretsGetRequest - { - /// - /// IDs of the secrets to retrieve - /// - [JsonPropertyName("ids")] - public Guid[] Ids { get; set; } - } - - public partial class SecretIdentifiersRequest - { - /// - /// Organization to retrieve all the secrets from - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - } - - public partial class SecretPutRequest - { - /// - /// ID of the secret to modify - /// - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("note")] - public string Note { get; set; } - - /// - /// Organization ID of the secret to modify - /// - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("projectIds")] - public Guid[] ProjectIds { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class SyncRequest - { - /// - /// Exclude the subdomains from the response, defaults to false - /// - [JsonPropertyName("excludeSubdomains")] - public bool? ExcludeSubdomains { get; set; } - } - - public partial class DocRef - { - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("Cipher")] - public Cipher Cipher { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("CipherView")] - public CipherView CipherView { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("Collection")] - public Collection Collection { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("Folder")] - public Folder Folder { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("FolderView")] - public FolderView FolderView { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("Send")] - public Send Send { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("SendView")] - public SendView SendView { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("SendListView")] - public SendListView SendListView { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("InitCryptoRequest")] - public InitCryptoRequest InitCryptoRequest { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("PasswordGeneratorRequest")] - public PasswordGeneratorRequest PasswordGeneratorRequest { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("PassphraseGeneratorRequest")] - public PassphraseGeneratorRequest PassphraseGeneratorRequest { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("ExportFormat")] - public ExportFormat? ExportFormat { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("MasterPasswordPolicyOptions")] - public MasterPasswordPolicyOptions MasterPasswordPolicyOptions { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("Kdf")] - public Kdf Kdf { get; set; } - } - - public partial class Cipher - { - [JsonPropertyName("attachments")] - public Attachment[] Attachments { get; set; } - - [JsonPropertyName("card")] - public Card Card { get; set; } - - [JsonPropertyName("collectionIds")] - public Guid[] CollectionIds { get; set; } - - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("deletedDate")] - public DateTimeOffset? DeletedDate { get; set; } - - [JsonPropertyName("edit")] - public bool Edit { get; set; } - - [JsonPropertyName("favorite")] - public bool Favorite { get; set; } - - [JsonPropertyName("fields")] - public Field[] Fields { get; set; } - - [JsonPropertyName("folderId")] - public Guid? FolderId { get; set; } - - [JsonPropertyName("id")] - public Guid? Id { get; set; } - - [JsonPropertyName("identity")] - public Identity Identity { get; set; } - - [JsonPropertyName("localData")] - public LocalData LocalData { get; set; } - - [JsonPropertyName("login")] - public Login Login { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("notes")] - public string Notes { get; set; } - - [JsonPropertyName("organizationId")] - public Guid? OrganizationId { get; set; } - - [JsonPropertyName("organizationUseTotp")] - public bool OrganizationUseTotp { get; set; } - - [JsonPropertyName("passwordHistory")] - public PasswordHistory[] PasswordHistory { get; set; } - - [JsonPropertyName("reprompt")] - public CipherRepromptType Reprompt { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("secureNote")] - public SecureNote SecureNote { get; set; } - - [JsonPropertyName("type")] - public CipherType Type { get; set; } - - [JsonPropertyName("viewPassword")] - public bool ViewPassword { get; set; } - } - - public partial class Attachment - { - [JsonPropertyName("fileName")] - public string FileName { get; set; } - - [JsonPropertyName("id")] - public string Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("size")] - public string Size { get; set; } - - /// - /// Readable size, ex: "4.2 KB" or "1.43 GB" - /// - [JsonPropertyName("sizeName")] - public string SizeName { get; set; } - - [JsonPropertyName("url")] - public string Url { get; set; } - } - - public partial class Card - { - [JsonPropertyName("brand")] - public string Brand { get; set; } - - [JsonPropertyName("cardholderName")] - public string CardholderName { get; set; } - - [JsonPropertyName("code")] - public string Code { get; set; } - - [JsonPropertyName("expMonth")] - public string ExpMonth { get; set; } - - [JsonPropertyName("expYear")] - public string ExpYear { get; set; } - - [JsonPropertyName("number")] - public string Number { get; set; } - } - - public partial class Field - { - [JsonPropertyName("linkedId")] - public LinkedIdType? LinkedId { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("type")] - public FieldType Type { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class Identity - { - [JsonPropertyName("address1")] - public string Address1 { get; set; } - - [JsonPropertyName("address2")] - public string Address2 { get; set; } - - [JsonPropertyName("address3")] - public string Address3 { get; set; } - - [JsonPropertyName("city")] - public string City { get; set; } - - [JsonPropertyName("company")] - public string Company { get; set; } - - [JsonPropertyName("country")] - public string Country { get; set; } - - [JsonPropertyName("email")] - public string Email { get; set; } - - [JsonPropertyName("firstName")] - public string FirstName { get; set; } - - [JsonPropertyName("lastName")] - public string LastName { get; set; } - - [JsonPropertyName("licenseNumber")] - public string LicenseNumber { get; set; } - - [JsonPropertyName("middleName")] - public string MiddleName { get; set; } - - [JsonPropertyName("passportNumber")] - public string PassportNumber { get; set; } - - [JsonPropertyName("phone")] - public string Phone { get; set; } - - [JsonPropertyName("postalCode")] - public string PostalCode { get; set; } - - [JsonPropertyName("ssn")] - public string Ssn { get; set; } - - [JsonPropertyName("state")] - public string State { get; set; } - - [JsonPropertyName("title")] - public string Title { get; set; } - - [JsonPropertyName("username")] - public string Username { get; set; } - } - - public partial class LocalData - { - [JsonPropertyName("lastLaunched")] - public long? LastLaunched { get; set; } - - [JsonPropertyName("lastUsedDate")] - public long? LastUsedDate { get; set; } - } - - public partial class Login - { - [JsonPropertyName("autofillOnPageLoad")] - public bool? AutofillOnPageLoad { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("passwordRevisionDate")] - public DateTimeOffset? PasswordRevisionDate { get; set; } - - [JsonPropertyName("totp")] - public string Totp { get; set; } - - [JsonPropertyName("uris")] - public LoginUri[] Uris { get; set; } - - [JsonPropertyName("username")] - public string Username { get; set; } - } - - public partial class LoginUri - { - [JsonPropertyName("match")] - public UriMatchType? Match { get; set; } - - [JsonPropertyName("uri")] - public string Uri { get; set; } - } - - public partial class PasswordHistory - { - [JsonPropertyName("lastUsedDate")] - public DateTimeOffset LastUsedDate { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - } - - public partial class SecureNote - { - [JsonPropertyName("type")] - public SecureNoteType Type { get; set; } - } - - public partial class CipherView - { - [JsonPropertyName("attachments")] - public AttachmentView[] Attachments { get; set; } - - [JsonPropertyName("card")] - public CardView Card { get; set; } - - [JsonPropertyName("collectionIds")] - public Guid[] CollectionIds { get; set; } - - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("deletedDate")] - public DateTimeOffset? DeletedDate { get; set; } - - [JsonPropertyName("edit")] - public bool Edit { get; set; } - - [JsonPropertyName("favorite")] - public bool Favorite { get; set; } - - [JsonPropertyName("fields")] - public FieldView[] Fields { get; set; } - - [JsonPropertyName("folderId")] - public Guid? FolderId { get; set; } - - [JsonPropertyName("id")] - public Guid? Id { get; set; } - - [JsonPropertyName("identity")] - public IdentityView Identity { get; set; } - - [JsonPropertyName("localData")] - public LocalDataView LocalData { get; set; } - - [JsonPropertyName("login")] - public LoginView Login { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("notes")] - public string Notes { get; set; } - - [JsonPropertyName("organizationId")] - public Guid? OrganizationId { get; set; } - - [JsonPropertyName("organizationUseTotp")] - public bool OrganizationUseTotp { get; set; } - - [JsonPropertyName("passwordHistory")] - public PasswordHistoryView[] PasswordHistory { get; set; } - - [JsonPropertyName("reprompt")] - public CipherRepromptType Reprompt { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("secureNote")] - public SecureNoteView SecureNote { get; set; } - - [JsonPropertyName("type")] - public CipherType Type { get; set; } - - [JsonPropertyName("viewPassword")] - public bool ViewPassword { get; set; } - } - - public partial class AttachmentView - { - [JsonPropertyName("fileName")] - public string FileName { get; set; } - - [JsonPropertyName("id")] - public string Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("size")] - public string Size { get; set; } - - [JsonPropertyName("sizeName")] - public string SizeName { get; set; } - - [JsonPropertyName("url")] - public string Url { get; set; } - } - - public partial class CardView - { - [JsonPropertyName("brand")] - public string Brand { get; set; } - - [JsonPropertyName("cardholderName")] - public string CardholderName { get; set; } - - [JsonPropertyName("code")] - public string Code { get; set; } - - [JsonPropertyName("expMonth")] - public string ExpMonth { get; set; } - - [JsonPropertyName("expYear")] - public string ExpYear { get; set; } - - [JsonPropertyName("number")] - public string Number { get; set; } - } - - public partial class FieldView - { - [JsonPropertyName("linkedId")] - public LinkedIdType? LinkedId { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("type")] - public FieldType Type { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class IdentityView - { - [JsonPropertyName("address1")] - public string Address1 { get; set; } - - [JsonPropertyName("address2")] - public string Address2 { get; set; } - - [JsonPropertyName("address3")] - public string Address3 { get; set; } - - [JsonPropertyName("city")] - public string City { get; set; } - - [JsonPropertyName("company")] - public string Company { get; set; } - - [JsonPropertyName("country")] - public string Country { get; set; } - - [JsonPropertyName("email")] - public string Email { get; set; } - - [JsonPropertyName("firstName")] - public string FirstName { get; set; } - - [JsonPropertyName("lastName")] - public string LastName { get; set; } - - [JsonPropertyName("licenseNumber")] - public string LicenseNumber { get; set; } - - [JsonPropertyName("middleName")] - public string MiddleName { get; set; } - - [JsonPropertyName("passportNumber")] - public string PassportNumber { get; set; } - - [JsonPropertyName("phone")] - public string Phone { get; set; } - - [JsonPropertyName("postalCode")] - public string PostalCode { get; set; } - - [JsonPropertyName("ssn")] - public string Ssn { get; set; } - - [JsonPropertyName("state")] - public string State { get; set; } - - [JsonPropertyName("title")] - public string Title { get; set; } - - [JsonPropertyName("username")] - public string Username { get; set; } - } - - public partial class LocalDataView - { - [JsonPropertyName("lastLaunched")] - public long? LastLaunched { get; set; } - - [JsonPropertyName("lastUsedDate")] - public long? LastUsedDate { get; set; } - } - - public partial class LoginView - { - [JsonPropertyName("autofillOnPageLoad")] - public bool? AutofillOnPageLoad { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("passwordRevisionDate")] - public DateTimeOffset? PasswordRevisionDate { get; set; } - - [JsonPropertyName("totp")] - public string Totp { get; set; } - - [JsonPropertyName("uris")] - public LoginUriView[] Uris { get; set; } - - [JsonPropertyName("username")] - public string Username { get; set; } - } - - public partial class LoginUriView - { - [JsonPropertyName("match")] - public UriMatchType? Match { get; set; } - - [JsonPropertyName("uri")] - public string Uri { get; set; } - } - - public partial class PasswordHistoryView - { - [JsonPropertyName("lastUsedDate")] - public DateTimeOffset LastUsedDate { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - } - - public partial class SecureNoteView - { - [JsonPropertyName("type")] - public SecureNoteType Type { get; set; } - } - - public partial class Collection - { - [JsonPropertyName("externalId")] - public string ExternalId { get; set; } - - [JsonPropertyName("hidePasswords")] - public bool HidePasswords { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("readOnly")] - public bool ReadOnly { get; set; } - } - - public partial class ExportFormatClass - { - [JsonPropertyName("EncryptedJson")] - public EncryptedJson EncryptedJson { get; set; } - } - - public partial class EncryptedJson - { - [JsonPropertyName("password")] - public string Password { get; set; } - } - - public partial class Folder - { - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - } - - public partial class FolderView - { - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - } - - public partial class InitCryptoRequest - { - /// - /// The user's email address - /// - [JsonPropertyName("email")] - public string Email { get; set; } - - /// - /// The user's KDF parameters, as received from the prelogin request - /// - [JsonPropertyName("kdfParams")] - public Kdf KdfParams { get; set; } - - /// - /// The encryption keys for all the organizations the user is a part of - /// - [JsonPropertyName("organizationKeys")] - public Dictionary OrganizationKeys { get; set; } - - /// - /// The user's master password - /// - [JsonPropertyName("password")] - public string Password { get; set; } - - /// - /// The user's encryptred private key - /// - [JsonPropertyName("privateKey")] - public string PrivateKey { get; set; } - - /// - /// The user's encrypted symmetric crypto key - /// - [JsonPropertyName("userKey")] - public string UserKey { get; set; } - } - - /// - /// The user's KDF parameters, as received from the prelogin request - /// - public partial class Kdf - { - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("pBKDF2")] - public PBkdf2 PBkdf2 { get; set; } - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("argon2id")] - public Argon2Id Argon2Id { get; set; } - } - - public partial class Argon2Id - { - [JsonPropertyName("iterations")] - public long Iterations { get; set; } - - [JsonPropertyName("memory")] - public long Memory { get; set; } - - [JsonPropertyName("parallelism")] - public long Parallelism { get; set; } - } - - public partial class PBkdf2 - { - [JsonPropertyName("iterations")] - public long Iterations { get; set; } - } - - public partial class MasterPasswordPolicyOptions - { - /// - /// Flag to indicate if the policy should be enforced on login. If true, and the user's - /// password does not meet the policy requirements, the user will be forced to update their - /// password. - /// - [JsonPropertyName("enforce_on_login")] - public bool EnforceOnLogin { get; set; } - - [JsonPropertyName("min_complexity")] - public long MinComplexity { get; set; } - - [JsonPropertyName("min_length")] - public long MinLength { get; set; } - - [JsonPropertyName("require_lower")] - public bool RequireLower { get; set; } - - [JsonPropertyName("require_numbers")] - public bool RequireNumbers { get; set; } - - [JsonPropertyName("require_special")] - public bool RequireSpecial { get; set; } - - [JsonPropertyName("require_upper")] - public bool RequireUpper { get; set; } - } - - /// - /// Passphrase generator request. - /// - /// The default separator is `-` and default number of words is 3. - /// - public partial class PassphraseGeneratorRequest - { - [JsonPropertyName("capitalize")] - public bool? Capitalize { get; set; } - - [JsonPropertyName("includeNumber")] - public bool? IncludeNumber { get; set; } - - [JsonPropertyName("numWords")] - public long? NumWords { get; set; } - - [JsonPropertyName("wordSeparator")] - public string WordSeparator { get; set; } - } - - /// - /// Password generator request. If all options are false, the default is to generate a - /// password with: - lowercase - uppercase - numbers - /// - /// The default length is 16. - /// - public partial class PasswordGeneratorRequest - { - [JsonPropertyName("avoidAmbiguous")] - public bool? AvoidAmbiguous { get; set; } - - [JsonPropertyName("length")] - public long? Length { get; set; } - - [JsonPropertyName("lowercase")] - public bool Lowercase { get; set; } - - [JsonPropertyName("minLowercase")] - public bool? MinLowercase { get; set; } - - [JsonPropertyName("minNumber")] - public bool? MinNumber { get; set; } - - [JsonPropertyName("minSpecial")] - public bool? MinSpecial { get; set; } - - [JsonPropertyName("minUppercase")] - public bool? MinUppercase { get; set; } - - [JsonPropertyName("numbers")] - public bool Numbers { get; set; } - - [JsonPropertyName("special")] - public bool Special { get; set; } - - [JsonPropertyName("uppercase")] - public bool Uppercase { get; set; } - } - - public partial class Send - { - [JsonPropertyName("accessCount")] - public long AccessCount { get; set; } - - [JsonPropertyName("accessId")] - public string AccessId { get; set; } - - [JsonPropertyName("deletionDate")] - public DateTimeOffset DeletionDate { get; set; } - - [JsonPropertyName("disabled")] - public bool Disabled { get; set; } - - [JsonPropertyName("expirationDate")] - public DateTimeOffset? ExpirationDate { get; set; } - - [JsonPropertyName("file")] - public SendFile File { get; set; } - - [JsonPropertyName("hideEmail")] - public bool HideEmail { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("maxAccessCount")] - public long? MaxAccessCount { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("notes")] - public string Notes { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("text")] - public SendText Text { get; set; } - - [JsonPropertyName("type")] - public SendType Type { get; set; } - } - - public partial class SendFile - { - [JsonPropertyName("fileName")] - public string FileName { get; set; } - - [JsonPropertyName("id")] - public string Id { get; set; } - - [JsonPropertyName("size")] - public string Size { get; set; } - - /// - /// Readable size, ex: "4.2 KB" or "1.43 GB" - /// - [JsonPropertyName("sizeName")] - public string SizeName { get; set; } - } - - public partial class SendText - { - [JsonPropertyName("hidden")] - public bool Hidden { get; set; } - - [JsonPropertyName("text")] - public string Text { get; set; } - } - - public partial class SendListView - { - [JsonPropertyName("accessId")] - public string AccessId { get; set; } - - [JsonPropertyName("deletionDate")] - public DateTimeOffset DeletionDate { get; set; } - - [JsonPropertyName("disabled")] - public bool Disabled { get; set; } - - [JsonPropertyName("expirationDate")] - public DateTimeOffset? ExpirationDate { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("type")] - public SendType Type { get; set; } - } - - public partial class SendView - { - [JsonPropertyName("accessCount")] - public long AccessCount { get; set; } - - [JsonPropertyName("accessId")] - public string AccessId { get; set; } - - [JsonPropertyName("deletionDate")] - public DateTimeOffset DeletionDate { get; set; } - - [JsonPropertyName("disabled")] - public bool Disabled { get; set; } - - [JsonPropertyName("expirationDate")] - public DateTimeOffset? ExpirationDate { get; set; } - - [JsonPropertyName("file")] - public SendFileView File { get; set; } - - [JsonPropertyName("hideEmail")] - public bool HideEmail { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("maxAccessCount")] - public long? MaxAccessCount { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("notes")] - public string Notes { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("text")] - public SendTextView Text { get; set; } - - [JsonPropertyName("type")] - public SendType Type { get; set; } - } - - public partial class SendFileView - { - [JsonPropertyName("fileName")] - public string FileName { get; set; } - - [JsonPropertyName("id")] - public string Id { get; set; } - - [JsonPropertyName("size")] - public string Size { get; set; } - - /// - /// Readable size, ex: "4.2 KB" or "1.43 GB" - /// - [JsonPropertyName("sizeName")] - public string SizeName { get; set; } - } - - public partial class SendTextView - { - [JsonPropertyName("hidden")] - public bool Hidden { get; set; } - - [JsonPropertyName("text")] - public string Text { get; set; } - } - - public partial class ResponseForApiKeyLoginResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public ApiKeyLoginResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class ApiKeyLoginResponse - { - [JsonPropertyName("authenticated")] - public bool Authenticated { get; set; } - - /// - /// Whether or not the user is required to update their master password - /// - [JsonPropertyName("forcePasswordReset")] - public bool ForcePasswordReset { get; set; } - - /// - /// TODO: What does this do? - /// - [JsonPropertyName("resetMasterPassword")] - public bool ResetMasterPassword { get; set; } - - [JsonPropertyName("twoFactor")] - public ApiKeyLoginResponseTwoFactorProviders TwoFactor { get; set; } - } - - public partial class ApiKeyLoginResponseTwoFactorProviders - { - [JsonPropertyName("authenticator")] - public PurpleAuthenticator Authenticator { get; set; } - - /// - /// Duo-backed 2fa - /// - [JsonPropertyName("duo")] - public PurpleDuo Duo { get; set; } - - /// - /// Email 2fa - /// - [JsonPropertyName("email")] - public PurpleEmail Email { get; set; } - - /// - /// Duo-backed 2fa operated by an organization the user is a member of - /// - [JsonPropertyName("organizationDuo")] - public PurpleDuo OrganizationDuo { get; set; } - - /// - /// Presence indicates the user has stored this device as bypassing 2fa - /// - [JsonPropertyName("remember")] - public PurpleRemember Remember { get; set; } - - /// - /// WebAuthn-backed 2fa - /// - [JsonPropertyName("webAuthn")] - public PurpleWebAuthn WebAuthn { get; set; } - - /// - /// Yubikey-backed 2fa - /// - [JsonPropertyName("yubiKey")] - public PurpleYubiKey YubiKey { get; set; } - } - - public partial class PurpleAuthenticator - { - } - - public partial class PurpleDuo - { - [JsonPropertyName("host")] - public string Host { get; set; } - - [JsonPropertyName("signature")] - public string Signature { get; set; } - } - - public partial class PurpleEmail - { - /// - /// The email to request a 2fa TOTP for - /// - [JsonPropertyName("email")] - public string Email { get; set; } - } - - public partial class PurpleRemember - { - } - - public partial class PurpleWebAuthn - { - } - - public partial class PurpleYubiKey - { - /// - /// Whether the stored yubikey supports near field communication - /// - [JsonPropertyName("nfc")] - public bool Nfc { get; set; } - } - - public partial class ResponseForFingerprintResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public FingerprintResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class FingerprintResponse - { - [JsonPropertyName("fingerprint")] - public string Fingerprint { get; set; } - } - - public partial class ResponseForPasswordLoginResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public PasswordLoginResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class PasswordLoginResponse - { - [JsonPropertyName("authenticated")] - public bool Authenticated { get; set; } - - /// - /// The information required to present the user with a captcha challenge. Only present when - /// authentication fails due to requiring validation of a captcha challenge. - /// - [JsonPropertyName("captcha")] - public CaptchaResponse Captcha { get; set; } - - /// - /// Whether or not the user is required to update their master password - /// - [JsonPropertyName("forcePasswordReset")] - public bool ForcePasswordReset { get; set; } - - /// - /// TODO: What does this do? - /// - [JsonPropertyName("resetMasterPassword")] - public bool ResetMasterPassword { get; set; } - - /// - /// The available two factor authentication options. Present only when authentication fails - /// due to requiring a second authentication factor. - /// - [JsonPropertyName("twoFactor")] - public PasswordLoginResponseTwoFactorProviders TwoFactor { get; set; } - } - - public partial class CaptchaResponse - { - /// - /// hcaptcha site key - /// - [JsonPropertyName("siteKey")] - public string SiteKey { get; set; } - } - - public partial class PasswordLoginResponseTwoFactorProviders - { - [JsonPropertyName("authenticator")] - public FluffyAuthenticator Authenticator { get; set; } - - /// - /// Duo-backed 2fa - /// - [JsonPropertyName("duo")] - public FluffyDuo Duo { get; set; } - - /// - /// Email 2fa - /// - [JsonPropertyName("email")] - public FluffyEmail Email { get; set; } - - /// - /// Duo-backed 2fa operated by an organization the user is a member of - /// - [JsonPropertyName("organizationDuo")] - public FluffyDuo OrganizationDuo { get; set; } - - /// - /// Presence indicates the user has stored this device as bypassing 2fa - /// - [JsonPropertyName("remember")] - public FluffyRemember Remember { get; set; } - - /// - /// WebAuthn-backed 2fa - /// - [JsonPropertyName("webAuthn")] - public FluffyWebAuthn WebAuthn { get; set; } - - /// - /// Yubikey-backed 2fa - /// - [JsonPropertyName("yubiKey")] - public FluffyYubiKey YubiKey { get; set; } - } - - public partial class FluffyAuthenticator - { - } - - public partial class FluffyDuo - { - [JsonPropertyName("host")] - public string Host { get; set; } - - [JsonPropertyName("signature")] - public string Signature { get; set; } - } - - public partial class FluffyEmail - { - /// - /// The email to request a 2fa TOTP for - /// - [JsonPropertyName("email")] - public string Email { get; set; } - } - - public partial class FluffyRemember - { - } - - public partial class FluffyWebAuthn - { - } - - public partial class FluffyYubiKey - { - /// - /// Whether the stored yubikey supports near field communication - /// - [JsonPropertyName("nfc")] - public bool Nfc { get; set; } - } - - public partial class ResponseForProjectResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public ProjectResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class ProjectResponse - { - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - } - - public partial class ResponseForProjectsDeleteResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public ProjectsDeleteResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class ProjectsDeleteResponse - { - [JsonPropertyName("data")] - public ProjectDeleteResponse[] Data { get; set; } - } - - public partial class ProjectDeleteResponse - { - [JsonPropertyName("error")] - public string Error { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - } - - public partial class ResponseForProjectsResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public ProjectsResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class ProjectsResponse - { - [JsonPropertyName("data")] - public DatumElement[] Data { get; set; } - } - - public partial class DatumElement - { - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - } - - public partial class ResponseForSecretIdentifiersResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public SecretIdentifiersResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class SecretIdentifiersResponse - { - [JsonPropertyName("data")] - public SecretIdentifierResponse[] Data { get; set; } - } - - public partial class SecretIdentifierResponse - { - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - } - - public partial class ResponseForSecretResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public SecretResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class SecretResponse - { - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("note")] - public string Note { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("projectId")] - public Guid? ProjectId { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class ResponseForSecretsDeleteResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public SecretsDeleteResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class SecretsDeleteResponse - { - [JsonPropertyName("data")] - public SecretDeleteResponse[] Data { get; set; } - } - - public partial class SecretDeleteResponse - { - [JsonPropertyName("error")] - public string Error { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - } - - public partial class ResponseForSecretsResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public SecretsResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class SecretsResponse - { - [JsonPropertyName("data")] - public DatumClass[] Data { get; set; } - } - - public partial class DatumClass - { - [JsonPropertyName("creationDate")] - public DateTimeOffset CreationDate { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("note")] - public string Note { get; set; } - - [JsonPropertyName("organizationId")] - public Guid OrganizationId { get; set; } - - [JsonPropertyName("projectId")] - public Guid? ProjectId { get; set; } - - [JsonPropertyName("revisionDate")] - public DateTimeOffset RevisionDate { get; set; } - - [JsonPropertyName("value")] - public string Value { get; set; } - } - - public partial class ResponseForSyncResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public SyncResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class SyncResponse - { - /// - /// List of ciphers accesible by the user - /// - [JsonPropertyName("ciphers")] - public CipherDetailsResponse[] Ciphers { get; set; } - - /// - /// Data about the user, including their encryption keys and the organizations they are a - /// part of - /// - [JsonPropertyName("profile")] - public ProfileResponse Profile { get; set; } - } - - public partial class CipherDetailsResponse - { - } - - /// - /// Data about the user, including their encryption keys and the organizations they are a - /// part of - /// - public partial class ProfileResponse - { - [JsonPropertyName("email")] - public string Email { get; set; } - - [JsonPropertyName("id")] - public Guid Id { get; set; } - - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("organizations")] - public ProfileOrganizationResponse[] Organizations { get; set; } - } - - public partial class ProfileOrganizationResponse - { - [JsonPropertyName("id")] - public Guid Id { get; set; } - } - - public partial class ResponseForUserApiKeyResponse - { - /// - /// The response data. Populated if `success` is true. - /// - [JsonPropertyName("data")] - public UserApiKeyResponse Data { get; set; } - - /// - /// A message for any error that may occur. Populated if `success` is false. - /// - [JsonPropertyName("errorMessage")] - public string ErrorMessage { get; set; } - - /// - /// Whether or not the SDK request succeeded. - /// - [JsonPropertyName("success")] - public bool Success { get; set; } - } - - public partial class UserApiKeyResponse - { - /// - /// The user's API key, which represents the client_secret portion of an oauth request. - /// - [JsonPropertyName("apiKey")] - public string ApiKey { get; set; } - } - - /// - /// Device type to send to Bitwarden. Defaults to SDK - /// - public enum DeviceType { Android, AndroidAmazon, ChromeBrowser, ChromeExtension, EdgeBrowser, EdgeExtension, FirefoxBrowser, FirefoxExtension, IOs, IeBrowser, LinuxDesktop, MacOsDesktop, OperaBrowser, OperaExtension, SafariBrowser, SafariExtension, Sdk, UnknownBrowser, Uwp, VivaldiBrowser, VivaldiExtension, WindowsDesktop }; - - /// - /// Two-factor provider - /// - public enum TwoFactorProvider { Authenticator, Duo, Email, OrganizationDuo, Remember, U2F, WebAuthn, Yubikey }; - - public enum LinkedIdType { Address1, Address2, Address3, Brand, CardholderName, City, Code, Company, Country, Email, ExpMonth, ExpYear, FirstName, FullName, LastName, LicenseNumber, MiddleName, Number, PassportNumber, Password, Phone, PostalCode, Ssn, State, Title, Username }; - - public enum FieldType { Boolean, Hidden, Linked, Text }; - - public enum UriMatchType { Domain, Exact, Host, Never, RegularExpression, StartsWith }; - - public enum CipherRepromptType { None, Password }; - - public enum SecureNoteType { Generic }; - - public enum CipherType { Card, Identity, Login, SecureNote }; - - public enum ExportFormatEnum { AccountEncryptedJson, Csv, Json }; - - public enum SendType { File, Text }; - - public partial struct ExportFormat - { - public ExportFormatEnum? Enum; - public ExportFormatClass ExportFormatClass; - - public static implicit operator ExportFormat(ExportFormatEnum Enum) => new ExportFormat { Enum = Enum }; - public static implicit operator ExportFormat(ExportFormatClass ExportFormatClass) => new ExportFormat { ExportFormatClass = ExportFormatClass }; - } - - public partial class ClientSettings - { - public static ClientSettings FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class Command - { - public static Command FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class DocRef - { - public static DocRef FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForApiKeyLoginResponse - { - public static ResponseForApiKeyLoginResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForFingerprintResponse - { - public static ResponseForFingerprintResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForPasswordLoginResponse - { - public static ResponseForPasswordLoginResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForProjectResponse - { - public static ResponseForProjectResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForProjectsDeleteResponse - { - public static ResponseForProjectsDeleteResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForProjectsResponse - { - public static ResponseForProjectsResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForSecretIdentifiersResponse - { - public static ResponseForSecretIdentifiersResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForSecretResponse - { - public static ResponseForSecretResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForSecretsDeleteResponse - { - public static ResponseForSecretsDeleteResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForSecretsResponse - { - public static ResponseForSecretsResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForSyncResponse - { - public static ResponseForSyncResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public partial class ResponseForUserApiKeyResponse - { - public static ResponseForUserApiKeyResponse FromJson(string json) => JsonSerializer.Deserialize(json, Bitwarden.Sdk.Converter.Settings); - } - - public static class Serialize - { - public static string ToJson(this ClientSettings self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this Command self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this DocRef self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForApiKeyLoginResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForFingerprintResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForPasswordLoginResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForProjectResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForProjectsDeleteResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForProjectsResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForSecretIdentifiersResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForSecretResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForSecretsDeleteResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForSecretsResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForSyncResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - public static string ToJson(this ResponseForUserApiKeyResponse self) => JsonSerializer.Serialize(self, Bitwarden.Sdk.Converter.Settings); - } - - internal static class Converter - { - public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) - { - Converters = - { - DeviceTypeConverter.Singleton, - TwoFactorProviderConverter.Singleton, - LinkedIdTypeConverter.Singleton, - FieldTypeConverter.Singleton, - UriMatchTypeConverter.Singleton, - CipherRepromptTypeConverter.Singleton, - SecureNoteTypeConverter.Singleton, - CipherTypeConverter.Singleton, - ExportFormatConverter.Singleton, - ExportFormatEnumConverter.Singleton, - SendTypeConverter.Singleton, - new DateOnlyConverter(), - new TimeOnlyConverter(), - IsoDateTimeOffsetConverter.Singleton - }, - }; - } - - internal class DeviceTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(DeviceType); - - public override DeviceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "Android": - return DeviceType.Android; - case "AndroidAmazon": - return DeviceType.AndroidAmazon; - case "ChromeBrowser": - return DeviceType.ChromeBrowser; - case "ChromeExtension": - return DeviceType.ChromeExtension; - case "EdgeBrowser": - return DeviceType.EdgeBrowser; - case "EdgeExtension": - return DeviceType.EdgeExtension; - case "FirefoxBrowser": - return DeviceType.FirefoxBrowser; - case "FirefoxExtension": - return DeviceType.FirefoxExtension; - case "IEBrowser": - return DeviceType.IeBrowser; - case "LinuxDesktop": - return DeviceType.LinuxDesktop; - case "MacOsDesktop": - return DeviceType.MacOsDesktop; - case "OperaBrowser": - return DeviceType.OperaBrowser; - case "OperaExtension": - return DeviceType.OperaExtension; - case "SDK": - return DeviceType.Sdk; - case "SafariBrowser": - return DeviceType.SafariBrowser; - case "SafariExtension": - return DeviceType.SafariExtension; - case "UWP": - return DeviceType.Uwp; - case "UnknownBrowser": - return DeviceType.UnknownBrowser; - case "VivaldiBrowser": - return DeviceType.VivaldiBrowser; - case "VivaldiExtension": - return DeviceType.VivaldiExtension; - case "WindowsDesktop": - return DeviceType.WindowsDesktop; - case "iOS": - return DeviceType.IOs; - } - throw new Exception("Cannot unmarshal type DeviceType"); - } - - public override void Write(Utf8JsonWriter writer, DeviceType value, JsonSerializerOptions options) - { - switch (value) - { - case DeviceType.Android: - JsonSerializer.Serialize(writer, "Android", options); - return; - case DeviceType.AndroidAmazon: - JsonSerializer.Serialize(writer, "AndroidAmazon", options); - return; - case DeviceType.ChromeBrowser: - JsonSerializer.Serialize(writer, "ChromeBrowser", options); - return; - case DeviceType.ChromeExtension: - JsonSerializer.Serialize(writer, "ChromeExtension", options); - return; - case DeviceType.EdgeBrowser: - JsonSerializer.Serialize(writer, "EdgeBrowser", options); - return; - case DeviceType.EdgeExtension: - JsonSerializer.Serialize(writer, "EdgeExtension", options); - return; - case DeviceType.FirefoxBrowser: - JsonSerializer.Serialize(writer, "FirefoxBrowser", options); - return; - case DeviceType.FirefoxExtension: - JsonSerializer.Serialize(writer, "FirefoxExtension", options); - return; - case DeviceType.IeBrowser: - JsonSerializer.Serialize(writer, "IEBrowser", options); - return; - case DeviceType.LinuxDesktop: - JsonSerializer.Serialize(writer, "LinuxDesktop", options); - return; - case DeviceType.MacOsDesktop: - JsonSerializer.Serialize(writer, "MacOsDesktop", options); - return; - case DeviceType.OperaBrowser: - JsonSerializer.Serialize(writer, "OperaBrowser", options); - return; - case DeviceType.OperaExtension: - JsonSerializer.Serialize(writer, "OperaExtension", options); - return; - case DeviceType.Sdk: - JsonSerializer.Serialize(writer, "SDK", options); - return; - case DeviceType.SafariBrowser: - JsonSerializer.Serialize(writer, "SafariBrowser", options); - return; - case DeviceType.SafariExtension: - JsonSerializer.Serialize(writer, "SafariExtension", options); - return; - case DeviceType.Uwp: - JsonSerializer.Serialize(writer, "UWP", options); - return; - case DeviceType.UnknownBrowser: - JsonSerializer.Serialize(writer, "UnknownBrowser", options); - return; - case DeviceType.VivaldiBrowser: - JsonSerializer.Serialize(writer, "VivaldiBrowser", options); - return; - case DeviceType.VivaldiExtension: - JsonSerializer.Serialize(writer, "VivaldiExtension", options); - return; - case DeviceType.WindowsDesktop: - JsonSerializer.Serialize(writer, "WindowsDesktop", options); - return; - case DeviceType.IOs: - JsonSerializer.Serialize(writer, "iOS", options); - return; - } - throw new Exception("Cannot marshal type DeviceType"); - } - - public static readonly DeviceTypeConverter Singleton = new DeviceTypeConverter(); - } - - internal class TwoFactorProviderConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(TwoFactorProvider); - - public override TwoFactorProvider Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "Authenticator": - return TwoFactorProvider.Authenticator; - case "Duo": - return TwoFactorProvider.Duo; - case "Email": - return TwoFactorProvider.Email; - case "OrganizationDuo": - return TwoFactorProvider.OrganizationDuo; - case "Remember": - return TwoFactorProvider.Remember; - case "U2f": - return TwoFactorProvider.U2F; - case "WebAuthn": - return TwoFactorProvider.WebAuthn; - case "Yubikey": - return TwoFactorProvider.Yubikey; - } - throw new Exception("Cannot unmarshal type TwoFactorProvider"); - } - - public override void Write(Utf8JsonWriter writer, TwoFactorProvider value, JsonSerializerOptions options) - { - switch (value) - { - case TwoFactorProvider.Authenticator: - JsonSerializer.Serialize(writer, "Authenticator", options); - return; - case TwoFactorProvider.Duo: - JsonSerializer.Serialize(writer, "Duo", options); - return; - case TwoFactorProvider.Email: - JsonSerializer.Serialize(writer, "Email", options); - return; - case TwoFactorProvider.OrganizationDuo: - JsonSerializer.Serialize(writer, "OrganizationDuo", options); - return; - case TwoFactorProvider.Remember: - JsonSerializer.Serialize(writer, "Remember", options); - return; - case TwoFactorProvider.U2F: - JsonSerializer.Serialize(writer, "U2f", options); - return; - case TwoFactorProvider.WebAuthn: - JsonSerializer.Serialize(writer, "WebAuthn", options); - return; - case TwoFactorProvider.Yubikey: - JsonSerializer.Serialize(writer, "Yubikey", options); - return; - } - throw new Exception("Cannot marshal type TwoFactorProvider"); - } - - public static readonly TwoFactorProviderConverter Singleton = new TwoFactorProviderConverter(); - } - - internal class LinkedIdTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(LinkedIdType); - - public override LinkedIdType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "Address1": - return LinkedIdType.Address1; - case "Address2": - return LinkedIdType.Address2; - case "Address3": - return LinkedIdType.Address3; - case "Brand": - return LinkedIdType.Brand; - case "CardholderName": - return LinkedIdType.CardholderName; - case "City": - return LinkedIdType.City; - case "Code": - return LinkedIdType.Code; - case "Company": - return LinkedIdType.Company; - case "Country": - return LinkedIdType.Country; - case "Email": - return LinkedIdType.Email; - case "ExpMonth": - return LinkedIdType.ExpMonth; - case "ExpYear": - return LinkedIdType.ExpYear; - case "FirstName": - return LinkedIdType.FirstName; - case "FullName": - return LinkedIdType.FullName; - case "LastName": - return LinkedIdType.LastName; - case "LicenseNumber": - return LinkedIdType.LicenseNumber; - case "MiddleName": - return LinkedIdType.MiddleName; - case "Number": - return LinkedIdType.Number; - case "PassportNumber": - return LinkedIdType.PassportNumber; - case "Password": - return LinkedIdType.Password; - case "Phone": - return LinkedIdType.Phone; - case "PostalCode": - return LinkedIdType.PostalCode; - case "Ssn": - return LinkedIdType.Ssn; - case "State": - return LinkedIdType.State; - case "Title": - return LinkedIdType.Title; - case "Username": - return LinkedIdType.Username; - } - throw new Exception("Cannot unmarshal type LinkedIdType"); - } - - public override void Write(Utf8JsonWriter writer, LinkedIdType value, JsonSerializerOptions options) - { - switch (value) - { - case LinkedIdType.Address1: - JsonSerializer.Serialize(writer, "Address1", options); - return; - case LinkedIdType.Address2: - JsonSerializer.Serialize(writer, "Address2", options); - return; - case LinkedIdType.Address3: - JsonSerializer.Serialize(writer, "Address3", options); - return; - case LinkedIdType.Brand: - JsonSerializer.Serialize(writer, "Brand", options); - return; - case LinkedIdType.CardholderName: - JsonSerializer.Serialize(writer, "CardholderName", options); - return; - case LinkedIdType.City: - JsonSerializer.Serialize(writer, "City", options); - return; - case LinkedIdType.Code: - JsonSerializer.Serialize(writer, "Code", options); - return; - case LinkedIdType.Company: - JsonSerializer.Serialize(writer, "Company", options); - return; - case LinkedIdType.Country: - JsonSerializer.Serialize(writer, "Country", options); - return; - case LinkedIdType.Email: - JsonSerializer.Serialize(writer, "Email", options); - return; - case LinkedIdType.ExpMonth: - JsonSerializer.Serialize(writer, "ExpMonth", options); - return; - case LinkedIdType.ExpYear: - JsonSerializer.Serialize(writer, "ExpYear", options); - return; - case LinkedIdType.FirstName: - JsonSerializer.Serialize(writer, "FirstName", options); - return; - case LinkedIdType.FullName: - JsonSerializer.Serialize(writer, "FullName", options); - return; - case LinkedIdType.LastName: - JsonSerializer.Serialize(writer, "LastName", options); - return; - case LinkedIdType.LicenseNumber: - JsonSerializer.Serialize(writer, "LicenseNumber", options); - return; - case LinkedIdType.MiddleName: - JsonSerializer.Serialize(writer, "MiddleName", options); - return; - case LinkedIdType.Number: - JsonSerializer.Serialize(writer, "Number", options); - return; - case LinkedIdType.PassportNumber: - JsonSerializer.Serialize(writer, "PassportNumber", options); - return; - case LinkedIdType.Password: - JsonSerializer.Serialize(writer, "Password", options); - return; - case LinkedIdType.Phone: - JsonSerializer.Serialize(writer, "Phone", options); - return; - case LinkedIdType.PostalCode: - JsonSerializer.Serialize(writer, "PostalCode", options); - return; - case LinkedIdType.Ssn: - JsonSerializer.Serialize(writer, "Ssn", options); - return; - case LinkedIdType.State: - JsonSerializer.Serialize(writer, "State", options); - return; - case LinkedIdType.Title: - JsonSerializer.Serialize(writer, "Title", options); - return; - case LinkedIdType.Username: - JsonSerializer.Serialize(writer, "Username", options); - return; - } - throw new Exception("Cannot marshal type LinkedIdType"); - } - - public static readonly LinkedIdTypeConverter Singleton = new LinkedIdTypeConverter(); - } - - internal class FieldTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(FieldType); - - public override FieldType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "Boolean": - return FieldType.Boolean; - case "Hidden": - return FieldType.Hidden; - case "Linked": - return FieldType.Linked; - case "Text": - return FieldType.Text; - } - throw new Exception("Cannot unmarshal type FieldType"); - } - - public override void Write(Utf8JsonWriter writer, FieldType value, JsonSerializerOptions options) - { - switch (value) - { - case FieldType.Boolean: - JsonSerializer.Serialize(writer, "Boolean", options); - return; - case FieldType.Hidden: - JsonSerializer.Serialize(writer, "Hidden", options); - return; - case FieldType.Linked: - JsonSerializer.Serialize(writer, "Linked", options); - return; - case FieldType.Text: - JsonSerializer.Serialize(writer, "Text", options); - return; - } - throw new Exception("Cannot marshal type FieldType"); - } - - public static readonly FieldTypeConverter Singleton = new FieldTypeConverter(); - } - - internal class UriMatchTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(UriMatchType); - - public override UriMatchType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "domain": - return UriMatchType.Domain; - case "exact": - return UriMatchType.Exact; - case "host": - return UriMatchType.Host; - case "never": - return UriMatchType.Never; - case "regularExpression": - return UriMatchType.RegularExpression; - case "startsWith": - return UriMatchType.StartsWith; - } - throw new Exception("Cannot unmarshal type UriMatchType"); - } - - public override void Write(Utf8JsonWriter writer, UriMatchType value, JsonSerializerOptions options) - { - switch (value) - { - case UriMatchType.Domain: - JsonSerializer.Serialize(writer, "domain", options); - return; - case UriMatchType.Exact: - JsonSerializer.Serialize(writer, "exact", options); - return; - case UriMatchType.Host: - JsonSerializer.Serialize(writer, "host", options); - return; - case UriMatchType.Never: - JsonSerializer.Serialize(writer, "never", options); - return; - case UriMatchType.RegularExpression: - JsonSerializer.Serialize(writer, "regularExpression", options); - return; - case UriMatchType.StartsWith: - JsonSerializer.Serialize(writer, "startsWith", options); - return; - } - throw new Exception("Cannot marshal type UriMatchType"); - } - - public static readonly UriMatchTypeConverter Singleton = new UriMatchTypeConverter(); - } - - internal class CipherRepromptTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(CipherRepromptType); - - public override CipherRepromptType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "None": - return CipherRepromptType.None; - case "Password": - return CipherRepromptType.Password; - } - throw new Exception("Cannot unmarshal type CipherRepromptType"); - } - - public override void Write(Utf8JsonWriter writer, CipherRepromptType value, JsonSerializerOptions options) - { - switch (value) - { - case CipherRepromptType.None: - JsonSerializer.Serialize(writer, "None", options); - return; - case CipherRepromptType.Password: - JsonSerializer.Serialize(writer, "Password", options); - return; - } - throw new Exception("Cannot marshal type CipherRepromptType"); - } - - public static readonly CipherRepromptTypeConverter Singleton = new CipherRepromptTypeConverter(); - } - - internal class SecureNoteTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(SecureNoteType); - - public override SecureNoteType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - if (value == "Generic") - { - return SecureNoteType.Generic; - } - throw new Exception("Cannot unmarshal type SecureNoteType"); - } - - public override void Write(Utf8JsonWriter writer, SecureNoteType value, JsonSerializerOptions options) - { - if (value == SecureNoteType.Generic) - { - JsonSerializer.Serialize(writer, "Generic", options); - return; - } - throw new Exception("Cannot marshal type SecureNoteType"); - } - - public static readonly SecureNoteTypeConverter Singleton = new SecureNoteTypeConverter(); - } - - internal class CipherTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(CipherType); - - public override CipherType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "Card": - return CipherType.Card; - case "Identity": - return CipherType.Identity; - case "Login": - return CipherType.Login; - case "SecureNote": - return CipherType.SecureNote; - } - throw new Exception("Cannot unmarshal type CipherType"); - } - - public override void Write(Utf8JsonWriter writer, CipherType value, JsonSerializerOptions options) - { - switch (value) - { - case CipherType.Card: - JsonSerializer.Serialize(writer, "Card", options); - return; - case CipherType.Identity: - JsonSerializer.Serialize(writer, "Identity", options); - return; - case CipherType.Login: - JsonSerializer.Serialize(writer, "Login", options); - return; - case CipherType.SecureNote: - JsonSerializer.Serialize(writer, "SecureNote", options); - return; - } - throw new Exception("Cannot marshal type CipherType"); - } - - public static readonly CipherTypeConverter Singleton = new CipherTypeConverter(); - } - - internal class ExportFormatConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(ExportFormat); - - public override ExportFormat Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - switch (reader.TokenType) - { - case JsonTokenType.String: - var stringValue = reader.GetString(); - switch (stringValue) - { - case "AccountEncryptedJson": - return new ExportFormat { Enum = ExportFormatEnum.AccountEncryptedJson }; - case "Csv": - return new ExportFormat { Enum = ExportFormatEnum.Csv }; - case "Json": - return new ExportFormat { Enum = ExportFormatEnum.Json }; - } - break; - case JsonTokenType.StartObject: - var objectValue = JsonSerializer.Deserialize(ref reader, options); - return new ExportFormat { ExportFormatClass = objectValue }; - } - throw new Exception("Cannot unmarshal type ExportFormat"); - } - - public override void Write(Utf8JsonWriter writer, ExportFormat value, JsonSerializerOptions options) - { - if (value.Enum != null) - { - switch (value.Enum) - { - case ExportFormatEnum.AccountEncryptedJson: - JsonSerializer.Serialize(writer, "AccountEncryptedJson", options); - return; - case ExportFormatEnum.Csv: - JsonSerializer.Serialize(writer, "Csv", options); - return; - case ExportFormatEnum.Json: - JsonSerializer.Serialize(writer, "Json", options); - return; - } - } - if (value.ExportFormatClass != null) - { - JsonSerializer.Serialize(writer, value.ExportFormatClass, options); - return; - } - throw new Exception("Cannot marshal type ExportFormat"); - } - - public static readonly ExportFormatConverter Singleton = new ExportFormatConverter(); - } - - internal class ExportFormatEnumConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(ExportFormatEnum); - - public override ExportFormatEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "AccountEncryptedJson": - return ExportFormatEnum.AccountEncryptedJson; - case "Csv": - return ExportFormatEnum.Csv; - case "Json": - return ExportFormatEnum.Json; - } - throw new Exception("Cannot unmarshal type ExportFormatEnum"); - } - - public override void Write(Utf8JsonWriter writer, ExportFormatEnum value, JsonSerializerOptions options) - { - switch (value) - { - case ExportFormatEnum.AccountEncryptedJson: - JsonSerializer.Serialize(writer, "AccountEncryptedJson", options); - return; - case ExportFormatEnum.Csv: - JsonSerializer.Serialize(writer, "Csv", options); - return; - case ExportFormatEnum.Json: - JsonSerializer.Serialize(writer, "Json", options); - return; - } - throw new Exception("Cannot marshal type ExportFormatEnum"); - } - - public static readonly ExportFormatEnumConverter Singleton = new ExportFormatEnumConverter(); - } - - internal class SendTypeConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(SendType); - - public override SendType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - switch (value) - { - case "File": - return SendType.File; - case "Text": - return SendType.Text; - } - throw new Exception("Cannot unmarshal type SendType"); - } - - public override void Write(Utf8JsonWriter writer, SendType value, JsonSerializerOptions options) - { - switch (value) - { - case SendType.File: - JsonSerializer.Serialize(writer, "File", options); - return; - case SendType.Text: - JsonSerializer.Serialize(writer, "Text", options); - return; - } - throw new Exception("Cannot marshal type SendType"); - } - - public static readonly SendTypeConverter Singleton = new SendTypeConverter(); - } - - public class DateOnlyConverter : JsonConverter - { - private readonly string serializationFormat; - public DateOnlyConverter() : this(null) { } - - public DateOnlyConverter(string? serializationFormat) - { - this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; - } - - public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - return DateOnly.Parse(value!); - } - - public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) - => writer.WriteStringValue(value.ToString(serializationFormat)); - } - - public class TimeOnlyConverter : JsonConverter - { - private readonly string serializationFormat; - - public TimeOnlyConverter() : this(null) { } - - public TimeOnlyConverter(string? serializationFormat) - { - this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; - } - - public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var value = reader.GetString(); - return TimeOnly.Parse(value!); - } - - public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) - => writer.WriteStringValue(value.ToString(serializationFormat)); - } - - internal class IsoDateTimeOffsetConverter : JsonConverter - { - public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); - - private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; - - private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; - private string? _dateTimeFormat; - private CultureInfo? _culture; - - public DateTimeStyles DateTimeStyles - { - get => _dateTimeStyles; - set => _dateTimeStyles = value; - } - - public string? DateTimeFormat - { - get => _dateTimeFormat ?? string.Empty; - set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; - } - - public CultureInfo Culture - { - get => _culture ?? CultureInfo.CurrentCulture; - set => _culture = value; - } - - public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) - { - string text; - - - if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal - || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) - { - value = value.ToUniversalTime(); - } - - text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); - - writer.WriteStringValue(text); - } - - public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - string? dateText = reader.GetString(); - - if (string.IsNullOrEmpty(dateText) == false) - { - if (!string.IsNullOrEmpty(_dateTimeFormat)) - { - return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); - } - else - { - return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); - } - } - else - { - return default(DateTimeOffset); - } - } - - - public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); - } -} -#pragma warning restore CS8618 -#pragma warning restore CS8601 -#pragma warning restore CS8603 - diff --git a/languages/go/README.md b/languages/go/README.md index 19979ed2c..e5f8707ff 100644 --- a/languages/go/README.md +++ b/languages/go/README.md @@ -31,7 +31,7 @@ import "github.com/bitwarden/sdk/languages/go" settings := ClientSettings{ // Your settings here } -client := NewBitwardenClient(settings) +bitwardenClient, _ := sdk.NewBitwardenClient(&apiURL, &identityURL) ``` --- @@ -41,7 +41,7 @@ client := NewBitwardenClient(settings) To login using an access token: ```go -response := client.AccessTokenLogin("your_access_token_here") +apiKeyLogin, err := bitwardenClient.AccessTokenLogin(accessToken) ``` --- @@ -51,25 +51,25 @@ response := client.AccessTokenLogin("your_access_token_here") #### Create a Project ```go -response, err := client.Projects.Create("organization_id", "project_name") +project, err := client.Projects.Create("organization_id", "project_name") ``` #### List Projects ```go -response, err := client.Projects.List("organization_id") +projects, err := client.Projects.List("organization_id") ``` #### Update a Project ```go -response, err := client.Projects.Update("project_id", "organization_id", "new_project_name") +project, err := client.Projects.Update("project_id", "organization_id", "new_project_name") ``` #### Delete Projects ```go -response, err := client.Projects.Delete([]string{"project_id_1", "project_id_2"}) +project, err := client.Projects.Delete([]string{"project_id_1", "project_id_2"}) ``` --- @@ -79,25 +79,25 @@ response, err := client.Projects.Delete([]string{"project_id_1", "project_id_2"} #### Create a Secret ```go -response, err := client.Secrets.Create("key", "value", "note", "organization_id", []string{"project_id"}) +secret, err := client.Secrets.Create("key", "value", "note", "organization_id", []string{"project_id"}) ``` #### List Secrets ```go -response, err := client.Secrets.List("organization_id") +secrets, err := client.Secrets.List("organization_id") ``` #### Update a Secret ```go -response, err := client.Secrets.Update("secret_id", "new_key", "new_value", "new_note", "organization_id", []string{"project_id"}) +secret, err := client.Secrets.Update("secret_id", "new_key", "new_value", "new_note", "organization_id", []string{"project_id"}) ``` #### Delete Secrets ```go -response, err := client.Secrets.Delete([]string{"secret_id_1", "secret_id_2"}) +secret, err := client.Secrets.Delete([]string{"secret_id_1", "secret_id_2"}) ``` --- @@ -107,7 +107,7 @@ response, err := client.Secrets.Delete([]string{"secret_id_1", "secret_id_2"}) To free up resources: ```go -client.Close() +defer bitwardenClient.Close() ``` --- diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index a417f16af..f4f6b5351 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -14,24 +14,25 @@ type BitwardenClient struct { Secrets SecretsInterface } -func NewBitwardenClient(apiURL *string, identityURL *string, userAgent *string) *BitwardenClient { +func NewBitwardenClient(apiURL *string, identityURL *string) (*BitwardenClient, error) { deviceType := DeviceType("SDK") + var userAgent = "GOLANG-SDK" clientSettings := ClientSettings{ APIURL: apiURL, IdentityURL: identityURL, - UserAgent: userAgent, + UserAgent: &userAgent, DeviceType: &deviceType, } settingsJSON, err := json.Marshal(clientSettings) if err != nil { - panic(err) + return nil, err } lib := cinterface.NewBitwardenLibrary() client, err := lib.Init(string(settingsJSON)) if err != nil { - panic(err) + return nil, err } runner := NewCommandRunner(client, lib) @@ -41,21 +42,24 @@ func NewBitwardenClient(apiURL *string, identityURL *string, userAgent *string) commandRunner: runner, Projects: NewProjects(runner), Secrets: NewSecrets(runner), - } + }, nil } -func (c *BitwardenClient) AccessTokenLogin(accessToken string) ResponseForAPIKeyLoginResponse { +func (c *BitwardenClient) AccessTokenLogin(accessToken string) (*ResponseForAPIKeyLoginResponse, error) { req := AccessTokenLoginRequest{AccessToken: accessToken} command := Command{AccessTokenLogin: &req} - responseStr := c.commandRunner.RunCommand(command) + responseStr, err := c.commandRunner.RunCommand(command) + if err != nil { + return nil, err + } var response ResponseForAPIKeyLoginResponse if err := json.Unmarshal([]byte(responseStr), &response); err != nil { - panic(err) + return nil, err } - return response + return &response, nil } func (c *BitwardenClient) Close() { diff --git a/languages/go/command_runner.go b/languages/go/command_runner.go index 20246a10d..3f79f7149 100644 --- a/languages/go/command_runner.go +++ b/languages/go/command_runner.go @@ -7,7 +7,7 @@ import ( ) type CommandRunnerInterface interface { - RunCommand(command Command) string + RunCommand(command Command) (string, error) } type CommandRunner struct { @@ -22,16 +22,16 @@ func NewCommandRunner(client cinterface.ClientPointer, lib cinterface.BitwardenL } } -func (c *CommandRunner) RunCommand(command Command) string { +func (c *CommandRunner) RunCommand(command Command) (string, error) { commandJSON, err := json.Marshal(command) if err != nil { - panic(err) + return "", err } responseStr, err := c.lib.RunCommand(string(commandJSON), c.client) if err != nil { - panic(err) + return "", err } - return responseStr + return responseStr, nil } diff --git a/languages/go/example/example.go b/languages/go/example/example.go index a20e6219f..db2a52a3b 100644 --- a/languages/go/example/example.go +++ b/languages/go/example/example.go @@ -11,9 +11,8 @@ import ( func main() { apiURL := os.Getenv("API_URL") identityURL := os.Getenv("IDENTITY_URL") - userAgent := os.Getenv("USER_AGENT") - bitwardenClient := sdk.NewBitwardenClient(&apiURL, &identityURL, &userAgent) + bitwardenClient, _ := sdk.NewBitwardenClient(&apiURL, &identityURL) accessToken := os.Getenv("ACCESS_TOKEN") organizationIDStr := os.Getenv("ORGANIZATION_ID") @@ -23,20 +22,23 @@ func main() { projectName = "NewTestProject" // default value } - responseForAPIKeyLoginResponse := bitwardenClient.AccessTokenLogin(accessToken) - fmt.Println(responseForAPIKeyLoginResponse) + apiKeyLogin, err := bitwardenClient.AccessTokenLogin(accessToken) + if err != nil { + panic(err) + } + fmt.Println(apiKeyLogin) organizationID, err := uuid.FromString(organizationIDStr) if err != nil { panic(err) } - projectResponse, err := bitwardenClient.Projects.Create(organizationID.String(), projectName) + project, err := bitwardenClient.Projects.Create(organizationID.String(), projectName) if err != nil { panic(err) } - fmt.Println(projectResponse) - projectID := projectResponse.ID + fmt.Println(project) + projectID := project.ID fmt.Println(projectID) if _, err = bitwardenClient.Projects.List(organizationID.String()); err != nil { @@ -55,11 +57,11 @@ func main() { value := "value" note := "note" - secretResponse, err := bitwardenClient.Secrets.Create(key, value, note, organizationID.String(), []string{projectID}) + secret, err := bitwardenClient.Secrets.Create(key, value, note, organizationID.String(), []string{projectID}) if err != nil { panic(err) } - secretID := secretResponse.ID + secretID := secret.ID if _, err = bitwardenClient.Secrets.List(organizationID.String()); err != nil { panic(err) @@ -81,5 +83,5 @@ func main() { panic(err) } - bitwardenClient.Close() + defer bitwardenClient.Close() } diff --git a/languages/go/project.go b/languages/go/project.go index 514420bdd..5fd5c53bd 100644 --- a/languages/go/project.go +++ b/languages/go/project.go @@ -99,6 +99,9 @@ func (p *Projects) Delete(projectIDs []string) (*ProjectResponse, error) { } func (p *Projects) executeCommand(command Command, target interface{}) error { - responseStr := p.CommandRunner.RunCommand(command) + responseStr, err := p.CommandRunner.RunCommand(command) + if err != nil { + return err + } return checkSuccessAndError(responseStr, target) } diff --git a/languages/go/secrets.go b/languages/go/secrets.go index c151377f1..e6863c459 100644 --- a/languages/go/secrets.go +++ b/languages/go/secrets.go @@ -17,7 +17,10 @@ func NewSecrets(commandRunner CommandRunnerInterface) *Secrets { } func (s *Secrets) executeCommand(command Command, target interface{}) error { - responseStr := s.CommandRunner.RunCommand(command) + responseStr, err := s.CommandRunner.RunCommand(command) + if err != nil { + return err + } return checkSuccessAndError(responseStr, target) } diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index 8d228a036..cb5d99aa8 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -63,7 +63,7 @@ async function main() { }); writeToFile("./languages/csharp/Bitwarden.Sdk/schemas.cs", csharp.lines); - + writeToFile("./languages/csharp/schemas.cs", csharp.lines); const go = await quicktype({ @@ -71,10 +71,10 @@ async function main() { lang: "go", rendererOptions: { package: "sdk", + "just-types-and-package": true, }, }); writeToFile("./languages/go/schema.go", go.lines); - } main(); From 4e98474b8e286f626fb43bc2904c62f2bb606920 Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Tue, 31 Oct 2023 12:24:09 +0100 Subject: [PATCH 22/30] address PR comments --- languages/go/README.md | 3 --- languages/go/bitwarden_client.go | 10 +++++----- languages/go/example/example.go | 3 +-- languages/go/project.go | 6 +++--- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/languages/go/README.md b/languages/go/README.md index e5f8707ff..3de364356 100644 --- a/languages/go/README.md +++ b/languages/go/README.md @@ -28,9 +28,6 @@ To initialize the client, you need to import the SDK and create a new `Bitwarden ```go import "github.com/bitwarden/sdk/languages/go" -settings := ClientSettings{ - // Your settings here -} bitwardenClient, _ := sdk.NewBitwardenClient(&apiURL, &identityURL) ``` diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index f4f6b5351..68d4401ae 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -16,7 +16,7 @@ type BitwardenClient struct { func NewBitwardenClient(apiURL *string, identityURL *string) (*BitwardenClient, error) { deviceType := DeviceType("SDK") - var userAgent = "GOLANG-SDK" + userAgent := "Bitwarden GOLANG-SDK" clientSettings := ClientSettings{ APIURL: apiURL, IdentityURL: identityURL, @@ -45,21 +45,21 @@ func NewBitwardenClient(apiURL *string, identityURL *string) (*BitwardenClient, }, nil } -func (c *BitwardenClient) AccessTokenLogin(accessToken string) (*ResponseForAPIKeyLoginResponse, error) { +func (c *BitwardenClient) AccessTokenLogin(accessToken string) error { req := AccessTokenLoginRequest{AccessToken: accessToken} command := Command{AccessTokenLogin: &req} responseStr, err := c.commandRunner.RunCommand(command) if err != nil { - return nil, err + return err } var response ResponseForAPIKeyLoginResponse if err := json.Unmarshal([]byte(responseStr), &response); err != nil { - return nil, err + return err } - return &response, nil + return nil } func (c *BitwardenClient) Close() { diff --git a/languages/go/example/example.go b/languages/go/example/example.go index db2a52a3b..5935d8002 100644 --- a/languages/go/example/example.go +++ b/languages/go/example/example.go @@ -22,11 +22,10 @@ func main() { projectName = "NewTestProject" // default value } - apiKeyLogin, err := bitwardenClient.AccessTokenLogin(accessToken) + err := bitwardenClient.AccessTokenLogin(accessToken) if err != nil { panic(err) } - fmt.Println(apiKeyLogin) organizationID, err := uuid.FromString(organizationIDStr) if err != nil { diff --git a/languages/go/project.go b/languages/go/project.go index 5fd5c53bd..24a30a7ac 100644 --- a/languages/go/project.go +++ b/languages/go/project.go @@ -5,7 +5,7 @@ type ProjectsInterface interface { List(organizationID string) (*ProjectsResponse, error) Get(projectID string) (*ProjectResponse, error) Update(projectID string, organizationID string, name string) (*ProjectResponse, error) - Delete(projectIDs []string) (*ProjectResponse, error) + Delete(projectIDs []string) (*ProjectsDeleteResponse, error) } type Projects struct { @@ -82,7 +82,7 @@ func (p *Projects) Update(projectID, organizationID, name string) (*ProjectRespo return &response, nil } -func (p *Projects) Delete(projectIDs []string) (*ProjectResponse, error) { +func (p *Projects) Delete(projectIDs []string) (*ProjectsDeleteResponse, error) { command := Command{ Projects: &ProjectsCommand{ Delete: &ProjectsDeleteRequest{ @@ -91,7 +91,7 @@ func (p *Projects) Delete(projectIDs []string) (*ProjectResponse, error) { }, } - var response ProjectResponse + var response ProjectsDeleteResponse if err := p.executeCommand(command, &response); err != nil { return nil, err } From 00ca7a37a84578f3b25b3b54f32bcad399fe679e Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Tue, 31 Oct 2023 13:37:55 +0100 Subject: [PATCH 23/30] address PR comments --- languages/go/bitwarden_client.go | 6 +----- languages/go/util.go | 7 ++++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index 68d4401ae..aedc51224 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -55,11 +55,7 @@ func (c *BitwardenClient) AccessTokenLogin(accessToken string) error { } var response ResponseForAPIKeyLoginResponse - if err := json.Unmarshal([]byte(responseStr), &response); err != nil { - return err - } - - return nil + return checkSuccessAndError(responseStr, &response) } func (c *BitwardenClient) Close() { diff --git a/languages/go/util.go b/languages/go/util.go index 13879de5f..01ab3578d 100644 --- a/languages/go/util.go +++ b/languages/go/util.go @@ -7,8 +7,9 @@ import ( func checkSuccessAndError(responseStr string, v interface{}) error { var wrapper struct { - Success bool `json:"success"` - ErrorMessage *string `json:"errorMessage"` + Success bool `json:"success"` + ErrorMessage *string `json:"errorMessage"` + Data *json.RawMessage `json:"data"` } err := json.Unmarshal([]byte(responseStr), &wrapper) @@ -23,7 +24,7 @@ func checkSuccessAndError(responseStr string, v interface{}) error { return fmt.Errorf("API error: unknown") } - err = json.Unmarshal([]byte(responseStr), &v) + err = json.Unmarshal(*wrapper.Data, &v) if err != nil { return fmt.Errorf("failed to unmarshal response: %v", err) } From b9060c417246651e53a8fe837de32c573f2468ae Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Tue, 31 Oct 2023 13:51:53 +0100 Subject: [PATCH 24/30] address PR comments --- languages/go/bitwarden_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/languages/go/bitwarden_client.go b/languages/go/bitwarden_client.go index aedc51224..5e1108ce1 100644 --- a/languages/go/bitwarden_client.go +++ b/languages/go/bitwarden_client.go @@ -54,7 +54,7 @@ func (c *BitwardenClient) AccessTokenLogin(accessToken string) error { return err } - var response ResponseForAPIKeyLoginResponse + var response APIKeyLoginResponse return checkSuccessAndError(responseStr, &response) } From 5ce40b4ed8f5d4956e037738dd73ae6d1357eac1 Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Thu, 2 Nov 2023 18:15:08 +0100 Subject: [PATCH 25/30] remove go.work --- go.work | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 go.work diff --git a/go.work b/go.work deleted file mode 100644 index 92e4a4e4e..000000000 --- a/go.work +++ /dev/null @@ -1,4 +0,0 @@ -go 1.20 - -use ./languages/go -use ./languages/go/example From afa281319e9cdc59d062e875ff49889217e5d985 Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Thu, 2 Nov 2023 18:56:31 +0100 Subject: [PATCH 26/30] address PR comments --- .github/workflows/golang-release.yml | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/.github/workflows/golang-release.yml b/.github/workflows/golang-release.yml index 7ffdf8381..6f41bcd3e 100644 --- a/.github/workflows/golang-release.yml +++ b/.github/workflows/golang-release.yml @@ -19,19 +19,22 @@ jobs: uses: ./.github/workflows/generate_schemas.yml build: - needs: [build_rust, generate-schemas] - runs-on: ubuntu-latest + name: Build + needs: + - build_rust + - generate-schemas + runs-on: ubuntu-22.04 steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - name: Setup Go environment - uses: actions/setup-go@v2 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: ${{ env.GO_VERSION }} - name: Cache dependencies - uses: actions/cache@v2 + uses: actions/cache@704facf57e6136b1bc63b828d79edcd491f0ee84 # v3.3.2 with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} @@ -45,14 +48,15 @@ jobs: run: go test -v ./... release: - needs: [build] - runs-on: ubuntu-latest + name: Release + needs: build + runs-on: ubuntu-22.04 steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - name: Setup Go environment - uses: actions/setup-go@v2 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: ${{ env.GO_VERSION }} @@ -60,7 +64,7 @@ jobs: run: echo "VERSION=${{ github.event.inputs.version_number }}" >> $GITHUB_ENV - name: Install Goreleaser - run: go install github.com/goreleaser/goreleaser@latest + run: go install github.com/goreleaser/goreleaser@v1.21.2 - name: Run Goreleaser run: goreleaser release --rm-dist --skip-validate From b7ef4b8e72b386e8212b24512a6122d80401cb5e Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Tue, 14 Nov 2023 12:49:30 +0100 Subject: [PATCH 27/30] remove build.sh and custom lib --- languages/go/build.sh | 8 --- .../cinterface/bitwarden_library_custom.go | 58 ------------------- 2 files changed, 66 deletions(-) delete mode 100755 languages/go/build.sh delete mode 100644 languages/go/internal/cinterface/bitwarden_library_custom.go diff --git a/languages/go/build.sh b/languages/go/build.sh deleted file mode 100755 index 0735ead6c..000000000 --- a/languages/go/build.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -if [ -n "$BITWARDEN_LIB_PATH" ]; then - sed "s/{{.LibPath}}/$BITWARDEN_LIB_PATH/g" internal/cinterface/bitwarden_library.go > internal/cinterface/bitwarden_library.go - go build -tags custom -else - go build -fi diff --git a/languages/go/internal/cinterface/bitwarden_library_custom.go b/languages/go/internal/cinterface/bitwarden_library_custom.go deleted file mode 100644 index 5acbde67d..000000000 --- a/languages/go/internal/cinterface/bitwarden_library_custom.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build custom -// +build custom - -package cinterface - -import ( - "fmt" - "unsafe" -) - -/* -#cgo LDFLAGS: -lbitwarden_c -#cgo linux LDFLAGS: -L/usr/local/lib -L/usr/lib -#cgo darwin LDFLAGS: -L/usr/local/lib -L/usr/lib -#include -typedef void* ClientPtr; -extern char* run_command(const char *command, ClientPtr client); -extern ClientPtr init(const char *clientSettings); -extern void free_mem(ClientPtr client); -*/ -import "C" - -type ClientPointer struct { - Pointer C.ClientPtr -} - -type BitwardenLibrary interface { - Init(clientSettings string) (ClientPointer, error) - FreeMem(client ClientPointer) - RunCommand(command string, client ClientPointer) (string, error) -} - -type BitwardenLibraryImpl struct{} - -func NewBitwardenLibrary() BitwardenLibrary { - return &BitwardenLibraryImpl{} -} - -func (b *BitwardenLibraryImpl) Init(clientSettings string) (ClientPointer, error) { - ptr := C.init(C.CString(clientSettings)) - if ptr == nil { - return ClientPointer{}, fmt.Errorf("initialization failed") - } - return ClientPointer{Pointer: ptr}, nil -} - -func (b *BitwardenLibraryImpl) FreeMem(client ClientPointer) { - C.free_mem(client.Pointer) -} - -func (b *BitwardenLibraryImpl) RunCommand(command string, client ClientPointer) (string, error) { - cstr := C.run_command(C.CString(command), client.Pointer) - if cstr == nil { - return "", fmt.Errorf("run command failed") - } - defer C.free(unsafe.Pointer(cstr)) - return C.GoString(cstr), nil -} From 4c9f6db67809852f884f762c51f8aac3f8609269 Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Mon, 27 Nov 2023 15:15:20 +0100 Subject: [PATCH 28/30] remove some comments --- languages/go/internal/cinterface/bitwarden_library.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/languages/go/internal/cinterface/bitwarden_library.go b/languages/go/internal/cinterface/bitwarden_library.go index 7e50272b6..42327adb2 100644 --- a/languages/go/internal/cinterface/bitwarden_library.go +++ b/languages/go/internal/cinterface/bitwarden_library.go @@ -1,6 +1,3 @@ -//go:build !custom -// +build !custom - package cinterface import ( From 9257c206299a73ce93008ad04c38324b4eb5d9ad Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Tue, 28 Nov 2023 13:43:01 +0100 Subject: [PATCH 29/30] run prettier --- languages/go/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/languages/go/README.md b/languages/go/README.md index 3de364356..e57badf7e 100644 --- a/languages/go/README.md +++ b/languages/go/README.md @@ -1,6 +1,7 @@ # Bitwarden SDK in Go -This SDK is designed to interact with Bitwarden services in Go. It includes implementations for managing projects and secrets, as well as a client interface to facilitate operations like login. +This SDK is designed to interact with Bitwarden services in Go. It includes implementations for +managing projects and secrets, as well as a client interface to facilitate operations like login. ## Prerequisites From 5c14d952ca5ef42ae4a6f54eaa3420841b62fa52 Mon Sep 17 00:00:00 2001 From: Boris Bujak Date: Thu, 30 Nov 2023 09:18:59 +0100 Subject: [PATCH 30/30] merged main --- .github/workflows/generate_schemas.yml | 4 ++-- support/scripts/schemas.ts | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/generate_schemas.yml b/.github/workflows/generate_schemas.yml index e1766d280..7eba684c4 100644 --- a/.github/workflows/generate_schemas.yml +++ b/.github/workflows/generate_schemas.yml @@ -63,13 +63,13 @@ jobs: name: sdk-schemas-json path: ${{ github.workspace }}/support/schemas/* if-no-files-found: error - + - name: Upload Go schemas artifact uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2 with: name: schemas.go path: ${{ github.workspace }}/languages/go/schema.go - + - name: Upload java schemas artifact uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3 with: diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index 27ad77d4b..98c0c39cb 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -70,8 +70,6 @@ async function main() { writeToFile("./languages/csharp/Bitwarden.Sdk/schemas.cs", csharp.lines); - writeToFile("./languages/csharp/schemas.cs", csharp.lines); - const go = await quicktype({ inputData, lang: "go", @@ -80,8 +78,9 @@ async function main() { "just-types-and-package": true, }, }); + writeToFile("./languages/go/schema.go", go.lines); - + const java = await quicktypeMultiFile({ inputData, lang: "java",