Documentation
¶
Overview ¶
Package bydev는 데브 라이선스 API의 공식 Go SDK다.
디바이스 로그인 · refresh_token 회전 · 세션 리스(하트비트) · licenseToken 검증 · 업데이트 확인을 sdks/spec 동작 명세대로 한다. 의존성은 표준 라이브러리뿐이다(cgo 없음). 이용 가능 여부를 참/거짓 하나로 알리지 않는다 — 세션 상태와 검증된 토큰의 클레임을 쓴다.
Index ¶
- Constants
- Variables
- func AppDataDir(appName string) string
- func StateJSON(s SessionState) map[string]any
- type AccessClaims
- type Active
- type ActiveSession
- type AppInfo
- type Client
- func (c *Client) CheckForUpdate(ctx context.Context, target, currentVersion string) (*UpdateCheck, error)
- func (c *Client) Devices(ctx context.Context, cursor string, limit int) (*DevicePage, error)
- func (c *Client) Entitlement(ctx context.Context) (*Entitlement, error)
- func (c *Client) HasCredentials(ctx context.Context) (bool, error)
- func (c *Client) Logout(ctx context.Context) (bool, error)
- func (c *Client) Profile(ctx context.Context) (*Profile, error)
- func (c *Client) ReleaseDevice(ctx context.Context, deviceID string) (*DeviceRelease, error)
- func (c *Client) Session() (*Session, error)
- func (c *Client) StartLogin(ctx context.Context) (*LoginAttempt, error)
- func (c *Client) VerifyDownload(data []byte, sha string) error
- func (c *Client) VerifyToken(ctx context.Context, token string) (*LicenseClaims, error)
- type Clock
- type Config
- type CredentialRecord
- type CredentialStore
- func DPAPICredentialStore(path string) CredentialStore
- func DefaultCredentialStore(appName, account string, logger Logger) CredentialStore
- func FileCredentialStore(path string, logger Logger) CredentialStore
- func MemoryStore(initial *CredentialRecord) CredentialStore
- func SecretToolCredentialStore(account string) CredentialStore
- type Degraded
- type Device
- type DeviceInfo
- type DevicePage
- type DevicePlatform
- type DeviceRelease
- type DistributionTarget
- type EntitledUpdate
- type Entitlement
- type EntitlementStatus
- type EntitlementSubscription
- type EntitlementTerm
- type Error
- type ErrorView
- type ExternalChannel
- type FingerprintSource
- type GrantType
- type HTTPRequest
- type HTTPResponse
- type InstallMode
- type LatestVersion
- type LicenseClaims
- type LicensePolicy
- type LicenseTokenInfo
- type Locked
- type Logger
- type LoginAttempt
- type LoginResult
- type NeedsDecision
- type NeedsDecisionReason
- type Ports
- type ProductInstall
- type Profile
- type Random
- type Route
- type Scheduler
- type Scope
- type ServerVerifier
- type Session
- type SessionInfo
- type SessionState
- type SessionStateType
- type Starting
- type Stopped
- type SubscriptionStatus
- type Transport
- type UpdateCheck
- type UpdateCoverage
- type UpdateCoverageType
- type UpdateDecision
- type UpdateRelease
- type UpdateStatus
- type WebhookVerification
Constants ¶
const CodeAuthorizationPending = "AUTHORIZATION_PENDING"
const CodeConfiguration = "CONFIGURATION"
const CodeDeviceInUse = "DEVICE_IN_USE"
const CodeDeviceLimitExceeded = "DEVICE_LIMIT_EXCEEDED"
const CodeDeviceNotFound = "DEVICE_NOT_FOUND"
const CodeDeviceReleaseLimitExceeded = "DEVICE_RELEASE_LIMIT_EXCEEDED"
const CodeDownloadIntegrity = "DOWNLOAD_INTEGRITY"
const CodeEntitlementExpired = "ENTITLEMENT_EXPIRED"
const CodeEntitlementNotFound = "ENTITLEMENT_NOT_FOUND"
const CodeEntitlementRevoked = "ENTITLEMENT_REVOKED"
const CodeEntitlementSuspended = "ENTITLEMENT_SUSPENDED"
const CodeEntitlementVersionNotCovered = "ENTITLEMENT_VERSION_NOT_COVERED"
const CodeExpiredToken = "EXPIRED_TOKEN"
const CodeGenerationRegressed = "GENERATION_REGRESSED"
const CodeIdempotencyKeyConflict = "IDEMPOTENCY_KEY_CONFLICT"
const CodeInstanceAlreadyRunning = "INSTANCE_ALREADY_RUNNING"
const CodeInternalError = "INTERNAL_ERROR"
const CodeInvalidClient = "INVALID_CLIENT"
API 에러 코드 (contracts ERROR_CODES). 분기는 이 값으로 한다.
const CodeInvalidGrant = "INVALID_GRANT"
const CodeLoginCancelled = "LOGIN_CANCELLED"
const CodeNetworkError = "NETWORK_ERROR"
SDK 에러 코드 (명세 3.3).
const CodeNotSignedIn = "NOT_SIGNED_IN"
const CodeOfflineExpired = "OFFLINE_EXPIRED"
const CodeProductNotFound = "PRODUCT_NOT_FOUND"
const CodeProductSuspended = "PRODUCT_SUSPENDED"
const CodeProtocolError = "PROTOCOL_ERROR"
const CodeRateLimited = "RATE_LIMITED"
const CodeScopeInsufficient = "SCOPE_INSUFFICIENT"
const CodeSessionRevoked = "SESSION_REVOKED"
const CodeSessionSuperseded = "SESSION_SUPERSEDED"
const CodeSlowDown = "SLOW_DOWN"
const CodeStorageFailed = "STORAGE_FAILED"
const CodeTakeoverLimitExceeded = "TAKEOVER_LIMIT_EXCEEDED"
const CodeTestModeOnly = "TEST_MODE_ONLY"
const CodeTokenInvalid = "TOKEN_INVALID"
const CodeValidationFailed = "VALIDATION_FAILED"
const CodeWebhookInvalid = "WEBHOOK_INVALID"
const DeviceCodeGrantType = "urn:ietf:params:oauth:grant-type:device_code"
DeviceCodeGrantType은 RFC 8628 디바이스 코드 grant_type이다.
const RuleApi = "v1"
const RuleFingerprintAlgorithm = "SHA-256"
const RuleFingerprintEncoding = "hex-lower"
const RuleFingerprintSalt = "bydev-device-v1"
const RuleFingerprintSourceReadAttempts = 3
const RuleFingerprintSourceReadRetryDelayMs = 300
const RuleHttpTimeoutSec = 30
const RuleJwksDefaultMaxAgeSec = 300
const RuleJwksUnknownKidRefetchMinIntervalSec = 60
const RuleLoginPollJitterMax = 1.15
const RuleLoginPollJitterMin = 1.0
const RuleLoginSlowDownIncrementSec = 5
const RuleSessionHeartbeatJitterMax = 1.15
const RuleSessionHeartbeatJitterMin = 0.85
const RuleSpecVersion = "1.2.0"
규칙 (sdks/spec/rules.json).
const RuleStorageRecordVersion = 1
const RuleStorageService = "dev.developedby.sdk"
const RuleTokenClockLeewaySec = 60
const RuleTokenRefreshSkewSec = 60
const RuleUserAgentPattern = "^bydev-(typescript|dotnet|swift|kotlin|python|go|rust|c)/[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?( .+)?$"
const RuleWebhookSecretPrefix = "whsec_"
const RuleWebhookSignatureVersion = "v1"
const RuleWebhookToleranceSec = 300
const SDKVersion = "1.0.0"
SDKVersion은 User-Agent(bydev-go/<판>)에 실린다.
const SpecVersion = "1.2.0"
SpecVersion은 이 SDK가 따르는 동작 명세 판이다.
const UserAgent = "bydev-go/" + SDKVersion
UserAgent는 모든 요청에 싣는 값이다(명세 3.1).
Variables ¶
var APIErrorHTTPStatus = map[string]int{"INVALID_CLIENT": 401, "AUTHORIZATION_PENDING": 400, "SLOW_DOWN": 400, "EXPIRED_TOKEN": 401, "INVALID_GRANT": 400, "SCOPE_INSUFFICIENT": 403, "ENTITLEMENT_NOT_FOUND": 404, "ENTITLEMENT_EXPIRED": 403, "ENTITLEMENT_REVOKED": 403, "ENTITLEMENT_SUSPENDED": 403, "DEVICE_IN_USE": 409, "INSTANCE_ALREADY_RUNNING": 409, "DEVICE_LIMIT_EXCEEDED": 409, "SESSION_REVOKED": 401, "SESSION_SUPERSEDED": 401, "TAKEOVER_LIMIT_EXCEEDED": 429, "DEVICE_NOT_FOUND": 404, "DEVICE_RELEASE_LIMIT_EXCEEDED": 429, "PRODUCT_NOT_FOUND": 404, "PRODUCT_SUSPENDED": 403, "RATE_LIMITED": 429, "IDEMPOTENCY_KEY_CONFLICT": 409, "VALIDATION_FAILED": 400, "TEST_MODE_ONLY": 403, "INTERNAL_ERROR": 500, "ENTITLEMENT_VERSION_NOT_COVERED": 403}
APIErrorHTTPStatus는 API 에러 코드의 HTTP 상태다.
var KnownDevicePlatformValues = []DevicePlatform{DevicePlatformWindows, DevicePlatformMacos, DevicePlatformLinux, DevicePlatformAndroid, DevicePlatformIos, DevicePlatformOther}
KnownDevicePlatformValues는 이 판이 아는 DevicePlatform 값이다.
var KnownDistributionTargetValues = []DistributionTarget{DistributionTargetWindowsX64, DistributionTargetWindowsArm64, DistributionTargetMacosUniversal, DistributionTargetMacosArm64, DistributionTargetMacosX64, DistributionTargetLinuxX64, DistributionTargetLinuxArm64, DistributionTargetBrowserExtension, DistributionTargetAndroid, DistributionTargetIos, DistributionTargetSourceArchive}
KnownDistributionTargetValues는 이 판이 아는 DistributionTarget 값이다.
var KnownEntitlementStatusValues = []EntitlementStatus{EntitlementStatusActive, EntitlementStatusExpired, EntitlementStatusSuspended, EntitlementStatusRevoked}
KnownEntitlementStatusValues는 이 판이 아는 EntitlementStatus 값이다.
var KnownGrantTypeValues = []GrantType{GrantTypePurchase, GrantTypeRenewal, GrantTypeTrial, GrantTypeCompensation, GrantTypeManual, GrantTypeTest}
KnownGrantTypeValues는 이 판이 아는 GrantType 값이다.
var KnownInstallModeValues = []InstallMode{InstallModeHosted, InstallModeExternal}
KnownInstallModeValues는 이 판이 아는 InstallMode 값이다.
var KnownNeedsDecisionReasonValues = []NeedsDecisionReason{NeedsDecisionReasonDeviceInUse, NeedsDecisionReasonInstanceAlreadyRunning, NeedsDecisionReasonDeviceLimitExceeded}
KnownNeedsDecisionReasonValues는 이 판이 아는 NeedsDecisionReason 값이다.
var KnownScopeValues = []Scope{ScopeEntitlementRead, ScopeSessionWrite, ScopeDeviceManage, ScopeProfileRead, ScopeProfileEmail, ScopeVersionRead}
KnownScopeValues는 이 판이 아는 Scope 값이다.
var KnownSessionStateTypeValues = []SessionStateType{SessionStateTypeStarting, SessionStateTypeActive, SessionStateTypeDegraded, SessionStateTypeNeedsdecision, SessionStateTypeLocked, SessionStateTypeStopped}
KnownSessionStateTypeValues는 이 판이 아는 SessionStateType 값이다.
var KnownSubscriptionStatusValues = []SubscriptionStatus{SubscriptionStatusActive, SubscriptionStatusPastDue, SubscriptionStatusCancelScheduled, SubscriptionStatusUnpaid, SubscriptionStatusExpired}
KnownSubscriptionStatusValues는 이 판이 아는 SubscriptionStatus 값이다.
var KnownUpdateCoverageTypeValues = []UpdateCoverageType{UpdateCoverageTypeAll, UpdateCoverageTypeUntil}
KnownUpdateCoverageTypeValues는 이 판이 아는 UpdateCoverageType 값이다.
var KnownUpdateStatusValues = []UpdateStatus{UpdateStatusUpToDate, UpdateStatusAvailable, UpdateStatusRequired}
KnownUpdateStatusValues는 이 판이 아는 UpdateStatus 값이다.
var RouteAcquireSession = Route{Method: "POST", Path: "/v1/sessions"}
공개 API 경로.
var RouteExchangeToken = Route{Method: "POST", Path: "/v1/oauth/token"}
var RouteGetJwks = Route{Method: "GET", Path: "/.well-known/jwks.json"}
var RouteGetLatestRelease = Route{Method: "GET", Path: "/v1/products/{id}/latest"}
var RouteGetMyEntitlement = Route{Method: "GET", Path: "/v1/entitlements/me"}
var RouteGetOpenIdConfiguration = Route{Method: "GET", Path: "/.well-known/openid-configuration"}
var RouteGetProductUpdates = Route{Method: "GET", Path: "/v1/products/{id}/updates"}
var RouteGetProfile = Route{Method: "GET", Path: "/v1/profile"}
var RouteHeartbeatSession = Route{Method: "POST", Path: "/v1/sessions/{sid}/heartbeat"}
var RouteIssueDeviceCode = Route{Method: "POST", Path: "/v1/oauth/device_code"}
var RouteListDevices = Route{Method: "GET", Path: "/v1/devices"}
var RouteReleaseDevice = Route{Method: "DELETE", Path: "/v1/devices/{deviceId}"}
var RouteReleaseSession = Route{Method: "DELETE", Path: "/v1/sessions/{sid}"}
var RouteRevokeToken = Route{Method: "POST", Path: "/v1/oauth/revoke"}
var RuleNeedsDecisionReasons = []string{"DEVICE_IN_USE", "INSTANCE_ALREADY_RUNNING", "DEVICE_LIMIT_EXCEEDED"}
var RuleSdkErrorCodes = []string{"NETWORK_ERROR", "PROTOCOL_ERROR", "STORAGE_FAILED", "NOT_SIGNED_IN", "TOKEN_INVALID", "GENERATION_REGRESSED", "OFFLINE_EXPIRED", "DOWNLOAD_INTEGRITY", "LOGIN_CANCELLED", "CONFIGURATION", "WEBHOOK_INVALID"}
var RuleSessionStartRetryDelaysSec = []float64{2.0, 5.0, 10.0, 30.0, 60.0}
var RuleSessionStates = []string{"Starting", "Active", "Degraded", "NeedsDecision", "Locked", "Stopped"}
var RuleTokenRefreshRetryDelaysSec = []float64{1.0, 3.0, 7.0}
var RuleTransientCodes = []string{"NETWORK_ERROR", "RATE_LIMITED", "INTERNAL_ERROR"}
var RuleTransientUnknownCodeStatusRanges = [][2]int{{500, 599}}
var RuleTransientUnknownCodeStatuses = []int{429}
var RuleUserAgentLanguages = []string{"typescript", "dotnet", "swift", "kotlin", "python", "go", "rust", "c"}
var SDKErrorCodes = []string{"NETWORK_ERROR", "PROTOCOL_ERROR", "STORAGE_FAILED", "NOT_SIGNED_IN", "TOKEN_INVALID", "GENERATION_REGRESSED", "OFFLINE_EXPIRED", "DOWNLOAD_INTEGRITY", "LOGIN_CANCELLED", "CONFIGURATION", "WEBHOOK_INVALID"}
SDKErrorCodes는 SDK가 만드는 에러 코드 목록이다.
Functions ¶
func StateJSON ¶
func StateJSON(s SessionState) map[string]any
StateJSON은 상태를 {"type": …, 필드…} 모양으로 쓴다.
Types ¶
type AccessClaims ¶
type AccessClaims struct {
Iss string `json:"iss"`
Sub string `json:"sub"`
Aud string `json:"aud"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
Jti string `json:"jti"`
}
AccessClaims는 검증된 access_token 클레임이다(명세 12절).
type Active ¶
type Active struct {
Session SessionInfo `json:"session"`
LicenseToken LicenseTokenInfo `json:"licenseToken"`
Claims LicenseClaims `json:"claims"`
}
Active는 세션을 들고 있다. 앱은 Claims로 기능을 연다.
type ActiveSession ¶
type ActiveSession struct {
DeviceID string `json:"deviceId"`
DeviceName string `json:"deviceName"`
LastSeenAt string `json:"lastSeenAt"`
}
ActiveSession은 다른 곳에서 쓰는 세션이다.
type AppInfo ¶
AppInfo는 실행 중인 앱이다(명세 1절 · ADR-0049) — 배포 대상(CheckForUpdate의 target과 같은 값)과 콘솔에 업로드한 버전 문자열. 세션 획득에 싣는다. 업데이트 제공 기한이 있는 영구 이용권은 이 값이 없으면 획득이 ENTITLEMENT_VERSION_NOT_COVERED로 거절된다.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client는 데브 라이선스 API 클라이언트다. 서버 응답 하나의 참/거짓으로 기능을 열지 않는다 — Session().State()와 검증된 토큰의 클레임을 쓴다.
func (*Client) CheckForUpdate ¶
func (c *Client) CheckForUpdate(ctx context.Context, target, currentVersion string) (*UpdateCheck, error)
CheckForUpdate는 업데이트 확인이다. Update.Status가 REQUIRED면 업데이트 전까지 실행을 막는다. 받은 파일은 설치 전에 VerifyDownload. Entitled가 있으면 Latest · Update · Install 대신 Entitled.Release를 따른다 — 범위 밖 버전을 설치하면 세션 획득이 거절된다.
func (*Client) Entitlement ¶
func (c *Client) Entitlement(ctx context.Context) (*Entitlement, error)
Entitlement는 이 제품의 이용권이다.
func (*Client) HasCredentials ¶
HasCredentials는 저장된 로그인이 있는지다 — 이용 가능 여부가 아니다.
func (*Client) ReleaseDevice ¶
ReleaseDevice는 기기를 해제한다(월 횟수 제한).
func (*Client) StartLogin ¶
func (c *Client) StartLogin(ctx context.Context) (*LoginAttempt, error)
StartLogin은 디바이스 로그인을 시작한다(명세 5절). 진행 중인 로그인은 취소한다.
func (*Client) VerifyDownload ¶
VerifyDownload는 내려받은 파일의 SHA-256을 확인한다 — 다르면 DOWNLOAD_INTEGRITY.
func (*Client) VerifyToken ¶
VerifyToken은 licenseToken을 검증한다(명세 9절) — 앱이 기능 코드 여러 곳에서 다시 검증할 때.
type Clock ¶
Clock은 지금 시각이다.
var SystemClock Clock = systemClock{}
SystemClock은 시스템 시계다 — SDK에서 시계를 직접 읽는 유일한 곳.
type Config ¶
type Config struct {
BaseURL string
ClientID string
ProductID string
Scopes []string
// Device는 세션을 쓰면 필요하다.
Device *DeviceInfo
// App은 실행 중인 앱의 배포 대상 · 버전이다 — 세션을 쓰면 넣는다(명세 1절 · ADR-0049).
App *AppInfo
Ports Ports
}
Config는 명세 1절의 설정이다.
type CredentialRecord ¶
type CredentialRecord struct {
Version int `json:"version"`
RefreshToken string `json:"refreshToken"`
Scope string `json:"scope"`
SavedAt string `json:"savedAt"`
}
CredentialRecord는 보안 저장소에 두는 기록이다(명세 3.6). access_token은 두지 않는다.
type CredentialStore ¶
type CredentialStore interface {
Load(ctx context.Context) (*CredentialRecord, error)
Save(ctx context.Context, record CredentialRecord) error
Clear(ctx context.Context) error
}
CredentialStore는 로그인 기록을 둔다. 없으면 Load가 nil을 돌려준다.
func DPAPICredentialStore ¶
func DPAPICredentialStore(path string) CredentialStore
DPAPICredentialStore는 Windows DPAPI(사용자 범위)로 암호화한 파일이다 — PowerShell에 표준 입력으로 넘긴다. 다른 Windows 사용자는 풀 수 없다.
func DefaultCredentialStore ¶
func DefaultCredentialStore(appName, account string, logger Logger) CredentialStore
DefaultCredentialStore는 운영체제에 맞는 기본 저장소다 — Windows DPAPI 파일 · Linux Secret Service(secret-tool이 없으면 0600 파일 + warn) · macOS는 cgo 없이 키체인을 안전하게 쓸 길이 없어(security 명령은 비밀을 인자로 받고, 그 명령이 만든 항목은 다른 프로세스도 security로 읽는다) 0600 파일 + warn. account는 clientId.
func FileCredentialStore ¶
func FileCredentialStore(path string, logger Logger) CredentialStore
FileCredentialStore는 사용자 전용 권한(0600) 파일이다 — **암호화하지 않는다.** 같은 사용자로 도는 프로그램은 읽을 수 있다. 운영체제 보안 저장소를 쓸 수 없을 때만(명세 2절 — warn 로그).
func MemoryStore ¶
func MemoryStore(initial *CredentialRecord) CredentialStore
MemoryStore는 메모리 저장소다 — 앱을 끄면 로그인이 사라진다. 시험 · 짧은 CLI용.
func SecretToolCredentialStore ¶
func SecretToolCredentialStore(account string) CredentialStore
SecretToolCredentialStore는 Linux Secret Service(libsecret secret-tool)다 — 비밀은 표준 입력으로 넘긴다. account는 clientId.
type Degraded ¶
type Degraded struct {
Active
ConsecutiveFailures int `json:"consecutiveFailures"`
OfflineUntil string `json:"offlineUntil"`
LastError *ErrorView `json:"lastError"`
}
Degraded는 하트비트가 일시적으로 실패 중이다. OfflineUntil까지는 계속 써도 된다.
type Device ¶
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Platform DevicePlatform `json:"platform"`
RegisteredAt string `json:"registeredAt"`
LastSeenAt string `json:"lastSeenAt"`
}
Device는 등록된 기기다.
type DeviceInfo ¶
DeviceInfo는 세션 획득 때 보내는 기기 정보다.
func SystemDeviceInfo ¶
func SystemDeviceInfo() DeviceInfo
SystemDeviceInfo는 Config.Device의 기본값이다 — 호스트 이름(64자까지)과 운영체제.
type DevicePage ¶
DevicePage는 기기 목록 한 쪽이다. NextCursor가 nil이면 마지막 쪽이다.
type DevicePlatform ¶
type DevicePlatform string
DevicePlatform는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const DevicePlatformAndroid DevicePlatform = "ANDROID"
const DevicePlatformIos DevicePlatform = "IOS"
const DevicePlatformLinux DevicePlatform = "LINUX"
const DevicePlatformMacos DevicePlatform = "MACOS"
const DevicePlatformOther DevicePlatform = "OTHER"
const DevicePlatformWindows DevicePlatform = "WINDOWS"
DevicePlatform 값.
type DeviceRelease ¶
type DeviceRelease struct {
ID string `json:"id"`
Status string `json:"status"`
ReleasedAt string `json:"releasedAt"`
}
DeviceRelease는 기기 해제 결과다.
type DistributionTarget ¶
type DistributionTarget string
DistributionTarget는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const DistributionTargetAndroid DistributionTarget = "ANDROID"
const DistributionTargetBrowserExtension DistributionTarget = "BROWSER_EXTENSION"
const DistributionTargetIos DistributionTarget = "IOS"
const DistributionTargetLinuxArm64 DistributionTarget = "LINUX_ARM64"
const DistributionTargetLinuxX64 DistributionTarget = "LINUX_X64"
const DistributionTargetMacosArm64 DistributionTarget = "MACOS_ARM64"
const DistributionTargetMacosUniversal DistributionTarget = "MACOS_UNIVERSAL"
const DistributionTargetMacosX64 DistributionTarget = "MACOS_X64"
const DistributionTargetSourceArchive DistributionTarget = "SOURCE_ARCHIVE"
const DistributionTargetWindowsArm64 DistributionTarget = "WINDOWS_ARM64"
const DistributionTargetWindowsX64 DistributionTarget = "WINDOWS_X64"
DistributionTarget 값.
type EntitledUpdate ¶
type EntitledUpdate struct {
CoveredUntil string `json:"coveredUntil"`
Release *UpdateRelease `json:"release"`
}
EntitledUpdate는 업데이트 제공 기한이 있는 구매자에게만 오는 값이다(ADR-0049 4절). 있으면 앱은 최상위 대신 Release를 따른다 — 최상위 최신은 그 구매자가 실행할 수 없는 버전일 수 있다. 이 대상에 범위 안 버전이 없으면 Release는 nil이다.
type Entitlement ¶
type Entitlement struct {
ID string `json:"id"`
ProductID string `json:"productId"`
Status EntitlementStatus `json:"status"`
Term EntitlementTerm `json:"term"`
UpdateCoverage UpdateCoverage `json:"updateCoverage"`
Subscription *EntitlementSubscription `json:"subscription"`
Policy LicensePolicy `json:"policy"`
EvaluatedAt string `json:"evaluatedAt"`
}
Entitlement는 이 제품의 이용권이다.
type EntitlementStatus ¶
type EntitlementStatus string
EntitlementStatus는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const EntitlementStatusActive EntitlementStatus = "ACTIVE"
EntitlementStatus 값.
const EntitlementStatusExpired EntitlementStatus = "EXPIRED"
const EntitlementStatusRevoked EntitlementStatus = "REVOKED"
const EntitlementStatusSuspended EntitlementStatus = "SUSPENDED"
type EntitlementSubscription ¶
type EntitlementSubscription struct {
ID string `json:"id"`
Status SubscriptionStatus `json:"status"`
WillRenew bool `json:"willRenew"`
NextBillingAt *string `json:"nextBillingAt"`
GraceEndsAt *string `json:"graceEndsAt"`
}
EntitlementSubscription은 구독형일 때만 있다.
type EntitlementTerm ¶
type EntitlementTerm struct {
Type string `json:"type"`
ExpiresAt *string `json:"expiresAt"`
RemainingDays *int `json:"remainingDays"`
RemainingSeconds *int `json:"remainingSeconds"`
}
EntitlementTerm은 기간이다. Type을 먼저 분기한다 — 영구(PERPETUAL)는 잔여 필드가 nil이다.
type Error ¶
type Error struct {
Code string
Message string
HTTPStatus int // 0이면 없음
CorrelationID string
RetryAfterSec int // 0이면 없음
Details map[string]any
// contains filtered or unexported fields
}
Error는 SDK의 에러 하나다(명세 3.3). Code로 분기하고 Message는 보여 주기만 한다. 앱의 오류 화면에 CorrelationID를 보이면 문의를 바로 찾는다.
type ErrorView ¶
type ErrorView struct {
Code string `json:"code"`
Message string `json:"message"`
HTTPStatus *int `json:"httpStatus"`
CorrelationID *string `json:"correlationId"`
RetryAfterSec *int `json:"retryAfterSec"`
Details map[string]any `json:"details"`
}
ErrorView는 상태에 싣는 에러다.
type ExternalChannel ¶
ExternalChannel은 외부 채널의 설치 위치다.
type FingerprintSource ¶
FingerprintSource는 운영체제의 기기 식별자다. 없으면 ""를 돌려준다 — 원본은 SDK 밖으로 나가지 않는다(해시만, 명세 10절).
func OSFingerprintSource ¶
func OSFingerprintSource(installIDFile string) FingerprintSource
OSFingerprintSource는 명세 10절 · 2절 표의 지문 출처다 — Windows MachineGuid · macOS IOPlatformUUID · Linux /etc/machine-id. 읽지 못하면 installIDFile의 설치 ID(없으면 만든다). installIDFile이 ""면 ""를 돌려준다(SDK가 클라이언트 수명 동안의 난수 ID로 물러난다).
type GrantType ¶
type GrantType string
GrantType는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const GrantTypeCompensation GrantType = "COMPENSATION"
const GrantTypeManual GrantType = "MANUAL"
const GrantTypePurchase GrantType = "PURCHASE"
GrantType 값.
const GrantTypeRenewal GrantType = "RENEWAL"
const GrantTypeTest GrantType = "TEST"
const GrantTypeTrial GrantType = "TRIAL"
type HTTPRequest ¶
HTTPRequest는 전송 포트가 보낼 요청이다. Body가 nil이면 본문이 없다.
type HTTPResponse ¶
HTTPResponse는 받은 응답이다. Header 이름은 소문자다.
type InstallMode ¶
type InstallMode string
InstallMode는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const InstallModeExternal InstallMode = "EXTERNAL"
const InstallModeHosted InstallMode = "HOSTED"
InstallMode 값.
type LatestVersion ¶
type LatestVersion struct {
Version string `json:"version"`
ReleasedAt string `json:"releasedAt"`
Notes *string `json:"notes"`
}
LatestVersion은 최신 버전이다.
type LicenseClaims ¶
type LicenseClaims struct {
Iss string `json:"iss"`
Sub string `json:"sub"`
Aud string `json:"aud"`
ProductID string `json:"product_id"`
DeviceID string `json:"device_id"`
Sid string `json:"sid"`
Generation int `json:"generation"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
// BuildID는 세션을 얻을 때 앱이 보낸 대상 · 버전(Config.App)으로 서버가 확정한 빌드다(ADR-0049). 확정하지 못했으면 nil.
BuildID *string `json:"build_id,omitempty"`
}
LicenseClaims는 검증된 licenseToken 클레임이다(명세 9절).
type LicensePolicy ¶
type LicensePolicy struct {
MaxDevices int `json:"maxDevices"`
MaxConcurrent int `json:"maxConcurrent"`
HeartbeatSec int `json:"heartbeatSec"`
OfflineGraceHours int `json:"offlineGraceHours"`
}
LicensePolicy는 판매자가 정한 정책 수치다 — 앱에 하드코딩하지 않는다.
type LicenseTokenInfo ¶
LicenseTokenInfo는 세션 보유 증명 JWT와 그 만료(오프라인 유예의 끝)다.
type Locked ¶
type Locked struct {
Code string `json:"code"`
Message string `json:"message"`
CorrelationID *string `json:"correlationId"`
Details map[string]any `json:"details"`
Retrying bool `json:"retrying"`
}
Locked는 쓰면 안 된다. Retrying이 참(OFFLINE_EXPIRED)이면 연결이 돌아올 때 스스로 풀린다.
type Logger ¶
type Logger interface {
Debug(msg string, kv ...any)
Info(msg string, kv ...any)
Warn(msg string, kv ...any)
}
Logger에는 토큰 · 지문 출처 값을 넘기지 않는다.
type LoginAttempt ¶
type LoginAttempt struct {
UserCode string
VerificationURI string
VerificationURIComplete string
ExpiresAt string
// contains filtered or unexported fields
}
LoginAttempt는 디바이스 플로우 하나다(명세 5절). 코드를 받은 순간부터 폴링하고 Wait는 그 결과를 기다린다.
func (*LoginAttempt) Cancel ¶
func (l *LoginAttempt) Cancel()
Cancel은 로그인을 취소한다 — Wait는 LOGIN_CANCELLED로 끝난다.
func (*LoginAttempt) Wait ¶
func (l *LoginAttempt) Wait(ctx context.Context) (*LoginResult, error)
Wait는 로그인이 끝나기를 기다린다.
type LoginResult ¶
type LoginResult struct {
Scope string `json:"scope"`
}
LoginResult는 로그인이 끝났을 때 받은 스코프다.
type NeedsDecision ¶
type NeedsDecision struct {
Reason NeedsDecisionReason `json:"reason"`
ActiveSession *ActiveSession `json:"activeSession"`
MaxDevices *int `json:"maxDevices"`
CorrelationID *string `json:"correlationId"`
}
NeedsDecision은 사용자가 골라야 한다 — DEVICE_IN_USE · INSTANCE_ALREADY_RUNNING이면 TakeOver, DEVICE_LIMIT_EXCEEDED면 기기 해제 뒤 Retry.
func (NeedsDecision) Type ¶
func (NeedsDecision) Type() string
type NeedsDecisionReason ¶
type NeedsDecisionReason string
NeedsDecisionReason는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const NeedsDecisionReasonDeviceInUse NeedsDecisionReason = "DEVICE_IN_USE"
NeedsDecisionReason 값.
const NeedsDecisionReasonDeviceLimitExceeded NeedsDecisionReason = "DEVICE_LIMIT_EXCEEDED"
const NeedsDecisionReasonInstanceAlreadyRunning NeedsDecisionReason = "INSTANCE_ALREADY_RUNNING"
type Ports ¶
type Ports struct {
Transport Transport
Store CredentialStore
Clock Clock
Scheduler Scheduler
Random Random
Fingerprint FingerprintSource
Logger Logger
}
Ports는 클라이언트가 쓰는 포트 묶음이다. 비운 칸은 기본 구현이다.
type ProductInstall ¶
type ProductInstall struct {
Mode InstallMode `json:"mode"`
BuildID string `json:"buildId,omitempty"`
DownloadURL string `json:"downloadUrl,omitempty"`
DownloadURLExpiresAt string `json:"downloadUrlExpiresAt,omitempty"`
SHA256 string `json:"sha256,omitempty"`
SizeBytes int `json:"sizeBytes,omitempty"`
Channels []ExternalChannel `json:"channels,omitempty"`
}
ProductInstall은 설치 방법이다. Mode가 HOSTED면 내려받기 필드, EXTERNAL이면 Channels가 있다. 모르는 방식이면 Mode만 있다.
func (ProductInstall) MarshalJSON ¶
func (p ProductInstall) MarshalJSON() ([]byte, error)
MarshalJSON은 방식마다 그 방식의 필드만 쓴다(계약의 판별 유니온 모양).
type Profile ¶
type Profile struct {
PseudonymousID string `json:"pseudonymousId"`
Nickname string `json:"nickname"`
Email *string `json:"email"`
}
Profile은 닉네임과 가명 식별자다. PseudonymousID를 판매자 쪽 고객 키로 쓴다.
type Random ¶
Random은 [0, 1) 실수와 UUID v4다.
var CryptoRandom Random = cryptoRandom{}
CryptoRandom은 crypto/rand 기반 난수다.
type Scheduler ¶
type Scheduler interface {
AfterFunc(d time.Duration, task func()) (cancel func())
Sleep(ctx context.Context, d time.Duration) error
Wait(ctx context.Context, done <-chan struct{}) error
}
Scheduler는 나중 작업 · 기다림이다. SDK가 시간이나 다른 작업을 기다리는 곳은 모두 Sleep · Wait를 거친다(명세 2절 — 블로킹 언어).
var TimerScheduler Scheduler = timerScheduler{}
TimerScheduler는 time.AfterFunc 기반 스케줄러다.
type Scope ¶
type Scope string
Scope는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const ScopeDeviceManage Scope = "device.manage"
const ScopeEntitlementRead Scope = "entitlement.read"
Scope 값.
const ScopeProfileEmail Scope = "profile.email"
const ScopeProfileRead Scope = "profile.read"
const ScopeSessionWrite Scope = "session.write"
const ScopeVersionRead Scope = "version.read"
type ServerVerifier ¶
type ServerVerifier struct {
// contains filtered or unexported fields
}
ServerVerifier는 판매자 서버의 토큰 검증이다(안내서 09장) — JWKS를 받아 캐시한다.
func NewServerVerifier ¶
func NewServerVerifier(baseURL, clientID string, transport Transport, clock Clock) *ServerVerifier
NewServerVerifier는 서버 검증기를 만든다. transport · clock이 nil이면 기본 구현.
func (*ServerVerifier) VerifyAccessToken ¶
func (s *ServerVerifier) VerifyAccessToken(ctx context.Context, token string) (*AccessClaims, error)
VerifyAccessToken은 access_token(at+jwt)을 검증한다.
func (*ServerVerifier) VerifyLicenseToken ¶
func (s *ServerVerifier) VerifyLicenseToken(ctx context.Context, token string, minGeneration int) (*LicenseClaims, error)
VerifyLicenseToken은 licenseToken을 검증한다. minGeneration — 같은 sub · device_id에서 이미 본 가장 큰 세대번호(0이면 보지 않는다).
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session은 라이선스 세션(실행 리스)이다. Start · TakeOver · Retry · Stop과 상태 구독.
func (*Session) Retry ¶
func (s *Session) Retry()
Retry는 NeedsDecision(기기 수) 또는 스스로 풀리지 않는 Locked에서 다시 얻는다.
func (*Session) Subscribe ¶
func (s *Session) Subscribe(listener func(SessionState)) func()
Subscribe는 상태가 바뀔 때마다 부른다. 돌려준 함수로 끊는다.
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"id"`
ProductID string `json:"productId"`
DeviceID string `json:"deviceId"`
Generation int `json:"generation"`
LeaseExpiresAt string `json:"leaseExpiresAt"`
HeartbeatSec int `json:"heartbeatSec"`
}
SessionInfo는 세션(실행 리스)이다.
type SessionState ¶
type SessionState interface{ Type() string }
SessionState는 세션 상태다. Type()으로 분기한다 — Starting · Active · Degraded · NeedsDecision · Locked · Stopped.
type SessionStateType ¶
type SessionStateType string
SessionStateType는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const SessionStateTypeActive SessionStateType = "Active"
const SessionStateTypeDegraded SessionStateType = "Degraded"
const SessionStateTypeLocked SessionStateType = "Locked"
const SessionStateTypeNeedsdecision SessionStateType = "NeedsDecision"
const SessionStateTypeStarting SessionStateType = "Starting"
SessionStateType 값.
const SessionStateTypeStopped SessionStateType = "Stopped"
type SubscriptionStatus ¶
type SubscriptionStatus string
SubscriptionStatus는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const SubscriptionStatusActive SubscriptionStatus = "ACTIVE"
SubscriptionStatus 값.
const SubscriptionStatusCancelScheduled SubscriptionStatus = "CANCEL_SCHEDULED"
const SubscriptionStatusExpired SubscriptionStatus = "EXPIRED"
const SubscriptionStatusPastDue SubscriptionStatus = "PAST_DUE"
const SubscriptionStatusUnpaid SubscriptionStatus = "UNPAID"
type Transport ¶
type Transport interface {
Send(ctx context.Context, req HTTPRequest) (HTTPResponse, error)
}
Transport는 요청을 보낸다. 연결 실패 · 시간 초과는 NETWORK_ERROR *Error로 돌려준다. 3xx를 따라가지 않는다.
func HTTPTransport ¶
HTTPTransport는 net/http 기반 전송이다. 리다이렉트를 따라가지 않는다.
type UpdateCheck ¶
type UpdateCheck struct {
Product struct {
ID string `json:"id"`
} `json:"product"`
Target DistributionTarget `json:"target"`
Latest LatestVersion `json:"latest"`
Update UpdateDecision `json:"update"`
Install ProductInstall `json:"install"`
// Entitled는 업데이트 제공 기한이 있는 구매자에게만 있다. 없으면 nil.
Entitled *EntitledUpdate `json:"entitled,omitempty"`
}
UpdateCheck는 업데이트 확인 결과다. Update.Status가 REQUIRED면 업데이트 전까지 실행을 막는다. Entitled가 있으면 Latest · Update · Install 대신 Entitled.Release를 따른다.
type UpdateCoverage ¶
type UpdateCoverage struct {
Type UpdateCoverageType `json:"type"`
Until string `json:"until,omitempty"`
}
UpdateCoverage는 업데이트 제공 범위다(ADR-0049). Type을 먼저 분기한다 — UNTIL이면 Until 전에 출시된 버전을 실행할 수 있다. 모르는 Type이면 Type만 있다(명세 0절 5).
type UpdateCoverageType ¶
type UpdateCoverageType string
UpdateCoverageType는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const UpdateCoverageTypeAll UpdateCoverageType = "ALL"
UpdateCoverageType 값.
const UpdateCoverageTypeUntil UpdateCoverageType = "UNTIL"
type UpdateDecision ¶
type UpdateDecision struct {
Status UpdateStatus `json:"status"`
}
UpdateDecision은 업데이트 판정이다. Status가 REQUIRED면 업데이트 전까지 실행을 막는다.
type UpdateRelease ¶
type UpdateRelease struct {
Latest LatestVersion `json:"latest"`
Update UpdateDecision `json:"update"`
Install ProductInstall `json:"install"`
}
UpdateRelease는 최신 버전 · 업데이트 판정 · 설치 방법이다 — UpdateCheck의 최상위와 EntitledUpdate.Release가 같은 모양이다.
type UpdateStatus ¶
type UpdateStatus string
UpdateStatus는 열린 열거다 — 모르는 값도 그대로 담는다(명세 0절 5).
const UpdateStatusAvailable UpdateStatus = "AVAILABLE"
const UpdateStatusRequired UpdateStatus = "REQUIRED"
const UpdateStatusUpToDate UpdateStatus = "UP_TO_DATE"
UpdateStatus 값.
type WebhookVerification ¶
WebhookVerification은 검증된 웹훅의 id와 시각이다. 중복 수신은 ID로 거른다.
func VerifyWebhook ¶
func VerifyWebhook(secrets []string, header http.Header, rawBody []byte, clock Clock) (*WebhookVerification, error)
VerifyWebhook은 웹훅 서명을 검증한다(안내서 11장 · Standard Webhooks v1). rawBody는 받은 그대로의 본문이다 — 파싱했다가 다시 만든 바이트는 서명이 맞지 않는다. 시크릿을 교체하는 중이면 둘 다 넘긴다. clock이 nil이면 시스템 시계.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
conformance-harness
command
conformance-harness는 Go SDK의 적합성 하네스다(sdks/spec/harness-protocol.md).
|
conformance-harness는 Go SDK의 적합성 하네스다(sdks/spec/harness-protocol.md). |
|
os-check
command
os-check는 운영체제 포트의 실제 확인이다 — Windows · Linux 기기에서 돌린다(launch-checklist A31 · ADR-0040 ⚠ 20).
|
os-check는 운영체제 포트의 실제 확인이다 — Windows · Linux 기기에서 돌린다(launch-checklist A31 · ADR-0040 ⚠ 20). |