@whatcha/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +184 -2
  3. package/dist/auth/gotrue-client.js +64 -0
  4. package/dist/auth/gotrue-client.js.map +1 -0
  5. package/dist/auth/session.js +97 -0
  6. package/dist/auth/session.js.map +1 -0
  7. package/dist/auth/token-store.js +165 -0
  8. package/dist/auth/token-store.js.map +1 -0
  9. package/dist/cli.js +103 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/commands/diaries.js +41 -0
  12. package/dist/commands/diaries.js.map +1 -0
  13. package/dist/commands/login.js +217 -0
  14. package/dist/commands/login.js.map +1 -0
  15. package/dist/commands/profiles.js +176 -0
  16. package/dist/commands/profiles.js.map +1 -0
  17. package/dist/commands/read.js +77 -0
  18. package/dist/commands/read.js.map +1 -0
  19. package/dist/commands/write.js +75 -0
  20. package/dist/commands/write.js.map +1 -0
  21. package/dist/config.js +47 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/errors.js +46 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/http-client.js +86 -0
  26. package/dist/http-client.js.map +1 -0
  27. package/dist/index.js +16 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/lib/append-entry.js +141 -0
  30. package/dist/lib/append-entry.js.map +1 -0
  31. package/dist/lib/diary-resolve.js +50 -0
  32. package/dist/lib/diary-resolve.js.map +1 -0
  33. package/dist/lib/entry-date.js +76 -0
  34. package/dist/lib/entry-date.js.map +1 -0
  35. package/dist/lib/entry-find.js +39 -0
  36. package/dist/lib/entry-find.js.map +1 -0
  37. package/dist/lib/jwt.js +25 -0
  38. package/dist/lib/jwt.js.map +1 -0
  39. package/dist/lib/output.js +29 -0
  40. package/dist/lib/output.js.map +1 -0
  41. package/dist/types.js +6 -0
  42. package/dist/types.js.map +1 -0
  43. package/package.json +46 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # whatcha
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official command-line client for [what-are-you-do-ing](https://whatareyoudo.ing) --
4
+ the tool an AI agent (or a script) uses instead of automating a browser.
5
+ See `docs/proposals/2026-09-official-cli.md` for why this exists.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npx @whatcha/cli <command>
11
+ ```
12
+
13
+ or install it once:
14
+
15
+ ```
16
+ npm install -g @whatcha/cli
17
+ whatcha <command>
18
+ ```
19
+
20
+ Requires Node >= 22 (fetch, `node:util`'s `parseArgs`, and the fixed
21
+ `package.json`'s `"engines"` all assume it).
22
+
23
+ ## Commands
24
+
25
+ ### `whatcha login`
26
+
27
+ ```
28
+ whatcha login [--email <email>] [--password <password>] [--token <refresh-token>] [--json]
29
+ ```
30
+
31
+ Signs in and stores the session -- an OS credential store when one is
32
+ available (macOS Keychain via `security`, Linux's Secret Service via
33
+ `secret-tool`), otherwise a `0600` file under the OS config dir
34
+ (`~/.config/whatcha/credentials.json` on Linux, `~/Library/.../whatcha` is
35
+ not used on macOS since the Keychain is tried first, `%APPDATA%\whatcha` on
36
+ Windows). Every other command reads that session and refreshes it as
37
+ needed; there is no separate `whatcha logout` in this first version -- clear
38
+ the credential store yourself (Keychain Access, `secret-tool clear service
39
+ whatcha-cli account whatcha`, or delete the file) if you need to.
40
+
41
+ Email and password can come from `--email`/`--password`, from
42
+ `WHATCHA_EMAIL`/`WHATCHA_PASSWORD`, or (only when neither is set) an
43
+ interactive prompt with the password masked. The env vars exist because an
44
+ AI agent invoking `whatcha` as a subprocess has no TTY to answer a prompt at.
45
+
46
+ **If sign-in is refused (issue #1428):** GoTrue enforces a Cloudflare
47
+ Turnstile challenge on the password grant, and an automated/headless
48
+ browser cannot solve it -- a real user hit exactly this ("Verification
49
+ failed" / "Please complete the verification") trying to sign in an AI
50
+ partner account. `POST /auth/login` also answers a captcha rejection with
51
+ the same generic 401 as a wrong password, so `whatcha` frequently cannot
52
+ tell you which one happened. Do not keep retrying the password in that
53
+ case. Instead:
54
+
55
+ ```
56
+ whatcha login --token <refresh-token>
57
+ ```
58
+
59
+ or set `WHATCHA_TOKEN` to the same value. This calls `POST /auth/refresh`
60
+ directly, which is **not** captcha-gated, so it works from a machine that
61
+ can never pass Turnstile. The refresh token itself has to come from
62
+ somewhere that *can* solve the challenge -- a browser or the mobile app,
63
+ signed in once, with the token then handed to the headless machine out of
64
+ band. As of this writing there is no self-service "show me my token" screen
65
+ in the app to get one from; see this PR's description for what a real fix
66
+ looks like on the API/product side.
67
+
68
+ Advanced: if `WHATCHA_SUPABASE_URL` and `WHATCHA_SUPABASE_ANON_KEY` are both
69
+ set, `whatcha login` talks to GoTrue directly instead of through
70
+ `/auth/login`. This does not bypass the captcha (GoTrue enforces it either
71
+ way) but its error responses do say explicitly when a request was rejected
72
+ for a captcha reason, which `whatcha` then reports plainly instead of
73
+ guessing. Nothing in this repo publishes those two values for a checkout to
74
+ read (they are build-time secrets on the mobile/web clients), so this path
75
+ is opt-in and unverified against a live server -- see the PR description.
76
+
77
+ ### `whatcha diaries`
78
+
79
+ ```
80
+ whatcha diaries [--json]
81
+ ```
82
+
83
+ Lists the diaries you can see (your personal shelf, same set `GET /diaries`
84
+ without `groupId` returns -- so not diaries in a system group like Public
85
+ Square).
86
+
87
+ ### `whatcha write`
88
+
89
+ ```
90
+ whatcha write <diary> --text "..." [--time HH:MM] [--date YYYY-MM-DD] [--json]
91
+ ```
92
+
93
+ `<diary>` is a diary id or its exact name (case-insensitive; an ambiguous
94
+ name lists the matches and asks for the id instead). `--date`/`--time`
95
+ default to today/now in **the diary's own timezone**, not the machine's --
96
+ that is what decides which diary-day the API's one-entry-per-day rule
97
+ (§11.4) puts the write on.
98
+
99
+ **Appending is always safe.** If the diary-day already has an entry, this
100
+ never sends a body it has not just read:
101
+
102
+ 1. No entry yet for that day -- `POST /entries` creates it with your text.
103
+ 2. An entry exists -- the entry is read first (`GET /entries/{id}`, to
104
+ carry its title/mood/tags/cover forward unchanged, since those fields
105
+ are full-replace-on-save the same as the body), then `PATCH` with
106
+ `appendBody: true` (fixed in #1424) appends server-side.
107
+ 3. If the server does not know `appendBody` (a 422 naming it an
108
+ unrecognized key), the text already read in step 2 is merged locally
109
+ and sent as a plain replacement of what was just read -- never blind.
110
+ 4. Either way, the entry is read back once more afterward to confirm the
111
+ old text is still there under the new text. If that check fails,
112
+ `whatcha` exits with status 2 and a loud warning instead of reporting
113
+ success -- see `src/lib/append-entry.ts` for why this exists (it is the
114
+ only defense against a server old enough to silently ignore
115
+ `appendBody` and just replace, which the API's own default
116
+ configuration would in fact do -- see the PR description).
117
+
118
+ ### `whatcha read`
119
+
120
+ ```
121
+ whatcha read <diary> [--date YYYY-MM-DD] [--json]
122
+ ```
123
+
124
+ Defaults to today (diary timezone). Prints title/tags/body; a locked (Time
125
+ Capsule) entry is reported as locked, never shown early. `GET /entries` has
126
+ no `?date=` filter, so this pages through the diary's entries
127
+ newest-first (`src/lib/entry-find.ts`) until it finds that day or passes it
128
+ -- exact, not fuzzy, but not O(1) for a very old date on a very active diary.
129
+
130
+ ### `whatcha profiles` / `whatcha switch`
131
+
132
+ ```
133
+ whatcha profiles [--json]
134
+ whatcha switch <@handle> [--json]
135
+ whatcha switch --account [--json]
136
+ ```
137
+
138
+ Sub-accounts (#1538): one login, more than one profile. A sub-profile is an
139
+ ordinary user with its own `@handle`, so after a switch `write`, `read` and
140
+ `diaries` all act as that profile -- none of them takes a flag, and none of
141
+ them knows the feature exists. The saved session simply is that profile.
142
+
143
+ `profiles` marks the current one with `*` and labels the account. Creating a
144
+ sub-profile is done in the app; this CLI switches between the ones that
145
+ exist.
146
+
147
+ `switch --account` is how you come back. The API refuses to mint an account
148
+ session from a sub-profile's session on purpose -- a sub-profile that could
149
+ ask for one would be a way to take the account over -- so `switch` sets the
150
+ account's refresh token aside in the same credential store and `--account`
151
+ spends it. Switching from one sub-profile to a sibling carries it forward
152
+ unchanged.
153
+
154
+ Billing is the one thing a sub-profile does not have: the account's plan is
155
+ its plan, and a sub-profile's own limits are the account's.
156
+
157
+ ## The `--json` contract
158
+
159
+ Every command accepts `--json`. On success it prints exactly one JSON
160
+ object to stdout: `{"ok": true, ...}`, with the fields documented per
161
+ command above (`diaries`, `entryId`/`mode`/`verified` for `write`,
162
+ `body`/`title`/`tags`/... for `read`). On failure it prints
163
+ `{"ok": false, "error": {"code", "message"}}` -- still to stdout, so a
164
+ script doing `whatcha ... --json | jq` gets parseable JSON either way,
165
+ without also having to capture stderr.
166
+
167
+ **Never included, on success or failure:** an access token, a refresh
168
+ token, or a password. `whatcha login --json`'s output is
169
+ `{"ok", "userId", "email", "credentialStore"}` -- the store's name, never
170
+ its contents.
171
+
172
+ ## Tests
173
+
174
+ ```
175
+ npm ci
176
+ npm run typecheck
177
+ npm test
178
+ ```
179
+
180
+ Every test runs with no network: `tests/fixtures/fake-client.ts` implements
181
+ the same `WhatchaClient` interface the real HTTP client does, so
182
+ `src/lib/append-entry.ts`, the command parsers, and the token store are all
183
+ exercised against an in-memory fake instead of a live API. The token-store
184
+ tests point `WHATCHA_CONFIG_DIR` at a throwaway directory rather than
185
+ touching a real OS keychain or the developer's own config file.
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoTrueError = void 0;
4
+ exports.signInWithPassword = signInWithPassword;
5
+ class GoTrueError extends Error {
6
+ status;
7
+ errorCode;
8
+ constructor(status, errorCode, message) {
9
+ super(message);
10
+ this.status = status;
11
+ this.errorCode = errorCode;
12
+ this.name = "GoTrueError";
13
+ }
14
+ /**
15
+ * GoTrue's captcha rejection is a 400 whose body names the captcha
16
+ * explicitly (`error_code: "captcha_failed"` on current GoTrue; older
17
+ * versions instead put it in `msg`, e.g. "captcha protection: request
18
+ * disallowed"), unlike a wrong password's "Invalid login credentials".
19
+ * Not verified against a live server -- see the PR description's "which
20
+ * paths I could verify" section.
21
+ */
22
+ looksLikeCaptchaFailure() {
23
+ const haystack = `${this.errorCode ?? ""} ${this.message}`.toLowerCase();
24
+ return haystack.includes("captcha");
25
+ }
26
+ }
27
+ exports.GoTrueError = GoTrueError;
28
+ async function signInWithPassword(supabaseUrl, anonKey, email, password, captchaToken) {
29
+ let res;
30
+ try {
31
+ res = await fetch(`${supabaseUrl.replace(/\/$/, "")}/auth/v1/token?grant_type=password`, {
32
+ method: "POST",
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ apikey: anonKey,
36
+ Authorization: `Bearer ${anonKey}`,
37
+ },
38
+ body: JSON.stringify({
39
+ email,
40
+ password,
41
+ gotrue_meta_security: captchaToken ? { captcha_token: captchaToken } : undefined,
42
+ }),
43
+ });
44
+ }
45
+ catch (err) {
46
+ throw new GoTrueError(0, "network_error", `Could not reach ${supabaseUrl}: ${err.message}`);
47
+ }
48
+ const text = await res.text();
49
+ const json = text ? JSON.parse(text) : undefined;
50
+ if (!res.ok) {
51
+ const body = json;
52
+ const message = body?.msg ?? body?.error_description ?? body?.error ?? `GoTrue answered ${res.status}`;
53
+ throw new GoTrueError(res.status, body?.error_code ?? body?.error, message);
54
+ }
55
+ const body = json;
56
+ return {
57
+ accessToken: body.access_token,
58
+ expiresIn: body.expires_in,
59
+ refreshToken: body.refresh_token,
60
+ userId: body.user.id,
61
+ email: body.user.email ?? email,
62
+ };
63
+ }
64
+ //# sourceMappingURL=gotrue-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gotrue-client.js","sourceRoot":"","sources":["../../src/auth/gotrue-client.ts"],"names":[],"mappings":";;;AA2DA,gDA2CC;AAtED,MAAa,WAAY,SAAQ,KAAK;IACf;IAAyB;IAA9C,YAAqB,MAAc,EAAW,SAA6B,EAAE,OAAe;QAC1F,KAAK,CAAC,OAAO,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C,CAAC,CAAC,CAAC,SAAS,CAAC;IAE1D,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;QACZ,MAAM,IAAI,GAAG,IAAqG,CAAC;QACnH,MAAM,OAAO,GAAG,IAAI,EAAE,GAAG,IAAI,IAAI,EAAE,iBAAiB,IAAI,IAAI,EAAE,KAAK,IAAI,mBAAmB,GAAG,CAAC,MAAM,EAAE,CAAC;QACvG,MAAM,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,IAAI,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,IAAI,GAAG,IAA2B,CAAC;IACzC,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,YAAY;QAC9B,SAAS,EAAE,IAAI,CAAC,UAAU;QAC1B,YAAY,EAAE,IAAI,CAAC,aAAa;QAChC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE;QACpB,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,KAAK;KAChC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.saveSession = saveSession;
4
+ exports.loadSession = loadSession;
5
+ exports.clearSession = clearSession;
6
+ exports.authenticatedClient = authenticatedClient;
7
+ exports.anonymousClient = anonymousClient;
8
+ const http_client_1 = require("../http-client");
9
+ const config_1 = require("../config");
10
+ const errors_1 = require("../errors");
11
+ const token_store_1 = require("./token-store");
12
+ /** Refresh this many seconds before actual expiry, so a call in flight does not race the token dying mid-request. */
13
+ const REFRESH_MARGIN_SECONDS = 60;
14
+ /**
15
+ * Tries each candidate store in order (OS keychain first where one exists
16
+ * for the platform, the 0600 file always last) and uses the first one that
17
+ * actually accepts the write. A keychain that exists but is locked, or a
18
+ * Secret Service that is not running, throws on `save` rather than on
19
+ * `isAvailable` -- both are caught here, not just the availability check.
20
+ */
21
+ async function saveSession(session, stores = (0, token_store_1.candidateStores)()) {
22
+ const errors = [];
23
+ for (const store of stores) {
24
+ if (!(await store.isAvailable()))
25
+ continue;
26
+ try {
27
+ await store.save(session);
28
+ return { store };
29
+ }
30
+ catch (err) {
31
+ errors.push(`${store.name}: ${err.message}`);
32
+ }
33
+ }
34
+ throw new Error(`Could not save the session to any credential store. Tried:\n${errors.join("\n")}`);
35
+ }
36
+ /** First candidate store that actually has a session, or null if none do. */
37
+ async function loadSession(stores = (0, token_store_1.candidateStores)()) {
38
+ for (const store of stores) {
39
+ if (!(await store.isAvailable()))
40
+ continue;
41
+ const session = await store.load();
42
+ if (session)
43
+ return session;
44
+ }
45
+ return null;
46
+ }
47
+ /** Best-effort clear from every candidate, not just whichever one currently holds the session -- avoids a stale copy surviving a store switch. */
48
+ async function clearSession(stores = (0, token_store_1.candidateStores)()) {
49
+ for (const store of stores) {
50
+ if (await store.isAvailable())
51
+ await store.clear();
52
+ }
53
+ }
54
+ /**
55
+ * A client wired to a saved session, refreshing the access token first if
56
+ * it is at or near expiry. Every command but `login` starts here.
57
+ *
58
+ * Throws CliUsageError (not ApiError) when there is no session or the
59
+ * refresh itself fails -- both are "run `whatcha login`" situations, not
60
+ * something a command should try to recover from.
61
+ */
62
+ async function authenticatedClient(stores = (0, token_store_1.candidateStores)()) {
63
+ let session = await loadSession(stores);
64
+ if (!session) {
65
+ throw new errors_1.CliUsageError("Not logged in. Run `whatcha login` first.");
66
+ }
67
+ const baseUrl = session.apiBaseUrl || (0, config_1.apiBaseUrl)();
68
+ const nowSeconds = Date.now() / 1000;
69
+ if (session.expiresAt / 1000 - nowSeconds < REFRESH_MARGIN_SECONDS) {
70
+ const anon = new http_client_1.FetchWhatchaClient(baseUrl, async () => undefined);
71
+ let refreshed;
72
+ try {
73
+ refreshed = await anon.post("/auth/refresh", { refreshToken: session.refreshToken });
74
+ }
75
+ catch {
76
+ throw new errors_1.CliUsageError("The saved session has expired and could not be refreshed. Run `whatcha login` again.");
77
+ }
78
+ session = {
79
+ ...session,
80
+ accessToken: refreshed.accessToken,
81
+ refreshToken: refreshed.refreshToken,
82
+ expiresAt: Date.now() + refreshed.expiresIn * 1000,
83
+ };
84
+ // Best-effort: a save failure here must not fail the command that
85
+ // triggered the refresh -- worst case, the next command refreshes
86
+ // again. Whichever store answered `load()` above is where this goes
87
+ // back to.
88
+ await saveSession(session, stores).catch(() => undefined);
89
+ }
90
+ const client = new http_client_1.FetchWhatchaClient(baseUrl, async () => `Bearer ${session.accessToken}`);
91
+ return { client, session };
92
+ }
93
+ /** An unauthenticated client for `/auth/login` itself, or for `--api-url` probing. */
94
+ function anonymousClient(baseUrl = (0, config_1.apiBaseUrl)()) {
95
+ return new http_client_1.FetchWhatchaClient(baseUrl, async () => undefined);
96
+ }
97
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":";;AAoBA,kCAYC;AAGD,kCAOC;AAGD,oCAIC;AAUD,kDAkCC;AAGD,0CAEC;AAlGD,gDAAmE;AACnE,sCAAuC;AACvC,sCAA0C;AAE1C,+CAA2E;AAE3E,qHAAqH;AACrH,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAMlC;;;;;;GAMG;AACI,KAAK,UAAU,WAAW,CAAC,OAAsB,EAAE,SAAuB,IAAA,6BAAe,GAAE;IAChG,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,WAAW,EAAE,CAAC;YAAE,SAAS;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC1B,OAAO,EAAE,KAAK,EAAE,CAAC;QACnB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,IAAI,KAAM,GAAa,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