@byokit/accounts 0.3.1 → 0.4.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.4.0
6
+
7
+ - Each catalogue row carries its billing (`subscription`, `api`); show `billingWords(p)` next to every provider you list.
8
+ - FIX: OpenRouter (API billing) is no longer offered by default on computers; `offered()` without keys returns subscription rows only. Name it explicitly (`offer: ['openrouter']`) to keep offering it.
9
+ - FIX: a locked-keychain read (iOS returns "User interaction is not allowed" while the phone is locked) no longer signs the person out: `keepFresh` treats it as unknown and tries later, only a refused refresh fires `onExpired`.
10
+ - `secureStore(secure, name, options?)` passes `options` (e.g. `{ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }`) to every keychain get, set and delete; the default is unchanged.
11
+ ## 0.3.1
12
+
13
+ - `respond(member, { instructions, input, onText })` asks ChatGPT with the member's own sign-in, the answer streaming in over an injected `fetch` (whole answer at once when the fetch can't stream); limits and lapsed sign-ins are acted on as `failed()` does.
14
+ - FIX: a plain HTTP 429 or an undated `rate_limit_exceeded` is a temporary rate limit, not "plan doesn't include this"; a streamed error keeps its code.
15
+ - FIX: a refresh that fails on the network before asking is reported as network trouble; a refused refresh signs the account out.
16
+
17
+ ## 0.3.0
18
+
19
+ - FIX: `@byokit/accounts/testing` `decoy()` now requires a caller-owned root; migrate from `decoy()` to `decoy(root)` and clean up that root when done.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @byokit/accounts
2
2
 
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
3
+ Sign in with the AI plan you already pay for (ChatGPT on every platform; OpenRouter on computers when an app offers it
4
+ (API billing, never by default); Grok and GitHub Copilot hidden by default), inside your own app, into your app's own store: on a computer (Node, Electron), in a browser
5
5
  (a PWA, Electron's renderer) and on a
6
6
  phone (React Native and Expo, iOS and Android). One import; your bundler picks the platform's side
7
7
  (`package.json`'s `react-native` and `browser` conditions).
@@ -48,7 +48,7 @@ Examples: [`examples/expo`](../../examples/expo) (iOS and Android bundles; Andro
48
48
  | | Computer (Node, Electron main) | Browser (PWA, Electron renderer) | Phone (React Native: iOS, Android) |
49
49
  |---|---|---|---|
50
50
  | ChatGPT | Its own page, straight back to this computer (port 1455); a code when asked or stuck | Device code | Device code |
51
- | OpenRouter | Its own page, back to this computer (Pi's flow) | Not yet | Not yet |
51
+ | OpenRouter | Its own page, back to this computer (Pi's flow), when an app offers it (API billing, never by default) | Not yet | Not yet |
52
52
  | Grok, Copilot (hidden) | Pi's flows | No | No |
53
53
  | Where sign-ins are kept | `fileStore(path)`, sealed with Electron's `safeStorage` when given | `browserStore(name)` (IndexedDB) | `secureStore(SecureStore, name)` (Keychain, Keystore) |
54
54
 
@@ -57,10 +57,12 @@ listener on the computer the browser runs on, so it is desktop only: ChatGPT sen
57
57
  `localhost:1455`, fixed for the client this signs in as. A web page can't call ChatGPT's model endpoint itself (it
58
58
  doesn't answer other web pages), so a PWA's model calls go through the app's own server or relay.
59
59
 
60
- - **Catalogue** (`catalogue.json`): each provider with its terms status (`allowed`, `grey`, `partner`), a one-line reason
61
- and a source. The kit labels; your app decides what to offer (`new Accounts({ offer: ['chatgpt'] })`). Without an
62
- explicit `offer`, only sign-ins supported on this platform are shown; an explicit list is not platform-filtered, so
63
- choose from the table above. Claude plan sign-in is never offered: Anthropic reserves it for its own apps.
60
+ - **Catalogue** (`catalogue.json`): each provider with its billing (`subscription`, `api`) and terms status (`allowed`,
61
+ `grey`, `partner`), a one-line reason and a source. The kit labels; your app decides what to offer
62
+ (`new Accounts({ offer: ['chatgpt'] })`). Without an explicit `offer`, only subscription sign-ins supported on this
63
+ platform are shown: OpenRouter is API-billed and never offered by default. An explicit list is not
64
+ platform-filtered, so choose from the table above. Show `billingWords(p)` next to every provider you list.
65
+ Claude plan sign-in is never offered: Anthropic reserves it for its own apps.
64
66
  - **Sign-in**: on computers, the provider's own page by default. For ChatGPT, whose page returns to this computer's
65
67
  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
66
68
  true. A code takes over when asked ("Having trouble?"), when the page never comes back, or when the port is taken by
@@ -72,9 +74,14 @@ doesn't answer other web pages), so a PWA's model calls go through the app's own
72
74
  sign-out uses its rotated token. If a cancelled sign-in finishes late, `onSignOutError` reports a failed revoke of its
73
75
  discarded credential (or it is logged when no handler is set).
74
76
  - **One person, one store**: `memoryStore()`, `fileStore(path)` (0600, the same shape as Pi's `auth.json`),
75
- `secureStore(SecureStore, name)` or `browserStore(name)`; any other storage with `recordStore(load, save)`. Writes are
77
+ `secureStore(SecureStore, name, options?)` or `browserStore(name)`; any other storage with `recordStore(load, save)`. Writes are
76
78
  serialized within a store instance; `browserStore` also uses Web Locks across tabs for the same provider when available.
77
- Never a shared fallback. Browser storage is readable by scripts on your page: avoid untrusted scripts. Using another
79
+ Never a shared fallback. Browser storage is readable by scripts on your page: avoid untrusted scripts. On a phone, pass
80
+ `{ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }` as `options` (to every get, set and delete) so
81
+ tokens never migrate to a new device through an iCloud/iTunes backup; without it Expo's default (`WHEN_UNLOCKED`)
82
+ applies. iOS Keychain items survive an app reinstall under the same bundle id (Android data is gone): apps that must
83
+ forget on reinstall keep a first-run marker outside the Keychain (e.g. `expo-file-system` or `AsyncStorage`) and, when
84
+ it is missing, call `accounts.logout(member, key)` for each offered key before first use, which revokes and wipes. Using another
78
85
  engine with the same seam (Pi's coding-agent `ModelRuntime`)? Override `open(member)` with an engine whose
79
86
  `credentialStore` is made with `boundStore(member, engineStore)` and whose `readCredential(id)` reads that store.
80
87
  - **Asking**: `respond(member, { instructions, input, model?, onText?, signal? })` asks ChatGPT's own answers endpoint
package/dist/accounts.js CHANGED
@@ -455,10 +455,14 @@ export class Accounts {
455
455
  return (await this.runtime(member)).getAuth(pi, { minOAuthValidityMs }).then(Boolean, async (e) => {
456
456
  if (offline(e))
457
457
  return true;
458
- if (e?.message !== `OAuth refresh returned a token that expires too soon for ${pi}`)
459
- return false;
460
- const c = await this.store(member).read(pi);
461
- return c?.type === 'oauth' && c.expires > Date.now();
458
+ if (e?.message === `OAuth refresh returned a token that expires too soon for ${pi}`) {
459
+ const c = await this.store(member).read(pi);
460
+ return c?.type === 'oauth' && c.expires > Date.now();
461
+ }
462
+ // Only the provider refusing (400-403) counts as expiry. Anything else (a locked keychain read, storage failing)
463
+ // is unknown: try later, never sign the person out.
464
+ const status = e?.status;
465
+ return typeof status !== 'number' || status < 400 || status > 403;
462
466
  });
463
467
  }
464
468
  /** Refresh every signed-in account an hour ahead of expiry (call it now and then), so a sign-in never lapses while
@@ -1,4 +1,6 @@
1
1
  export type Terms = 'allowed' | 'grey' | 'partner' | 'forbidden';
2
+ /** How the person pays: their plan (`subscription`), or per-use charges to their account (`api`, never offered by default). */
3
+ export type Billing = 'subscription' | 'api';
2
4
  /** `callbackPort`: where the provider sends the browser back after its own sign-in page, fixed for the client Pi signs in as.
3
5
  * `revoke`: where signing out ends the sign-in on the provider's side too, for the client `clientId`. */
4
6
  export type Provider = {
@@ -13,6 +15,7 @@ export type Provider = {
13
15
  callbackPort?: number;
14
16
  clientId?: string;
15
17
  revoke?: string;
18
+ billing: Billing;
16
19
  terms: Terms;
17
20
  hidden: boolean;
18
21
  why: string;
@@ -20,5 +23,6 @@ export type Provider = {
20
23
  };
21
24
  export declare const PROVIDERS: Record<string, Provider>;
22
25
  export declare function provider(key: string): Provider;
23
- /** What an app offers: the keys it names, in its order, or every provider not hidden by default. */
26
+ /** What an app offers: the keys it names, in its order, or every subscription provider not hidden by default.
27
+ * API-billed rows are never in the default: an app offers them only by naming them. */
24
28
  export declare const offered: (keys?: readonly string[]) => Provider[];
package/dist/catalogue.js CHANGED
@@ -1,7 +1,8 @@
1
- // The AI accounts a person can bring, by the name they know, with each provider's terms status as data (catalogue.json,
2
- // readable from Kotlin too). The kit labels; the app decides what to offer. Claude plan sign-in is absent on purpose:
3
- // Anthropic reserves it for its own apps, so no app can wire it by mistake. Meta and Kimi are left out too (a
4
- // competitor by the owner's choice; Kimi refuses anything but coding agents).
1
+ // The AI accounts a person can bring, by the name they know, with each provider's billing and terms status as data
2
+ // (catalogue.json, readable from Kotlin too). The kit labels; the app decides what to offer. API-billed rows are never
3
+ // offered by default; an app names them explicitly. Claude plan sign-in is absent on purpose: Anthropic reserves it for
4
+ // its own apps, so no app can wire it by mistake. Meta and Kimi are left out too (a competitor by the owner's choice;
5
+ // Kimi refuses anything but coding agents).
5
6
  import CATALOGUE from './catalogue.json' with { type: 'json' };
6
7
  export const PROVIDERS = Object.fromEntries(Object.entries(CATALOGUE).map(([key, p]) => [key, { key, ...p }]));
7
8
  export function provider(key) {
@@ -10,5 +11,6 @@ export function provider(key) {
10
11
  throw Object.assign(new Error('no such AI account'), { status: 404 });
11
12
  return p;
12
13
  }
13
- /** What an app offers: the keys it names, in its order, or every provider not hidden by default. */
14
- export const offered = (keys) => keys ? keys.map(provider) : Object.values(PROVIDERS).filter((p) => !p.hidden);
14
+ /** What an app offers: the keys it names, in its order, or every subscription provider not hidden by default.
15
+ * API-billed rows are never in the default: an app offers them only by naming them. */
16
+ export const offered = (keys) => keys ? keys.map(provider) : Object.values(PROVIDERS).filter((p) => !p.hidden && p.billing === 'subscription');
@@ -10,6 +10,7 @@
10
10
  "callbackPort": 1455,
11
11
  "clientId": "app_EMoamEEZ73f0CkXaXp7hrann",
12
12
  "revoke": "https://auth.openai.com/oauth/revoke",
13
+ "billing": "subscription",
13
14
  "terms": "grey",
14
15
  "hidden": false,
15
16
  "why": "Signs in through Codex's own sign-in. OpenAI documents it for Codex, not for other apps, and has endorsed one other app using it.",
@@ -22,6 +23,7 @@
22
23
  "models": {
23
24
  "strong": "moonshotai/kimi-k2.6"
24
25
  },
26
+ "billing": "api",
25
27
  "terms": "allowed",
26
28
  "hidden": false,
27
29
  "why": "Documented sign-in for any app, no registration. Pay-as-you-go credits, not a subscription.",
@@ -34,6 +36,7 @@
34
36
  "models": {
35
37
  "strong": "grok-4.7"
36
38
  },
39
+ "billing": "subscription",
37
40
  "terms": "partner",
38
41
  "hidden": true,
39
42
  "why": "xAI allows plan sign-in only in apps it has partnered with.",
@@ -46,6 +49,7 @@
46
49
  "models": {
47
50
  "strong": "gpt-5.4"
48
51
  },
52
+ "billing": "subscription",
49
53
  "terms": "partner",
50
54
  "hidden": true,
51
55
  "why": "GitHub allows Copilot sign-in only in apps it has partnered with; this uses VS Code's client.",
@@ -1,7 +1,7 @@
1
1
  export { Accounts, planOf, portable, type AccountsOptions, type AuthHost, type Loopback, type Member, type Platform, type SignIn, type Status } from './accounts.ts';
2
- export { PROVIDERS, offered, provider, type Provider, type Terms } from './catalogue.ts';
2
+ export { PROVIDERS, offered, provider, type Billing, type Provider, type Terms } from './catalogue.ts';
3
3
  export { PORTABLE, claims, credentialOf, devicePoll, deviceStart, portableEngine, type EngineOptions, type Poll } from './engine.ts';
4
4
  export { REST_MS, classify, type Kind } from './limits.ts';
5
5
  export { ResponseError, limitResponse, respond, sseReader, type Ask } from './responses.ts';
6
6
  export { browserStore, memoryStore, recordStore, secureStore, type SecureStoreLike } from './stores.ts';
7
- export { WORDS, callbackPage, clock, failure, say, signInError, type WordKey, type Why } from './words.ts';
7
+ export { WORDS, billingWords, callbackPage, clock, failure, say, signInError, type WordKey, type Why } from './words.ts';
package/dist/portable.js CHANGED
@@ -6,4 +6,4 @@ export { PORTABLE, claims, credentialOf, devicePoll, deviceStart, portableEngine
6
6
  export { REST_MS, classify } from "./limits.js";
7
7
  export { ResponseError, limitResponse, respond, sseReader } from "./responses.js";
8
8
  export { browserStore, memoryStore, recordStore, secureStore } from "./stores.js";
9
- export { WORDS, callbackPage, clock, failure, say, signInError } from "./words.js";
9
+ export { WORDS, billingWords, callbackPage, clock, failure, say, signInError } from "./words.js";
package/dist/stores.d.ts CHANGED
@@ -9,16 +9,19 @@ export type EndingStore = CredentialStore & {
9
9
  * re-reads first, so a sign-in that took minutes never overwrites a provider that changed meanwhile. */
10
10
  export declare function recordStore(load: () => Promise<Record>, save: (data: Record) => Promise<void>): EndingStore;
11
11
  export declare function memoryStore(): CredentialStore;
12
- /** The parts of `expo-secure-store` this uses (Keychain on iOS, Keystore-encrypted on Android); pass the module itself. */
12
+ /** The parts of `expo-secure-store` this uses (Keychain on iOS, Keystore-encrypted on Android); pass the module itself.
13
+ * Every method takes the same optional `options` (e.g. `{ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }`). */
13
14
  export type SecureStoreLike = {
14
- getItemAsync(key: string): Promise<string | null>;
15
- setItemAsync(key: string, value: string): Promise<void>;
16
- deleteItemAsync(key: string): Promise<void>;
15
+ getItemAsync(key: string, options?: object): Promise<string | null>;
16
+ setItemAsync(key: string, value: string, options?: object): Promise<void>;
17
+ deleteItemAsync(key: string, options?: object): Promise<void>;
17
18
  };
18
19
  /** One person's sign-ins in the phone's secure storage: `secureStore(SecureStore, 'byokit.1')`. Keys may hold letters,
19
20
  * digits, `.`, `-` and `_`. The record is split into pieces under the 2048 bytes expo-secure-store warns about, written
20
- * as a new generation, then `name` is pointed at it: a crash mid-write leaves the old sign-ins whole. */
21
- export declare function secureStore(secure: SecureStoreLike, name: string): CredentialStore;
21
+ * as a new generation, then `name` is pointed at it: a crash mid-write leaves the old sign-ins whole. `options` (e.g.
22
+ * `{ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }`) is passed to every get, set and delete;
23
+ * without it Expo's default (`WHEN_UNLOCKED`) applies. */
24
+ export declare function secureStore(secure: SecureStoreLike, name: string, options?: object): CredentialStore;
22
25
  /** One person's sign-ins in the browser's IndexedDB (a PWA, or Electron's renderer), under `name`. A browser has no
23
26
  * keychain: anything running on this page could read them, so keep the page free of scripts you don't control. */
24
27
  export declare function browserStore(name: string, db?: string): EndingStore;
package/dist/stores.js CHANGED
@@ -40,14 +40,16 @@ export function memoryStore() {
40
40
  }
41
41
  /** One person's sign-ins in the phone's secure storage: `secureStore(SecureStore, 'byokit.1')`. Keys may hold letters,
42
42
  * digits, `.`, `-` and `_`. The record is split into pieces under the 2048 bytes expo-secure-store warns about, written
43
- * as a new generation, then `name` is pointed at it: a crash mid-write leaves the old sign-ins whole. */
44
- export function secureStore(secure, name) {
45
- const head = async () => { const [gen = '0', n = '0'] = (await secure.getItemAsync(name))?.split(':') ?? []; return { gen: Number(gen), n: Number(n) }; };
43
+ * as a new generation, then `name` is pointed at it: a crash mid-write leaves the old sign-ins whole. `options` (e.g.
44
+ * `{ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }`) is passed to every get, set and delete;
45
+ * without it Expo's default (`WHEN_UNLOCKED`) applies. */
46
+ export function secureStore(secure, name, options) {
47
+ const head = async () => { const [gen = '0', n = '0'] = (await secure.getItemAsync(name, options))?.split(':') ?? []; return { gen: Number(gen), n: Number(n) }; };
46
48
  const load = async () => {
47
49
  const { gen, n } = await head();
48
50
  let text = '';
49
51
  for (let i = 0; i < n; i++)
50
- text += (await secure.getItemAsync(`${name}.${gen}.${i}`)) ?? '';
52
+ text += (await secure.getItemAsync(`${name}.${gen}.${i}`, options)) ?? '';
51
53
  return text ? JSON.parse(text) : {};
52
54
  };
53
55
  const save = async (data) => {
@@ -55,13 +57,13 @@ export function secureStore(secure, name) {
55
57
  const gen = old.gen + 1;
56
58
  const parts = (Object.keys(data).length ? JSON.stringify(data) : '').match(/[\s\S]{1,1800}/g) ?? [];
57
59
  for (const [i, part] of parts.entries())
58
- await secure.setItemAsync(`${name}.${gen}.${i}`, part);
59
- await secure.setItemAsync(name, `${gen}:${parts.length}`);
60
+ await secure.setItemAsync(`${name}.${gen}.${i}`, part, options);
61
+ await secure.setItemAsync(name, `${gen}:${parts.length}`, options);
60
62
  for (let i = 0; i < old.n; i++)
61
- await secure.deleteItemAsync(`${name}.${old.gen}.${i}`);
63
+ await secure.deleteItemAsync(`${name}.${old.gen}.${i}`, options);
62
64
  // Leftovers of a write that crashed at this generation before.
63
- for (let i = parts.length; (await secure.getItemAsync(`${name}.${gen}.${i}`)) !== null; i++)
64
- await secure.deleteItemAsync(`${name}.${gen}.${i}`);
65
+ for (let i = parts.length; (await secure.getItemAsync(`${name}.${gen}.${i}`, options)) !== null; i++)
66
+ await secure.deleteItemAsync(`${name}.${gen}.${i}`, options);
65
67
  };
66
68
  return recordStore(load, save);
67
69
  }
package/dist/words.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import WORDS from './words.json';
2
+ import type { Provider } from './catalogue.ts';
2
3
  export type WordKey = keyof typeof WORDS;
3
4
  export { WORDS };
4
5
  /** A sentence with its `{slots}` filled. */
@@ -8,6 +9,8 @@ export declare const clock: (t: number) => string;
8
9
  /** Why a sign-in failed, from the engine's own error. */
9
10
  export type Why = 'expired' | 'declined' | 'offline' | 'deviceCodeOff' | 'busy' | 'tooLong' | 'failed';
10
11
  export declare function failure(error: string): Why;
12
+ /** What the person pays, in one plain sentence to show next to the provider. */
13
+ export declare const billingWords: (p: Provider) => string;
11
14
  /** A failed sign-in in one plain sentence with one next step. */
12
15
  export declare const signInError: (name: string, error: string) => string;
13
16
  /** The app's own page for the browser tab a provider sends back: it says how it really went, never "success" before it is. */
package/dist/words.js CHANGED
@@ -20,6 +20,8 @@ export function failure(error) {
20
20
  return 'deviceCodeOff';
21
21
  return 'failed';
22
22
  }
23
+ /** What the person pays, in one plain sentence to show next to the provider. */
24
+ export const billingWords = (p) => say(`billing.${p.billing}`, { name: p.name, company: p.company });
23
25
  /** A failed sign-in in one plain sentence with one next step. */
24
26
  export const signInError = (name, error) => say(`signIn.${failure(error)}`, { name });
25
27
  /** The app's own page for the browser tab a provider sends back: it says how it really went, never "success" before it is. */
package/dist/words.json CHANGED
@@ -18,6 +18,8 @@
18
18
  "status.signedOut": "{name} isn't signed in yet.",
19
19
  "status.needsAgain": "{name} needs you to sign in again.",
20
20
  "terms.grey": "Uses your {name} plan. {company} may change this at any time.",
21
+ "billing.subscription": "Uses your {name} plan.",
22
+ "billing.api": "Charged per use to your {company} account, not a plan.",
21
23
  "status.notIncluded": "Your {name} plan doesn't include this yet.",
22
24
  "callback.done": "You're signed in. You can go back to {app} now.",
23
25
  "callback.declined": "No problem. Nothing was changed. You can go back to {app}.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byokit/accounts",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
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",
@@ -35,7 +35,8 @@
35
35
  }
36
36
  },
37
37
  "files": [
38
- "dist"
38
+ "dist",
39
+ "CHANGELOG.md"
39
40
  ],
40
41
  "scripts": {
41
42
  "prepack": "tsc -b"