Documentation
¶
Overview ¶
Package protocol implements the Huawei CodeArts / 码道 cloud protocol: PKCE + DPoP OAuth, STS refresh, SDK-HMAC-SHA256 signing, v2 chat, and model catalogs.
Index ¶
- Constants
- func AccountKey(c Credential) string
- func ApplyBenefitHeaders(req *http.Request, benefit bool, modelID string)
- func BuildAuthorizeURL(cfg LoginConfig, ticketID, codeChallenge string, port int) string
- func CanonicalHeaders(req *http.Request) (headers, signed string)
- func CanonicalModel(id string) string
- func CanonicalQuery(raw string) string
- func CanonicalRequest(...) string
- func CanonicalURI(path string) string
- func ChatTarget(snapBase string) string
- func DoJSON(client *http.Client, req *http.Request, maxBody int64) (status int, body []byte, err error)
- func ExtractCallbackCode(raw string) string
- func ExtractCallbackRedirect(raw string) string
- func ExtractCallbackSecret(raw string) string
- func FileNameFor(c Credential) string
- func HMACHex(key, msg string) string
- func IsBenefitModel(accountID, model string) bool
- func LooksLikeCodeArts(raw []byte, fileName string) bool
- func MarshalCredential(c Credential) ([]byte, error)
- func MergeCredential(original []byte, c Credential) ([]byte, error)
- func NewChatRequest(target string, body []byte, cred SignCredential, model string, ...) (*http.Request, error)
- func NewTicketRequest(cfg LoginConfig, ticketID, secret string) (*http.Request, error)
- func NewTokenRequest(cfg LoginConfig, form url.Values, dpop DPoPPrivateJWK) (*http.Request, error)
- func NormalizeNonStreamBody(body []byte, model string) ([]byte, error)
- func PKCE() (verifier, challenge string, err error)
- func ParamInvalid(msg string) bool
- func ParseSignature(authorization string) string
- func ParseSignedHeaders(authorization string) string
- func PostChatCompletions(client *http.Client, target string, body []byte, cred SignCredential, ...) (*http.Response, error)
- func PrepareChatBody(raw []byte, model string, stream bool) ([]byte, string, error)
- func RandomHex(n int) (string, error)
- func RandomHexOrTime(n int) string
- func ReadAllLimited(r io.Reader, n int64) ([]byte, error)
- func RedirectURI(cfg LoginConfig, port int) string
- func SHA256Hex(b []byte) string
- func SafePortalRedirect(raw string) string
- func SetAccountModels(accountID string, infos []ModelInfo)
- func SignDPoPProof(jwk DPoPPrivateJWK, htu string) (string, error)
- func SignRequest(req *http.Request, body []byte, cred SignCredential, opts SignOptions)
- func StringToSign(xDate, canonicalRequest string) string
- func StripModelPrefix(model, prefix string) string
- func TicketURL(cfg LoginConfig, ticketID, secret string) string
- func TokenEndpoint(cfg LoginConfig) string
- func TokenFormAuthorizationCode(cfg LoginConfig, code, codeVerifier string, port int) url.Values
- func TokenFormRefresh(cfg LoginConfig, refreshToken, codeVerifier string) url.Values
- func TranslateStreamChunk(chunk []byte, model string) (payloads [][]byte, done bool, err error)
- func UpstreamChatError(status int, body []byte) string
- type CallbackParts
- type Credential
- type DPoPPrivateJWK
- type LegacyCreds
- type LoginConfig
- type ModelInfo
- type STSCreds
- type SignCredential
- type SignOptions
- type TokenResponse
Constants ¶
const ( PluginID = "codearts" PluginName = "CodeArts (华为码道)" PluginVersion = "0.1.5" PluginAuthor = "codeartsPlugin" // Provider is the CPA auth/executor identifier and auth-file type. Provider = "codearts" SnapEngineAPIHost = "https://snap-access.cn-north-4.myhuaweicloud.com" SnapManagerHost = SnapEngineAPIHost + "/snap-manager" PortalHost = "https://codearts.huaweicloud.com/portal" STSHost = "https://sts.cn-north-4.myhuaweicloud.com" BenefitHost = "https://opengw.developer.huaweicloud.com" ClientID = "codearts-agent" EpChatV2 = "/api/v2/chat/completions" EpAgentList = "/v1/agent-center/agents/useragents" EpAgentDetail = "/v1/agent-center/agents/detail" EpModelBuiltin = "/v1/model/builtin" EpBenefitConfig = "/api/v1/gateway/config" EpBenefitClaim = "/api/v1/benefit/claim" EpLoginTicket = "/v1/login/ticket" EpOAuthTokens = "/v1/oauth2/tokens" EpCurrentUser = "/v1/current/user" EpCallerIdentity = "/v5/caller-identity" OAuthPluginName = "snap_AIIDE" OAuthPluginVersion = "5.2.0" HeaderMaasType = "maas_type" HeaderModelID = "model-id" HeaderModelName = "model-name" MaasBenefit = "benefit" SigningAlgorithm = "SDK-HMAC-SHA256" DefaultChatHost = "snap-access.cn-north-4.myhuaweicloud.com" )
Variables ¶
This section is empty.
Functions ¶
func AccountKey ¶
func AccountKey(c Credential) string
AccountKey is the in-process catalog id for this credential. Huawei token responses sometimes omit user_id; fall back to access_key_id so benefit flags from model.for_auth still apply at execute time.
func ApplyBenefitHeaders ¶
ApplyBenefitHeaders sets maas_type / model-id / model-name on req when benefit is true. These headers must be present before SignRequest so they enter SignedHeaders.
func BuildAuthorizeURL ¶
func BuildAuthorizeURL(cfg LoginConfig, ticketID, codeChallenge string, port int) string
BuildAuthorizeURL constructs https://codearts.huaweicloud.com/portal/authorize?...
func CanonicalHeaders ¶
CanonicalHeaders returns the signed header block (lowercase keys, sorted) and the SignedHeaders list. All request headers participate.
func CanonicalModel ¶
CanonicalModel maps case variants to the ID last seen in discovery.
func CanonicalRequest ¶
func CanonicalRequest(method, canonicalURI, canonicalQuery, canonicalHeaders, signedHeaders, payloadHash string) string
CanonicalRequest is the Huawei SDK canonical request string.
func CanonicalURI ¶
CanonicalURI percent-encodes each path segment and always ends with "/".
func ChatTarget ¶
ChatTarget is the upstream chat-completions URL.
func DoJSON ¶
func DoJSON(client *http.Client, req *http.Request, maxBody int64) (status int, body []byte, err error)
DoJSON performs req with client and reads at most maxBody bytes.
func ExtractCallbackCode ¶
ExtractCallbackCode pulls an OAuth code from a pasted callback URL or raw code.
func ExtractCallbackRedirect ¶
ExtractCallbackRedirect pulls the Huawei continue-login URL from a first-hop callback.
func ExtractCallbackSecret ¶
ExtractCallbackSecret pulls portal-issued secret from a callback URL.
func FileNameFor ¶
func FileNameFor(c Credential) string
FileNameFor returns the host auth file name for this credential. User id wins when set. Otherwise the access key is used so accounts that omit user_id do not share one file. The access key is not prefixed with ak:; that form belongs only to AccountKey.
func IsBenefitModel ¶
IsBenefitModel reports whether this account+model must send maas_type=benefit.
func LooksLikeCodeArts ¶
LooksLikeCodeArts reports whether raw JSON is a CodeArts auth file. Type is read from the raw object. ParseCredential still defaults an empty type for credentials this plugin already owns; that default must not claim a file whose type is missing or blank.
func MarshalCredential ¶
func MarshalCredential(c Credential) ([]byte, error)
MarshalCredential encodes the credential as JSON.
func MergeCredential ¶ added in v0.1.2
func MergeCredential(original []byte, c Credential) ([]byte, error)
MergeCredential overlays c onto the JSON object in original and returns the result. Keys this plugin does not own (CPA's prefix, priority, proxy_url, note, disabled, ...) are kept so a parse or refresh write does not drop them. An empty or non-object original yields MarshalCredential(c).
func NewChatRequest ¶
func NewChatRequest(target string, body []byte, cred SignCredential, model string, benefit, stream bool, opts SignOptions) (*http.Request, error)
NewChatRequest builds a signed POST to /api/v2/chat/completions.
func NewTicketRequest ¶
func NewTicketRequest(cfg LoginConfig, ticketID, secret string) (*http.Request, error)
NewTicketRequest builds GET snap-manager /v1/login/ticket.
func NewTokenRequest ¶
func NewTokenRequest(cfg LoginConfig, form url.Values, dpop DPoPPrivateJWK) (*http.Request, error)
NewTokenRequest builds a POST to STS with form body and DPoP proof.
func NormalizeNonStreamBody ¶ added in v0.1.4
NormalizeNonStreamBody returns one OpenAI chat completion for a non-stream executor payload. Plain JSON is returned unchanged. SSE is aggregated.
func ParamInvalid ¶ added in v0.1.5
ParamInvalid reports InferHub.001001005, a client request-shape rejection. Retrying the same body with benefit headers cannot fix it.
func ParseSignature ¶
ParseSignature extracts the Signature hex from an Authorization value.
func ParseSignedHeaders ¶
ParseSignedHeaders extracts the SignedHeaders list from an Authorization value.
func PostChatCompletions ¶
func PostChatCompletions(client *http.Client, target string, body []byte, cred SignCredential, model string, benefit, stream bool, opts SignOptions) (*http.Response, error)
PostChatCompletions signs and sends the OpenAI-shaped body to the v2 endpoint.
func PrepareChatBody ¶
PrepareChatBody rebuilds an OpenAI chat body into the shape InferHub accepts. Unknown fields are dropped. A named tool_choice object becomes the string "required" with tools reduced to that one function: InferHub rejects the object form with InferHub.001001005.400.
func RandomHexOrTime ¶
RandomHexOrTime returns n random bytes as hex, falling back to a timestamp.
func ReadAllLimited ¶
ReadAllLimited reads at most n bytes from r.
func RedirectURI ¶
func RedirectURI(cfg LoginConfig, port int) string
RedirectURI is the loopback URI Huawei binds to the authorization code.
func SafePortalRedirect ¶
SafePortalRedirect returns raw if it is an https Huawei portal/login URL.
func SetAccountModels ¶
SetAccountModels replaces one account's catalog.
func SignDPoPProof ¶
func SignDPoPProof(jwk DPoPPrivateJWK, htu string) (string, error)
SignDPoPProof builds an ES256 DPoP JWT (htm=POST, htu=token endpoint).
func SignRequest ¶
func SignRequest(req *http.Request, body []byte, cred SignCredential, opts SignOptions)
SignRequest adds X-Sdk-Date, X-Security-Token, X-Sdk-Content-Sha256, Host, and Authorization (SDK-HMAC-SHA256). Every header on req except Authorization is signed. CanonicalURI always ends with "/".
func StringToSign ¶
StringToSign is algorithm + date + hex(sha256(canonicalRequest)).
func StripModelPrefix ¶ added in v0.1.2
StripModelPrefix returns the Huawei model id for a CPA route name. CPA namespaces an auth's models as "<prefix>/<id>" when the auth file sets prefix. Huawei only accepts the bare id, so a leading "<prefix>/" is removed. When prefix is unknown, a single leading "<seg>/" is still removed: Huawei ids themselves never contain "/", and the in-process catalog is empty until model.for_auth has run. A name with more than one slash is left as-is.
func TicketURL ¶
func TicketURL(cfg LoginConfig, ticketID, secret string) string
TicketURL is the snap-manager ticket poll URL.
func TokenEndpoint ¶
func TokenEndpoint(cfg LoginConfig) string
TokenEndpoint is the STS oauth2/tokens URL.
func TokenFormAuthorizationCode ¶
func TokenFormAuthorizationCode(cfg LoginConfig, code, codeVerifier string, port int) url.Values
TokenFormAuthorizationCode is the STS form for grant_type=authorization_code.
func TokenFormRefresh ¶
func TokenFormRefresh(cfg LoginConfig, refreshToken, codeVerifier string) url.Values
TokenFormRefresh is the STS form for grant_type=refresh_token.
func TranslateStreamChunk ¶ added in v0.1.4
TranslateStreamChunk converts one upstream read into JSON objects for host.stream.emit. The caller must not add a "data:" prefix. done is true when the upstream sent the SSE terminator or the read was a finished JSON object. An upstream error_code returns an error instead of a chunk.
func UpstreamChatError ¶
UpstreamChatError returns a non-empty message when Huawei wrapped a failure in a 2xx JSON body (e.g. error_code 4004 benefit not found).
Types ¶
type CallbackParts ¶
type CallbackParts struct {
Code string
Secret string
Redirect string
State string
TicketID string
}
CallbackParts is the Huawei loopback callback: first hop is secret+redirect, second hop carries the authorization code. State and TicketID are optional binding keys; the authorize URL does not send state.
func ParseCallback ¶
func ParseCallback(raw string) CallbackParts
ParseCallback extracts code / secret / redirect / state / ticket_id from a pasted callback URL, a labeled Chinese prompt, or a raw authorization code.
type Credential ¶
type Credential struct {
Type string `json:"type"`
UserID string `json:"user_id,omitempty"`
UserName string `json:"user_name,omitempty"`
DomainID string `json:"domain_id,omitempty"`
AccessKeyID string `json:"access_key_id"`
SecretAccessKey string `json:"secret_access_key"`
SecurityToken string `json:"security_token"`
Expiration string `json:"expiration,omitempty"`
RefreshToken string `json:"refresh_token"`
CodeVerifier string `json:"code_verifier,omitempty"`
ClientID string `json:"client_id,omitempty"`
DPoPPrivateKey map[string]string `json:"dpop_private_key,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
}
Credential is the persisted CodeArts OAuth + STS record. client_id and dpop_private_key.d must survive refresh; refresh_token is one-time.
func ApplyRefresh ¶
func ApplyRefresh(prev Credential, tok TokenResponse) Credential
ApplyRefresh copies rotated STS + refresh_token onto prev while keeping client_id, code_verifier, and the DPoP private JWK (including d) unchanged.
func NewCredentialFromToken ¶
func NewCredentialFromToken(tok TokenResponse, verifier string, clientID string, dpop DPoPPrivateJWK) Credential
NewCredentialFromToken builds a persistable credential from a token response.
func ParseCredential ¶
func ParseCredential(raw []byte) (Credential, error)
ParseCredential decodes a persisted auth JSON object.
type DPoPPrivateJWK ¶
DPoPPrivateJWK is the P-256 private JWK persisted with the refresh_token.
func NewDPoPPrivateJWK ¶
func NewDPoPPrivateJWK() (DPoPPrivateJWK, error)
NewDPoPPrivateJWK generates a persistable ES256 P-256 private JWK.
type LegacyCreds ¶
type LegacyCreds struct {
Access string `json:"access"`
Secret string `json:"secret"`
SecurityToken string `json:"securitytoken"`
ExpiresAt string `json:"expires_at"`
}
LegacyCreds is the ticket-channel credential object.
type LoginConfig ¶
type LoginConfig struct {
ClientID string
PortalHost string
SnapManager string
STSHost string
RedirectPath string
PluginName string
PluginVersion string
}
LoginConfig is the Huawei OAuth/PKCE configuration.
func DefaultLoginConfig ¶
func DefaultLoginConfig() LoginConfig
DefaultLoginConfig matches the official CodeArts Agent plugin.
type ModelInfo ¶
type ModelInfo struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
ContextWindow int64 `json:"contextWindow,omitempty"`
MaxTokens int64 `json:"maxTokens,omitempty"`
Benefit bool `json:"benefit,omitempty"`
Desc string `json:"desc,omitempty"`
}
ModelInfo is a discovered model.
func AccountModels ¶
AccountModels returns a copy of one account catalog.
func DiscoverModels ¶
func DiscoverModels(client *http.Client, cred SignCredential, accountID string, snapBase, benefitBase string, claimBenefit bool) []ModelInfo
DiscoverModels fetches agent-center + builtin + benefit catalogs. Failures on individual sources are ignored; an empty merge stays empty.
func MergeModels ¶
MergeModels de-duplicates by lower(id); benefit is OR-ed.
type STSCreds ¶
type STSCreds struct {
AccessKeyID string `json:"access_key_id"`
SecretAccessKey string `json:"secret_access_key"`
SecurityToken string `json:"security_token"`
Expiration string `json:"expiration"`
}
STSCreds is the nested credentials object from oauth2/tokens.
type SignCredential ¶
SignCredential is the STS (or permanent) AK/SK used for SDK-HMAC-SHA256.
func SignCredentialFrom ¶
func SignCredentialFrom(c Credential) SignCredential
SignCredentialFrom returns HMAC material.
type SignOptions ¶
type SignOptions struct {
// Date, if non-zero, is used as X-Sdk-Date instead of time.Now.
Date time.Time
}
SignOptions controls deterministic signing for tests.
type TokenResponse ¶
type TokenResponse struct {
UserID string `json:"user_id"`
UserName string `json:"user_name"`
DomainID string `json:"domain_id"`
RefreshToken string `json:"refresh_token"`
Credentials STSCreds `json:"credentials"`
Credential LegacyCreds `json:"credential"`
Error string `json:"error"`
ErrorCode string `json:"error_code"`
ErrorMessage string `json:"error_msg"`
}
TokenResponse is the STS / oauth2/tokens JSON body.
func ParseTokenResponse ¶
func ParseTokenResponse(raw []byte) (TokenResponse, error)
ParseTokenResponse decodes an oauth2/tokens or ticket JSON body.
func (TokenResponse) HasSTS ¶
func (t TokenResponse) HasSTS() bool
HasSTS reports whether the response contains usable STS material.
func (*TokenResponse) Normalize ¶
func (t *TokenResponse) Normalize()
Normalize fills credentials from the legacy ticket object when needed.