@byokit/accounts 0.2.0 → 0.2.2

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.
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,7 +1,8 @@
1
1
  # @byokit/accounts
2
2
 
3
- Sign in with the AI plan you already pay for (ChatGPT, OpenRouter; Grok and GitHub Copilot on request), inside your
4
- own app, into your app's own store: on a computer (Node, Electron), in a browser (a PWA, Electron's renderer) and on a
3
+ Sign in with the AI plan you already pay for (ChatGPT on every platform; OpenRouter on computers; Grok and GitHub
4
+ Copilot hidden by default), inside your own app, into your app's own store: on a computer (Node, Electron), in a browser
5
+ (a PWA, Electron's renderer) and on a
5
6
  phone (React Native and Expo, iOS and Android). One import; your bundler picks the platform's side
6
7
  (`package.json`'s `react-native` and `browser` conditions).
7
8
 
@@ -30,8 +31,8 @@ const accounts = new Accounts({ store: (member) => secureStore(SecureStore, `byo
30
31
  const shown = await accounts.login(1, 'chatgpt'); // { state: 'waiting', via: 'code', code, url }: open url, show code
31
32
  ```
32
33
 
33
- Examples that sign in end to end: [`examples/expo`](../../examples/expo) (iOS and Android) and
34
- [`examples/pwa`](../../examples/pwa).
34
+ Examples: [`examples/expo`](../../examples/expo) (iOS and Android bundles; Android emulator sign-in) and
35
+ [`examples/pwa`](../../examples/pwa) (browser sign-in).
35
36
 
36
37
  ## Which sign-in works where
37
38
 
@@ -48,25 +49,30 @@ listener on the computer the browser runs on, so it is desktop only: ChatGPT sen
48
49
  doesn't answer other web pages), so a PWA's model calls go through the app's own server or relay.
49
50
 
50
51
  - **Catalogue** (`catalogue.json`): each provider with its terms status (`allowed`, `grey`, `partner`), a one-line reason
51
- and a source. The kit labels; your app decides what to offer (`new Accounts({ offer: ['chatgpt', 'grok'] })`).
52
- Claude plan sign-in is never offered: Anthropic reserves it for its own apps.
53
- - **Sign-in**: the provider's own page by default. For ChatGPT, whose page returns to this computer's port 1455, the kit
54
- listens there itself, so the tab shows your app's words (`new Accounts({ app: 'My App' })`) and only once they are
52
+ and a source. The kit labels; your app decides what to offer (`new Accounts({ offer: ['chatgpt'] })`). Without an
53
+ explicit `offer`, only sign-ins supported on this platform are shown; an explicit list is not platform-filtered, so
54
+ choose from the table above. Claude plan sign-in is never offered: Anthropic reserves it for its own apps.
55
+ - **Sign-in**: on computers, the provider's own page by default. For ChatGPT, whose page returns to this computer's
56
+ port 1455, the kit listens there itself, so the tab shows your app's words (`new Accounts({ app: 'My App' })`) and only once they are
55
57
  true. A code takes over when asked ("Having trouble?"), when the page never comes back, or when the port is taken by
56
58
  another sign-in. A 15-minute cap, nothing kept unless the engine can use it, and every failure is one plain sentence
57
59
  (`words.json`) with a `why` for apps that word it themselves. `plan(member)` tells a work ChatGPT from a personal one.
58
- - **Sign-out**: `logout(member, key)` also ends a ChatGPT sign-in at OpenAI (`POST auth.openai.com/oauth/revoke`, as
59
- Codex's own sign-out does), then deletes it here whatever OpenAI answers. It runs in the store's own turn, so a refresh
60
- under way finishes first and the token it rotated to is the one ended.
60
+ - **Sign-out**: `logout(member, key)` attempts to revoke a ChatGPT token at OpenAI (`POST auth.openai.com/oauth/revoke`),
61
+ then deletes the local sign-in even if the revoke fails. A failed revoke rejects after local deletion; report it because
62
+ the remote sign-in may remain active. Within one store instance, a refresh already in progress finishes first, so
63
+ sign-out uses its rotated token. If a cancelled sign-in finishes late, `onSignOutError` reports a failed revoke of its
64
+ discarded credential (or it is logged when no handler is set).
61
65
  - **One person, one store**: `memoryStore()`, `fileStore(path)` (0600, the same shape as Pi's `auth.json`),
62
- `secureStore(SecureStore, name)` or `browserStore(name)`; any other storage with `recordStore(load, save)`. Every one
63
- serializes its writes, so a refresh and a sign-out never interleave. Never a shared fallback. Using another engine
64
- with the same seam (Pi's coding-agent `ModelRuntime`)? Override `open(member)`.
66
+ `secureStore(SecureStore, name)` or `browserStore(name)`; any other storage with `recordStore(load, save)`. Writes are
67
+ serialized within a store instance; `browserStore` also uses Web Locks across tabs for the same provider when available.
68
+ Never a shared fallback. Browser storage is readable by scripts on your page: avoid untrusted scripts. Using another
69
+ engine with the same seam (Pi's coding-agent `ModelRuntime`)? Override `open(member)` with an engine whose
70
+ `credentialStore` is made with `boundStore(member, engineStore)` and whose `readCredential(id)` reads that store.
65
71
  - **Limits**: `failed(member, key, error)` rests an account until the provider said (or a default), marks a plan that
66
72
  doesn't include this use, and signs out only a sign-in that no longer refreshes. `ladder()` picks the next usable
67
73
  account; `keepFresh()` refreshes ahead of expiry. Limits come from errors only; no undocumented usage endpoint is read.
68
74
  - **Isolation**: ambient discovery is off (no environment variable or credential file is ever consulted), and
69
75
  `@byokit/accounts/testing` has the decoy-HOME harness and fs tracer to prove it in your own tests.
70
- - **A stand-in OpenAI**: `mockOpenAI()` from `@byokit/accounts/testing` (or `node .../testing/mock-openai.ts 1455`)
76
+ - **A stand-in OpenAI**: `mockOpenAI()` from `@byokit/accounts/testing` (or `node .../testing/mock-openai.ts [port]`)
71
77
  answers device code, its page where a person types the code, token exchange, refresh and revoke, so tests and demos
72
78
  sign in end to end with no account. Point the kit at it with `new Accounts({ authBase })`.
@@ -1,9 +1,16 @@
1
1
  import type { CredentialStore, Models } from '@earendil-works/pi-ai';
2
2
  import { type Provider } from './catalogue.ts';
3
3
  import { type Kind } from './limits.ts';
4
+ import { type EndingStore } from './stores.ts';
4
5
  import { type Why } from './words.ts';
5
6
  /** What signing in needs from an engine: Pi's `Models`, or anything shaped like it (the coding agent's `ModelRuntime`). */
6
- export type AuthHost = Pick<Models, 'login' | 'logout' | 'checkAuth' | 'getAuth'>;
7
+ type BoundStore = CredentialStore & {
8
+ signOut: (id: string, p: Provider) => Promise<void>;
9
+ };
10
+ export type AuthHost = Pick<Models, 'login' | 'logout' | 'checkAuth' | 'getAuth'> & {
11
+ readCredential: CredentialStore['read'];
12
+ credentialStore: BoundStore;
13
+ };
7
14
  export type Member = string | number;
8
15
  /** What the person sees while signing in: the provider's own page to open (`via: 'browser'`), or a code to type there
9
16
  * (`via: 'code'`), never the engine's own prompts. `why` names how a failed one failed, for apps that word it themselves. */
@@ -67,6 +74,10 @@ export declare class Accounts<R extends AuthHost = AuthHost, M extends Member =
67
74
  private opts;
68
75
  private runtimes;
69
76
  private stores;
77
+ private generations;
78
+ private signals;
79
+ private chains;
80
+ private signingOut;
70
81
  private flows;
71
82
  private ready;
72
83
  private lapsed;
@@ -79,11 +90,15 @@ export declare class Accounts<R extends AuthHost = AuthHost, M extends Member =
79
90
  onSignedIn?: (member: M, key: string) => void;
80
91
  /** Said once when a sign-in can no longer be refreshed. */
81
92
  onExpired?: (member: M, key: string) => void;
93
+ onSignOutError?: (member: M, key: string, error: Error) => void;
82
94
  private platform;
83
95
  /** Offered: the providers named in `offer`, else every provider not hidden that this platform can sign in to. */
84
96
  constructor(opts?: AccountsOptions<M>, platform?: Platform);
85
97
  /** A member's own store. */
86
- protected store(member: M): CredentialStore;
98
+ protected store(member: M): EndingStore;
99
+ private serial;
100
+ protected boundStore(member: M, raw: CredentialStore): BoundStore;
101
+ protected engine(member: M, raw: CredentialStore): Promise<R>;
87
102
  /** A member's engine, holding only their own sign-ins (`store(member)`). Override to use another engine with the same seam. */
88
103
  protected open(member: M): Promise<R>;
89
104
  runtime(member: M): Promise<R>;
@@ -136,15 +151,16 @@ export declare class Accounts<R extends AuthHost = AuthHost, M extends Member =
136
151
  paste(member: M, key: string, text: string): void;
137
152
  /** Stop a sign-in and forget it; nothing it started is kept. */
138
153
  cancel(member: M, key: string): void;
154
+ private refreshed;
139
155
  /** Refresh every signed-in account an hour ahead of expiry (call it now and then), so a sign-in never lapses while
140
156
  * nobody is looking. Only the provider refusing signs it out, and `onExpired` says so once; a network hiccup doesn't. */
141
157
  keepFresh(members: readonly M[]): Promise<void>;
142
158
  /** After the account turned a request away: true if its sign-in still refreshes; if not, it is signed out for good. */
143
159
  recheck(member: M, key: string): Promise<boolean>;
144
160
  /** Signs out here, and at the provider too where it can end a sign-in (ChatGPT), best effort: the sign-in is deleted
145
- * here whatever the provider answers. The revoke runs in the store's own turn, so a refresh under way finishes first
146
- * and the token it rotated to is the one ended; a refresh after it is refused. */
161
+ * here whatever the provider answers. */
147
162
  logout(member: M, key: string): Promise<void>;
148
163
  view(member: M, key: string): SignIn | null;
149
164
  stop(): void;
150
165
  }
166
+ export {};
package/dist/accounts.js CHANGED
@@ -20,20 +20,19 @@ const offline = (e) => failure(String(e?.message)) === 'offline';
20
20
  * access token, never retried (fixtures/conformance/revoke.json). */
21
21
  async function revoke(url, clientId, c) {
22
22
  const body = c.refresh ? { token: c.refresh, token_type_hint: 'refresh_token', client_id: clientId } : { token: c.access, token_type_hint: 'access_token' };
23
- const stop = new AbortController();
24
- const t = setTimeout(() => stop.abort(), 10_000);
25
- try {
26
- await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: stop.signal });
27
- }
28
- finally {
29
- clearTimeout(t);
30
- }
23
+ const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000) });
24
+ if (!response.ok)
25
+ throw new Error(`ChatGPT sign-out failed (${response.status})`);
31
26
  }
32
27
  export class Accounts {
33
28
  providers;
34
29
  opts;
35
30
  runtimes = new Map();
36
31
  stores = new Map();
32
+ generations = new Map();
33
+ signals = new WeakMap();
34
+ chains = new Map();
35
+ signingOut = new Map();
37
36
  flows = new Map();
38
37
  ready = new Map();
39
38
  lapsed = new Set();
@@ -46,6 +45,7 @@ export class Accounts {
46
45
  onSignedIn;
47
46
  /** Said once when a sign-in can no longer be refreshed. */
48
47
  onExpired;
48
+ onSignOutError;
49
49
  platform;
50
50
  /** Offered: the providers named in `offer`, else every provider not hidden that this platform can sign in to. */
51
51
  constructor(opts = {}, platform = portable) {
@@ -56,14 +56,115 @@ export class Accounts {
56
56
  /** A member's own store. */
57
57
  store(member) {
58
58
  let s = this.stores.get(String(member));
59
- if (!s)
60
- this.stores.set(String(member), s = (this.opts.store ?? memoryStore)(member));
59
+ if (!s) {
60
+ const base = (this.opts.store ?? memoryStore)(member);
61
+ let chain = Promise.resolve();
62
+ const serial = (fn) => { const result = chain.then(fn); chain = result.catch(() => { }); return result; };
63
+ s = {
64
+ read: (id) => base.read(id),
65
+ list: () => base.list(),
66
+ modify: (id, fn, options) => serial(() => base.modify(id, fn, options)),
67
+ delete: (id, options) => serial(() => base.delete(id, options)),
68
+ end: (id, fn) => serial(async () => {
69
+ if (typeof base.end === 'function')
70
+ return base.end(id, fn);
71
+ try {
72
+ await fn(await base.read(id));
73
+ }
74
+ finally {
75
+ await base.delete(id);
76
+ }
77
+ }),
78
+ };
79
+ this.stores.set(String(member), s);
80
+ }
61
81
  return s;
62
82
  }
63
- /** A member's engine, holding only their own sign-ins (`store(member)`). Override to use another engine with the same seam. */
64
- open(member) {
65
- return Promise.resolve(this.platform.engine(this.store(member), this.opts.authBase));
83
+ async serial(id, fn) {
84
+ const previous = this.chains.get(id) ?? Promise.resolve();
85
+ const work = previous.then(fn, fn);
86
+ const tail = work.then(() => { }, () => { });
87
+ this.chains.set(id, tail);
88
+ try {
89
+ return await work;
90
+ }
91
+ finally {
92
+ if (this.chains.get(id) === tail)
93
+ this.chains.delete(id);
94
+ }
95
+ }
96
+ boundStore(member, raw) {
97
+ const key = (id) => `${member}:${this.providers.find((p) => p.pi === id)?.key ?? id}`;
98
+ return {
99
+ read: (id, options) => raw.read(id, options),
100
+ list: (options) => raw.list(options),
101
+ modify: (id, fn, options) => {
102
+ const account = key(id);
103
+ const stale = Symbol();
104
+ const started = options?.signal ? this.signals.get(options.signal) ?? this.generations.get(account) ?? 0 : this.generations.get(account) ?? 0;
105
+ const discard = async (next) => {
106
+ const p = this.providers.find((p) => p.pi === id);
107
+ if (next?.type === 'oauth' && p?.revoke) {
108
+ try {
109
+ await revoke(this.opts.authBase ? `${this.opts.authBase}/oauth/revoke` : p.revoke, p.clientId, next);
110
+ }
111
+ catch (e) {
112
+ const error = e instanceof Error ? e : new Error(String(e));
113
+ if (this.onSignOutError)
114
+ this.onSignOutError(member, p.key, error);
115
+ else
116
+ console.error(`sign-out ${p.key} for member ${member}:`, error);
117
+ throw error;
118
+ }
119
+ }
120
+ };
121
+ return this.serial(account, async () => {
122
+ if (started !== (this.generations.get(account) ?? 0)) {
123
+ await discard(await fn(undefined));
124
+ return undefined;
125
+ }
126
+ try {
127
+ return await raw.modify(id, async (current) => {
128
+ const next = await fn(current);
129
+ if (started !== (this.generations.get(account) ?? 0)) {
130
+ await discard(next);
131
+ throw stale;
132
+ }
133
+ return next;
134
+ }, options);
135
+ }
136
+ catch (e) {
137
+ if (e === stale)
138
+ return undefined;
139
+ throw e;
140
+ }
141
+ });
142
+ },
143
+ delete: (id, options) => this.serial(key(id), () => raw.delete(id, options)),
144
+ signOut: (id, p) => this.serial(key(id), async () => {
145
+ let error;
146
+ try {
147
+ const c = await raw.read(id);
148
+ if (c?.type === 'oauth')
149
+ await revoke(this.opts.authBase ? `${this.opts.authBase}/oauth/revoke` : p.revoke, p.clientId, c);
150
+ }
151
+ catch (e) {
152
+ error = e;
153
+ }
154
+ await raw.delete(id);
155
+ if (error)
156
+ throw error;
157
+ }),
158
+ };
159
+ }
160
+ engine(member, raw) {
161
+ const credentials = this.boundStore(member, raw);
162
+ return Promise.resolve(Object.assign(this.platform.engine(credentials, this.opts.authBase), {
163
+ credentialStore: credentials, readCredential: (id) => credentials.read(id),
164
+ }));
66
165
  }
166
+ /** A member's engine, holding only their own sign-ins (`store(member)`). Override to use another engine with the same seam. */
167
+ open(member) { return this.engine(member, this.store(member)); }
67
168
  runtime(member) {
68
169
  let r = this.runtimes.get(String(member));
69
170
  if (!r)
@@ -86,7 +187,7 @@ export class Accounts {
86
187
  }
87
188
  /** Which ChatGPT the member signed in with: its plan, email, and whether it is a work account. Null when not signed in. */
88
189
  async plan(member) {
89
- const c = await this.store(member).read(this.offer('chatgpt').pi).catch(() => undefined);
190
+ const c = await (await this.runtime(member)).readCredential(this.offer('chatgpt').pi).catch(() => undefined);
90
191
  return c?.type === 'oauth' ? planOf(c.access) : null;
91
192
  }
92
193
  /** Whether the member's plan lacks this use; `on` records what the provider said, or that the person changed plans. */
@@ -160,6 +261,9 @@ export class Accounts {
160
261
  async login(member, key, body = {}) {
161
262
  this.offer(key);
162
263
  const id = `${member}:${key}`;
264
+ const pending = this.signingOut.get(id);
265
+ if (pending)
266
+ await pending.catch(() => { });
163
267
  const now = this.flows.get(id);
164
268
  if (now?.state === 'waiting' && body.via === 'code' && now.via === 'browser') {
165
269
  // "Having trouble?": the same sign-in carries on with a code instead.
@@ -168,7 +272,8 @@ export class Accounts {
168
272
  await Promise.race([visible, now.done]);
169
273
  }
170
274
  else if (now?.state !== 'waiting') {
171
- const flow = { state: 'waiting', abort: new AbortController() };
275
+ const flow = { state: 'waiting', abort: new AbortController(), generation: this.generations.get(id) ?? 0 };
276
+ this.signals.set(flow.abort.signal, flow.generation);
172
277
  this.flows.set(id, flow);
173
278
  const visible = new Promise((r) => (flow.shown = r));
174
279
  flow.done = this.signIn(member, key, body, flow);
@@ -238,11 +343,14 @@ export class Accounts {
238
343
  catcher?.close();
239
344
  await attempt('code');
240
345
  }
241
- // Never half signed in: only a sign-in the engine can use counts.
346
+ if (flow.generation !== (this.generations.get(id) ?? 0) || flow.state !== 'waiting')
347
+ return;
242
348
  if (!(await rt.checkAuth(p.pi).catch(() => undefined))) {
243
349
  await rt.logout(p.pi).catch(() => { });
244
350
  throw new Error('no usable credential');
245
351
  }
352
+ if (flow.generation !== (this.generations.get(id) ?? 0) || flow.state !== 'waiting')
353
+ return;
246
354
  flow.state = 'done';
247
355
  this.ready.set(id, true);
248
356
  for (const s of [this.lapsed, this.without])
@@ -307,6 +415,17 @@ export class Accounts {
307
415
  this.flows.delete(`${member}:${key}`);
308
416
  this.onChange?.(member, key);
309
417
  }
418
+ async refreshed(member, key, minOAuthValidityMs) {
419
+ const pi = this.offer(key).pi;
420
+ return (await this.runtime(member)).getAuth(pi, { minOAuthValidityMs }).then(Boolean, async (e) => {
421
+ if (offline(e))
422
+ return true;
423
+ if (e?.message !== `OAuth refresh returned a token that expires too soon for ${pi}`)
424
+ return false;
425
+ const c = await this.store(member).read(pi);
426
+ return c?.type === 'oauth' && c.expires > Date.now();
427
+ });
428
+ }
310
429
  /** Refresh every signed-in account an hour ahead of expiry (call it now and then), so a sign-in never lapses while
311
430
  * nobody is looking. Only the provider refusing signs it out, and `onExpired` says so once; a network hiccup doesn't. */
312
431
  async keepFresh(members) {
@@ -314,7 +433,7 @@ export class Accounts {
314
433
  for (const p of this.providers) {
315
434
  if (this.ready.get(`${m}:${p.key}`) !== true)
316
435
  continue;
317
- const ok = await (await this.runtime(m)).getAuth(p.pi, { minOAuthValidityMs: 60 * 60_000 }).then(Boolean, offline);
436
+ const ok = await this.refreshed(m, p.key, 60 * 60_000);
318
437
  if (!ok) {
319
438
  this.forget(m, p.key);
320
439
  this.onExpired?.(m, p.key);
@@ -323,9 +442,7 @@ export class Accounts {
323
442
  }
324
443
  /** After the account turned a request away: true if its sign-in still refreshes; if not, it is signed out for good. */
325
444
  async recheck(member, key) {
326
- // Asking for a year's validity forces a refresh; the fresh token then "expires too soon" for that year, which is fine.
327
- const ok = await (await this.runtime(member)).getAuth(this.offer(key).pi, { minOAuthValidityMs: 365 * 86_400_000 })
328
- .then(Boolean, (e) => offline(e) || /expires too soon/.test(String(e?.message)));
445
+ const ok = await this.refreshed(member, key, 365 * 86_400_000);
329
446
  if (!ok) {
330
447
  await this.logout(member, key).catch(() => { });
331
448
  this.forget(member, key);
@@ -333,17 +450,37 @@ export class Accounts {
333
450
  return ok;
334
451
  }
335
452
  /** Signs out here, and at the provider too where it can end a sign-in (ChatGPT), best effort: the sign-in is deleted
336
- * here whatever the provider answers. The revoke runs in the store's own turn, so a refresh under way finishes first
337
- * and the token it rotated to is the one ended; a refresh after it is refused. */
453
+ * here whatever the provider answers. */
338
454
  async logout(member, key) {
339
455
  const p = this.offer(key);
340
- const url = p.revoke && (this.opts.authBase ? `${this.opts.authBase}/oauth/revoke` : p.revoke);
341
- if (url)
342
- await this.store(member).modify(p.pi, async (c) => { if (c?.type === 'oauth')
343
- await revoke(url, p.clientId, c).catch(() => { }); return undefined; }).catch(() => { });
344
- await (await this.runtime(member)).logout(p.pi);
345
- this.ready.set(`${member}:${key}`, false);
346
- this.onChange?.(member, key);
456
+ const id = `${member}:${key}`;
457
+ this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
458
+ this.cancel(member, key);
459
+ const work = (async () => {
460
+ const rt = await this.runtime(member);
461
+ let error;
462
+ try {
463
+ if (p.revoke)
464
+ await rt.credentialStore.signOut(p.pi, p);
465
+ else
466
+ await rt.logout(p.pi);
467
+ }
468
+ catch (e) {
469
+ error = e;
470
+ }
471
+ this.ready.set(id, false);
472
+ this.onChange?.(member, key);
473
+ if (error)
474
+ throw error;
475
+ })();
476
+ this.signingOut.set(id, work);
477
+ try {
478
+ await work;
479
+ }
480
+ finally {
481
+ if (this.signingOut.get(id) === work)
482
+ this.signingOut.delete(id);
483
+ }
347
484
  }
348
485
  view(member, key) {
349
486
  const f = this.flows.get(`${member}:${key}`);
package/dist/engine.js CHANGED
@@ -17,11 +17,11 @@ export function deviceStart(status, body) {
17
17
  if (status === 404)
18
18
  throw new Error('OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.');
19
19
  if (status < 200 || status > 299)
20
- throw new Error(`OpenAI Codex device code request failed with status ${status}${body ? `: ${body}` : ''}`);
20
+ throw new Error(`OpenAI Codex device code request failed with status ${status}`);
21
21
  const j = json(body);
22
22
  const intervalSeconds = typeof j?.interval === 'string' ? Number(j.interval.trim()) : j?.interval;
23
23
  if (!j?.device_auth_id || !j.user_code || typeof intervalSeconds !== 'number' || !Number.isFinite(intervalSeconds) || intervalSeconds < 0)
24
- throw new Error(`Invalid OpenAI Codex device code response: ${body}`);
24
+ throw new Error('Invalid OpenAI Codex device code response');
25
25
  return { deviceAuthId: String(j.device_auth_id), userCode: String(j.user_code), intervalSeconds };
26
26
  }
27
27
  export function devicePoll(status, body) {
@@ -29,7 +29,7 @@ export function devicePoll(status, body) {
29
29
  const j = json(body);
30
30
  return j?.authorization_code && j.code_verifier
31
31
  ? { status: 'complete', authorizationCode: j.authorization_code, codeVerifier: j.code_verifier }
32
- : { status: 'failed', message: `Invalid OpenAI Codex device auth token response: ${body}` };
32
+ : { status: 'failed', message: 'Invalid OpenAI Codex device auth token response' };
33
33
  }
34
34
  if (status === 403 || status === 404)
35
35
  return { status: 'pending' };
@@ -39,12 +39,13 @@ export function devicePoll(status, body) {
39
39
  return { status: 'pending' };
40
40
  if (code === 'slow_down')
41
41
  return { status: 'slow_down' };
42
- return { status: 'failed', message: `OpenAI Codex device auth failed with status ${status}${body ? `: ${body}` : ''}` };
42
+ const detail = code === 'deviceauth_expired' || code === 'access_denied' ? `: ${code}` : '';
43
+ return { status: 'failed', message: `OpenAI Codex device auth failed with status ${status}${detail}` };
43
44
  }
44
45
  /** A token response as the stored credential, the same shape Pi keeps. */
45
46
  export function credentialOf(j, now = Date.now()) {
46
47
  if (typeof j?.access_token !== 'string' || typeof j.refresh_token !== 'string' || typeof j.expires_in !== 'number')
47
- throw new Error(`OpenAI Codex token response missing fields: ${JSON.stringify(j)}`);
48
+ throw new Error('OpenAI Codex token response missing fields');
48
49
  let accountId;
49
50
  try {
50
51
  accountId = claims(j.access_token)['https://api.openai.com/auth']?.chatgpt_account_id;
@@ -81,7 +82,7 @@ export function portableEngine(credentials, { base = 'https://auth.openai.com' }
81
82
  };
82
83
  const tokens = async (what, r) => {
83
84
  if (r.status < 200 || r.status > 299)
84
- throw new Error(`OpenAI Codex token ${what} failed (${r.status}): ${r.body}`);
85
+ throw new Error(`OpenAI Codex token ${what} failed (${r.status})`);
85
86
  return credentialOf(json(r.body));
86
87
  };
87
88
  const refresh = async (c) => {
@@ -123,7 +124,18 @@ export function portableEngine(credentials, { base = 'https://auth.openai.com' }
123
124
  }, true, signal));
124
125
  if (signal?.aborted)
125
126
  throw new Error('Login cancelled');
126
- await credentials.modify(id, async () => c);
127
+ let wrote = false;
128
+ await credentials.modify(id, async () => {
129
+ if (signal?.aborted)
130
+ return undefined;
131
+ wrote = true;
132
+ return c;
133
+ }, { signal });
134
+ if (signal?.aborted) {
135
+ if (wrote)
136
+ await credentials.delete(id);
137
+ throw new Error('Login cancelled');
138
+ }
127
139
  return c;
128
140
  }
129
141
  if (p.status === 'slow_down')
@@ -146,8 +158,6 @@ export function portableEngine(credentials, { base = 'https://auth.openai.com' }
146
158
  c = await credentials.modify(id, async (now) => (now?.type === 'oauth' && soon(now) ? refresh(now) : undefined));
147
159
  if (c?.type !== 'oauth')
148
160
  return undefined;
149
- if (minOAuthValidityMs !== undefined && soon(c))
150
- throw new Error('OAuth refresh returned a token that expires too soon for openai-codex');
151
161
  }
152
162
  return { auth: { apiKey: c.access }, source: 'OAuth' };
153
163
  },
package/dist/stores.d.ts CHANGED
@@ -2,9 +2,12 @@ import type { Credential, CredentialStore } from '@earendil-works/pi-ai';
2
2
  export type Record = {
3
3
  [providerId: string]: Credential;
4
4
  };
5
+ export type EndingStore = CredentialStore & {
6
+ end(id: string, fn: (c: Credential | undefined) => Promise<void>): Promise<void>;
7
+ };
5
8
  /** A store over one whole record the platform loads and saves. Writes are serialized within this process; a write
6
9
  * re-reads first, so a sign-in that took minutes never overwrites a provider that changed meanwhile. */
7
- export declare function recordStore(load: () => Promise<Record>, save: (data: Record) => Promise<void>): CredentialStore;
10
+ export declare function recordStore(load: () => Promise<Record>, save: (data: Record) => Promise<void>): EndingStore;
8
11
  export declare function memoryStore(): CredentialStore;
9
12
  /** The parts of `expo-secure-store` this uses (Keychain on iOS, Keystore-encrypted on Android); pass the module itself. */
10
13
  export type SecureStoreLike = {
@@ -18,4 +21,4 @@ export type SecureStoreLike = {
18
21
  export declare function secureStore(secure: SecureStoreLike, name: string): CredentialStore;
19
22
  /** One person's sign-ins in the browser's IndexedDB (a PWA, or Electron's renderer), under `name`. A browser has no
20
23
  * keychain: anything running on this page could read them, so keep the page free of scripts you don't control. */
21
- export declare function browserStore(name: string, db?: string): CredentialStore;
24
+ export declare function browserStore(name: string, db?: string): EndingStore;
package/dist/stores.js CHANGED
@@ -6,11 +6,13 @@ export function recordStore(load, save) {
6
6
  return {
7
7
  read: async (id) => (await load())[id],
8
8
  list: async () => Object.entries(await load()).map(([providerId, c]) => ({ providerId, type: c.type })),
9
- modify: (id, fn) => serial(async () => {
9
+ modify: (id, fn, options) => serial(async () => {
10
10
  const current = (await load())[id];
11
11
  const next = await fn(current);
12
12
  if (next === undefined)
13
13
  return current;
14
+ if (options?.signal?.aborted)
15
+ throw new Error('Login cancelled');
14
16
  await save({ ...(await load()), [id]: next });
15
17
  return next;
16
18
  }),
@@ -18,6 +20,18 @@ export function recordStore(load, save) {
18
20
  delete data[id];
19
21
  await save(data);
20
22
  } }),
23
+ end: (id, fn) => serial(async () => {
24
+ try {
25
+ await fn((await load())[id]);
26
+ }
27
+ finally {
28
+ const data = await load();
29
+ if (id in data) {
30
+ delete data[id];
31
+ await save(data);
32
+ }
33
+ }
34
+ }),
21
35
  };
22
36
  }
23
37
  export function memoryStore() {
@@ -74,5 +88,12 @@ export function browserStore(name, db = 'byokit') {
74
88
  d.close();
75
89
  }
76
90
  };
77
- return recordStore(async () => (await run('readonly', (s) => s.get(name))) ?? {}, (data) => run('readwrite', (s) => s.put(data, name)));
91
+ const store = recordStore(async () => (await run('readonly', (s) => s.get(name))) ?? {}, (data) => run('readwrite', (s) => s.put(data, name)));
92
+ const locked = async (id, fn) => typeof navigator !== 'undefined' && navigator.locks ? await navigator.locks.request(`byokit:${db}:${name}:${id}`, fn) : fn();
93
+ return {
94
+ ...store,
95
+ modify: (id, fn, options) => locked(id, () => store.modify(id, fn, options)),
96
+ delete: (id, options) => locked(id, () => store.delete(id, options)),
97
+ end: (id, fn) => locked(id, () => store.end(id, fn)),
98
+ };
78
99
  }
@@ -1,7 +1,7 @@
1
1
  // OpenAI's sign-in, stood in for: device code, its page where a person types the code, token exchange and refresh
2
2
  // (rotating), revoke, and the same CORS answer the real endpoints give, so a web page, a phone app or a test signs in
3
3
  // end to end with no account and no real network. Run it alone for a demo or an emulator:
4
- // node packages/accounts/src/testing/mock-openai.ts [port] (then approve on its /codex/device page)
4
+ // node packages/accounts/src/testing/mock-openai.ts [port] (21455 by default, never ChatGPT's own 1455)
5
5
  import { createServer } from 'node:http';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  /** An access token as OpenAI shapes it: the account, the plan and the email in its claims. */
@@ -107,6 +107,6 @@ export async function mockOpenAI({ port = 0, host = '127.0.0.1', plan = 'plus',
107
107
  };
108
108
  }
109
109
  if (process.argv[1] === fileURLToPath(import.meta.url)) {
110
- const m = await mockOpenAI({ port: Number(process.argv[2] ?? 1455), host: '0.0.0.0', log: (line) => console.log(new Date().toISOString().slice(11, 19), line) });
110
+ const m = await mockOpenAI({ port: Number(process.argv[2] ?? 21455), host: '0.0.0.0', log: (line) => console.log(new Date().toISOString().slice(11, 19), line) });
111
111
  console.log(`stand-in OpenAI on ${m.base}; approve codes at ${m.base}/codex/device`);
112
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byokit/accounts",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Sign in with the AI plan you already pay for, into your app's own store.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -25,10 +25,6 @@
25
25
  "types": "./dist/index.d.ts",
26
26
  "default": "./dist/index.js"
27
27
  },
28
- "./portable": {
29
- "types": "./dist/portable.d.ts",
30
- "default": "./dist/portable.js"
31
- },
32
28
  "./isolate": {
33
29
  "types": "./dist/isolate.d.ts",
34
30
  "default": "./dist/isolate.js"