|
| 1 | +package cronoapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "net/http/cookiejar" |
| 9 | + "net/url" |
| 10 | + "regexp" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +// DefaultBaseURL is the production Cronometer host. |
| 16 | +const DefaultBaseURL = "https://cronometer.com" |
| 17 | + |
| 18 | +const ( |
| 19 | + defaultTimeout = 60 * time.Second |
| 20 | + userAgentHdr = "crono-export-cli (clean-room; https://github.com/quantcli/crono-export-cli)" |
| 21 | +) |
| 22 | + |
| 23 | +// Client is an authenticated Cronometer session. Construct it with |
| 24 | +// NewClient, then call Login. After Login the client holds the GWT |
| 25 | +// session auth token and user ID and can call any of the Export* |
| 26 | +// methods. Logout tears down the session, best-effort. |
| 27 | +// |
| 28 | +// Client is not safe for concurrent use by multiple goroutines. |
| 29 | +type Client struct { |
| 30 | + HTTPClient *http.Client |
| 31 | + |
| 32 | + baseURL string |
| 33 | + permutation string |
| 34 | + userAgent string |
| 35 | + |
| 36 | + userID int |
| 37 | + authToken string |
| 38 | +} |
| 39 | + |
| 40 | +// NewClient returns a fresh Client. If httpClient is nil a default |
| 41 | +// client with a 60-second timeout and a cookie jar is constructed. |
| 42 | +// If httpClient is non-nil but has no Jar set, a cookie jar is |
| 43 | +// installed so session cookies round-trip across requests. |
| 44 | +func NewClient(httpClient *http.Client) *Client { |
| 45 | + if httpClient == nil { |
| 46 | + jar, _ := cookiejar.New(nil) |
| 47 | + httpClient = &http.Client{ |
| 48 | + Jar: jar, |
| 49 | + Timeout: defaultTimeout, |
| 50 | + } |
| 51 | + } else if httpClient.Jar == nil { |
| 52 | + jar, _ := cookiejar.New(nil) |
| 53 | + httpClient.Jar = jar |
| 54 | + } |
| 55 | + return &Client{ |
| 56 | + HTTPClient: httpClient, |
| 57 | + baseURL: DefaultBaseURL, |
| 58 | + permutation: DefaultGWTPermutation, |
| 59 | + userAgent: userAgentHdr, |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// SetBaseURL overrides the Cronometer host. Intended for tests. |
| 64 | +func (c *Client) SetBaseURL(u string) { c.baseURL = strings.TrimRight(u, "/") } |
| 65 | + |
| 66 | +// SetPermutation overrides the GWT permutation hash sent on |
| 67 | +// /cronometer/app calls. Useful when Cronometer rotates their deploy |
| 68 | +// hash and we need to point at the new value without a code release. |
| 69 | +func (c *Client) SetPermutation(p string) { c.permutation = p } |
| 70 | + |
| 71 | +// AuthToken returns the GWT session auth token from the most recent |
| 72 | +// successful Login. Empty before Login or after Logout. Exposed for |
| 73 | +// debugging; not normally needed by callers. |
| 74 | +func (c *Client) AuthToken() string { return c.authToken } |
| 75 | + |
| 76 | +// UserID returns the Cronometer user ID from the most recent |
| 77 | +// successful Login. Zero before Login or after Logout. |
| 78 | +func (c *Client) UserID() int { return c.userID } |
| 79 | + |
| 80 | +// anticsrfRe extracts the hidden anti-CSRF token from the login HTML. |
| 81 | +// WIRE_SHAPES.md §(1). |
| 82 | +var anticsrfRe = regexp.MustCompile(`name="anticsrf"\s+value="([^"]+)"`) |
| 83 | + |
| 84 | +// fetchAntiCSRF performs the anonymous GET /login/ that bootstraps the |
| 85 | +// session cookie jar and returns the anti-CSRF form token embedded in |
| 86 | +// the response HTML. |
| 87 | +func (c *Client) fetchAntiCSRF(ctx context.Context) (string, error) { |
| 88 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/login/", nil) |
| 89 | + if err != nil { |
| 90 | + return "", err |
| 91 | + } |
| 92 | + req.Header.Set("User-Agent", c.userAgent) |
| 93 | + resp, err := c.HTTPClient.Do(req) |
| 94 | + if err != nil { |
| 95 | + return "", fmt.Errorf("GET /login/: %w", err) |
| 96 | + } |
| 97 | + defer resp.Body.Close() |
| 98 | + if resp.StatusCode != http.StatusOK { |
| 99 | + return "", fmt.Errorf("GET /login/: HTTP %d", resp.StatusCode) |
| 100 | + } |
| 101 | + body, err := io.ReadAll(resp.Body) |
| 102 | + if err != nil { |
| 103 | + return "", fmt.Errorf("read /login/ body: %w", err) |
| 104 | + } |
| 105 | + m := anticsrfRe.FindSubmatch(body) |
| 106 | + if m == nil { |
| 107 | + return "", fmt.Errorf("anti-CSRF token not found in /login/ response") |
| 108 | + } |
| 109 | + return string(m[1]), nil |
| 110 | +} |
| 111 | + |
| 112 | +// submitLogin posts the credential form to /login. Cronometer responds |
| 113 | +// with a small JSON body and additional Set-Cookie entries on success. |
| 114 | +// The cookie jar on c.HTTPClient picks those up automatically. We do |
| 115 | +// not parse the JSON success body — its only documented failure mode |
| 116 | +// is `{"error":"AntiCSRF Token Invalid"}`, which we surface explicitly. |
| 117 | +func (c *Client) submitLogin(ctx context.Context, username, password, csrfToken string) error { |
| 118 | + form := url.Values{} |
| 119 | + form.Set("anticsrf", csrfToken) |
| 120 | + form.Set("password", password) |
| 121 | + form.Set("username", username) |
| 122 | + |
| 123 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/login", strings.NewReader(form.Encode())) |
| 124 | + if err != nil { |
| 125 | + return err |
| 126 | + } |
| 127 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 128 | + req.Header.Set("User-Agent", c.userAgent) |
| 129 | + |
| 130 | + resp, err := c.HTTPClient.Do(req) |
| 131 | + if err != nil { |
| 132 | + return fmt.Errorf("POST /login: %w", err) |
| 133 | + } |
| 134 | + defer resp.Body.Close() |
| 135 | + body, err := io.ReadAll(resp.Body) |
| 136 | + if err != nil { |
| 137 | + return fmt.Errorf("read /login body: %w", err) |
| 138 | + } |
| 139 | + if resp.StatusCode != http.StatusOK { |
| 140 | + return fmt.Errorf("POST /login: HTTP %d: %s", resp.StatusCode, truncate(string(body), 200)) |
| 141 | + } |
| 142 | + bodyStr := string(body) |
| 143 | + if strings.Contains(bodyStr, `"error"`) { |
| 144 | + return fmt.Errorf("login failed: %s", truncate(bodyStr, 200)) |
| 145 | + } |
| 146 | + return nil |
| 147 | +} |
| 148 | + |
| 149 | +// Login performs the three-step Cronometer authentication handshake: |
| 150 | +// |
| 151 | +// 1. GET /login/ — bootstrap cookies + read anti-CSRF token. |
| 152 | +// 2. POST /login — credential submission. |
| 153 | +// 3. POST /cronometer/app (GWT-RPC authenticate) — fetch userID + |
| 154 | +// session auth token used to mint export nonces. |
| 155 | +// |
| 156 | +// Steps map 1:1 to WIRE_SHAPES.md §(1), §(2), and §(3). |
| 157 | +func (c *Client) Login(ctx context.Context, username, password string) error { |
| 158 | + if username == "" || password == "" { |
| 159 | + return fmt.Errorf("login: username and password required") |
| 160 | + } |
| 161 | + csrf, err := c.fetchAntiCSRF(ctx) |
| 162 | + if err != nil { |
| 163 | + return err |
| 164 | + } |
| 165 | + if err := c.submitLogin(ctx, username, password, csrf); err != nil { |
| 166 | + return err |
| 167 | + } |
| 168 | + |
| 169 | + // Step 3: GWT-RPC authenticate. UTC offset in minutes for the host |
| 170 | + // timezone — captured payload sent -300 (NYC DST). We send the |
| 171 | + // current local zone's offset so the response reflects the user's |
| 172 | + // local calendar. |
| 173 | + _, offsetSec := time.Now().Zone() |
| 174 | + body, err := c.gwtCall(ctx, authenticateBody(c.permutation, offsetSec/60)) |
| 175 | + if err != nil { |
| 176 | + return fmt.Errorf("authenticate: %w", err) |
| 177 | + } |
| 178 | + uid, tok, err := parseAuthenticateResponse(body) |
| 179 | + if err != nil { |
| 180 | + return err |
| 181 | + } |
| 182 | + c.userID = uid |
| 183 | + c.authToken = tok |
| 184 | + return nil |
| 185 | +} |
| 186 | + |
| 187 | +// Logout calls the GWT-RPC logout method. WIRE_SHAPES.md §(14) notes |
| 188 | +// this is best-effort: crono-export-cli already calls it via defer and |
| 189 | +// ignores the returned error. |
| 190 | +func (c *Client) Logout(ctx context.Context) error { |
| 191 | + if c.authToken == "" { |
| 192 | + return nil |
| 193 | + } |
| 194 | + body, err := c.gwtCall(ctx, logoutBody(c.permutation, c.authToken)) |
| 195 | + c.authToken = "" |
| 196 | + c.userID = 0 |
| 197 | + if err != nil { |
| 198 | + return err |
| 199 | + } |
| 200 | + if !strings.HasPrefix(body, "//OK") { |
| 201 | + return fmt.Errorf("logout: unexpected response: %s", truncate(body, 80)) |
| 202 | + } |
| 203 | + return nil |
| 204 | +} |
0 commit comments