-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
352 lines (320 loc) · 10.4 KB
/
Copy pathclient.go
File metadata and controls
352 lines (320 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package simple
import (
"context"
"fmt"
"net/url"
"strings"
"sync"
"github.com/systemlocker/system-locker-simple-go/slhwid"
)
const (
authPath = "/auth"
variablePath = "/auth/variable"
)
// Expiration is the outcome of a key-expiration lookup.
type Expiration struct {
// Permanent keys never expire ("Never").
Permanent bool
// ExpiresAt is the formatted UTC expiry string (for example
// "2026-08-15 12:00:00 UTC"). Empty for permanent keys.
ExpiresAt string
}
// VariableValue is the outcome of a variable lookup.
type VariableValue struct {
// Found is false when the variable is missing, protected, or the key
// check failed.
Found bool
// Value is the variable contents when Found.
Value string
}
// ResetOutcome is the outcome of an HWID reset request.
type ResetOutcome uint8
const (
// ResetGranted: the HWID was cleared.
ResetGranted ResetOutcome = iota
// ResetDenied: self-service resets are disabled for the system (or the
// key is not eligible).
ResetDenied
// ResetTooSoon: the 30-day cooldown is still running.
ResetTooSoon
)
func (o ResetOutcome) String() string {
switch o {
case ResetGranted:
return "granted"
case ResetDenied:
return "denied"
case ResetTooSoon:
return "tooSoon"
default:
return "unknown"
}
}
// Client performs stateless Simple checks. One Client per system; safe for
// concurrent use.
type Client struct {
config Config
http HTTPClient
mutex sync.Mutex
slhwidSession slhwidSession
}
// slhwidSession is the slice of the SL-HWID session the client needs; the
// indirection keeps the module swappable in tests without exposing test
// hooks publicly.
type slhwidSession interface {
HWID() string
Commit() error
}
// slHwidPrepare is swappable so tests can drive the SL-HWID module without
// touching real hardware or storage.
var slHwidPrepare = func(opts slhwid.Options) (slhwidSession, error) {
return slhwid.Prepare(opts)
}
// Option customizes NewClient.
type Option func(*Client)
// WithHTTPClient injects a custom transport (tests, proxies).
func WithHTTPClient(http HTTPClient) Option {
return func(c *Client) { c.http = http }
}
// NewClient validates the configuration and returns a ready Client.
func NewClient(config Config, options ...Option) (*Client, error) {
if config.HWIDMode != "" && config.HWIDMode != "legacy" && config.HWIDMode != "sl-hwid" {
return nil, configurationError("HWIDMode must be \"legacy\" or \"sl-hwid\".")
}
if err := resolveDefaultHWID(&config); err != nil {
return nil, configurationError("Could not derive the default hardware ID: %v. Supply a custom HWID or use \"1\" to disable device checks.", err)
}
if config.SystemID == "" {
return nil, configurationError("System ID must not be empty.")
}
if config.Version == "" {
return nil, configurationError("Version must not be empty.")
}
if !strings.HasPrefix(config.BaseURL, "https://") {
return nil, configurationError("Base URL must use HTTPS.")
}
client := &Client{config: config.clone()}
for _, option := range options {
option(client)
}
if client.http == nil {
client.http = NewDefaultHTTPClient(config.RequestTimeout, config.UserAgent)
}
return client, nil
}
// Config returns the configuration.
func (c *Client) Config() Config { return c.config.clone() }
func (c *Client) endpoint(path string) string {
if strings.HasSuffix(c.config.BaseURL, "/") {
return c.config.BaseURL[:len(c.config.BaseURL)-1] + path
}
return c.config.BaseURL + path
}
// request performs one POST and returns the trimmed body plus headers.
func (c *Client) request(ctx context.Context, path string, fields url.Values) (string, HTTPResponse, error) {
response := c.http.PostForm(ctx, c.endpoint(path), fields)
if !response.OK() {
if response.Err != nil {
return "", response, transportError("request failed: %s", response.Err.Error())
}
return "", response, transportError("server returned HTTP %d: %s", response.StatusCode, strings.TrimSpace(response.Body))
}
return strings.TrimSpace(response.Body), response, nil
}
// resolveHWID returns the HWID for outgoing requests. The legacy mode (and
// any explicit value) was already resolved at construction; "sl-hwid"
// enrolls or recovers lazily here, on the first request, and caches the
// session so a later successful authentication can commit a refresh.
func (c *Client) resolveHWID() (string, error) {
if c.config.HWID != "" {
return c.config.HWID, nil
}
c.mutex.Lock()
defer c.mutex.Unlock()
if c.slhwidSession != nil {
return c.slhwidSession.HWID(), nil
}
session, err := slHwidPrepare(slhwid.Options{
StorePath: c.config.SLHwidStore,
ExtraMandatory: c.config.SLHwidExtraMandatory,
})
if err != nil {
return "", &Error{Kind: ErrLocalFailure, Message: fmt.Sprintf("SL-HWID unavailable: %v", err)}
}
c.slhwidSession = session
return session.HWID(), nil
}
// commitHwid re-centers the SL-HWID shares on the hardware observed this
// launch. It runs only after the server accepted an authentication; failures
// are non-fatal — the next launch re-derives.
func (c *Client) commitHwid() {
c.mutex.Lock()
session := c.slhwidSession
c.mutex.Unlock()
if session != nil {
_ = session.Commit()
}
}
func (c *Client) baseFields() (url.Values, error) {
hwidValue, err := c.resolveHWID()
if err != nil {
return nil, err
}
fields := url.Values{
"system": {c.config.SystemID},
"version": {c.config.Version},
"hwid": {hwidValue},
"clean": {"1"},
}
if c.config.ProgramDigest != "" {
fields.Set("digest", c.config.ProgramDigest)
}
return fields, nil
}
// AuthenticateWithKey checks a license key (mikros mode). It returns true
// only when the server answers literally "true".
func (c *Client) AuthenticateWithKey(ctx context.Context, licenseKey string) (bool, error) {
fields, err := c.baseFields()
if err != nil {
return false, err
}
fields.Set("key", licenseKey)
return c.authenticate(ctx, fields)
}
// AuthenticateWithPassword checks username + password credentials (goliath
// mode).
func (c *Client) AuthenticateWithPassword(ctx context.Context, username, password string) (bool, error) {
fields, err := c.baseFields()
if err != nil {
return false, err
}
fields.Set("username", username)
fields.Set("password", password)
return c.authenticate(ctx, fields)
}
func (c *Client) authenticate(ctx context.Context, fields url.Values) (bool, error) {
body, _, err := c.request(ctx, authPath, fields)
if err != nil {
return false, err
}
if body == "true" {
// The server accepted this identity on this device.
c.commitHwid()
return true, nil
}
return false, classify(body)
}
// KeyExpirationForKey returns the expiry of a license key.
func (c *Client) KeyExpirationForKey(ctx context.Context, licenseKey string) (Expiration, error) {
fields, err := c.baseFields()
if err != nil {
return Expiration{}, err
}
fields.Set("key", licenseKey)
fields.Set("intent", "expiration")
return c.expiration(ctx, fields)
}
// KeyExpirationForPassword returns the expiry of the authenticated user's
// key for this system.
func (c *Client) KeyExpirationForPassword(ctx context.Context, username, password string) (Expiration, error) {
fields, err := c.baseFields()
if err != nil {
return Expiration{}, err
}
fields.Set("username", username)
fields.Set("password", password)
fields.Set("intent", "expiration")
return c.expiration(ctx, fields)
}
func (c *Client) expiration(ctx context.Context, fields url.Values) (Expiration, error) {
body, response, err := c.request(ctx, authPath, fields)
if err != nil {
return Expiration{}, err
}
// A successful intent response carries auth: true; failures carry the
// reason in auth (and the body).
if response.Header("auth") != "true" {
return Expiration{}, classify(body)
}
if body == "Never" || body == "N/A" {
return Expiration{Permanent: true, ExpiresAt: body}, nil
}
return Expiration{ExpiresAt: body}, nil
}
// GetVariable fetches a server-side variable. Pass a license key when the
// variable is protected.
func (c *Client) GetVariable(ctx context.Context, name string, licenseKey ...string) (VariableValue, error) {
fields := url.Values{
"system": {c.config.SystemID},
"variable": {name},
"clean": {"1"},
}
if len(licenseKey) > 0 && licenseKey[0] != "" {
fields.Set("key", licenseKey[0])
}
body, response, err := c.request(ctx, variablePath, fields)
if err != nil {
return VariableValue{}, err
}
// The intent header disambiguates: "true" means the body is the value
// (even when the value is literally "false"); "false" means missing,
// protected, or unauthorized; anything else is an error reason.
switch response.Header("intent") {
case "true":
return VariableValue{Found: true, Value: body}, nil
case "false":
return VariableValue{Found: false}, nil
default:
return VariableValue{}, classify(body)
}
}
// ResetHwidForKey clears the HWID bound to a license key (self-service;
// per-system flag and a 30-day cooldown apply).
func (c *Client) ResetHwidForKey(ctx context.Context, licenseKey string) (ResetOutcome, error) {
fields, err := c.baseFields()
if err != nil {
return ResetDenied, err
}
fields.Set("key", licenseKey)
fields.Set("intent", "hwidreset")
return c.resetHwid(ctx, fields)
}
// ResetHwidForPassword clears the HWID of the authenticated user's key.
func (c *Client) ResetHwidForPassword(ctx context.Context, username, password string) (ResetOutcome, error) {
fields, err := c.baseFields()
if err != nil {
return ResetDenied, err
}
fields.Set("username", username)
fields.Set("password", password)
fields.Set("intent", "hwidreset")
return c.resetHwid(ctx, fields)
}
func (c *Client) resetHwid(ctx context.Context, fields url.Values) (ResetOutcome, error) {
body, response, err := c.request(ctx, authPath, fields)
if err != nil {
return ResetDenied, err
}
// Credential failures carry the reason in the auth header (and body).
if authHeader := response.Header("auth"); authHeader != "" && authHeader != "true" {
return ResetDenied, classify(body)
}
// The intent header carries true/false/toosoon; the clean body carries
// "1"/""/"toosoon".
switch response.Header("intent") {
case "true", "1":
return ResetGranted, nil
case "toosoon":
return ResetTooSoon, nil
case "false", "":
if body == "toosoon" {
return ResetTooSoon, nil
}
if body == "true" || body == "1" {
return ResetGranted, nil
}
return ResetDenied, nil
default:
return ResetDenied, &Error{Kind: ErrUnknownReason, Reason: response.Header("intent"), Message: "Unexpected hwidreset response."}
}
}