@byokit/accounts 0.2.0 → 0.2.1

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/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.1",
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"