@tensorpass/aiconnect 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +18 -2
  4. package/dist/callback.d.ts +2 -0
  5. package/dist/callback.js +4 -0
  6. package/dist/callback.js.map +1 -0
  7. package/dist/chatContent.d.ts +9 -0
  8. package/dist/chatContent.js +23 -0
  9. package/dist/chatContent.js.map +1 -0
  10. package/dist/cli/loopbackSignIn.d.ts +11 -0
  11. package/dist/cli/loopbackSignIn.js +94 -0
  12. package/dist/cli/loopbackSignIn.js.map +1 -0
  13. package/dist/cli/main.d.ts +2 -0
  14. package/dist/cli/main.js +41 -0
  15. package/dist/cli/main.js.map +1 -0
  16. package/dist/cli/siteKeyCommand.d.ts +11 -0
  17. package/dist/cli/siteKeyCommand.js +31 -0
  18. package/dist/cli/siteKeyCommand.js.map +1 -0
  19. package/dist/cli/siteKeyPlacement.d.ts +3 -0
  20. package/dist/cli/siteKeyPlacement.js +56 -0
  21. package/dist/cli/siteKeyPlacement.js.map +1 -0
  22. package/dist/client.d.ts +43 -0
  23. package/dist/client.js +211 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/connectionState.d.ts +31 -0
  26. package/dist/connectionState.js +4 -0
  27. package/dist/connectionState.js.map +1 -0
  28. package/dist/guards/answerGuard.d.ts +14 -0
  29. package/dist/guards/answerGuard.js +189 -0
  30. package/dist/guards/answerGuard.js.map +1 -0
  31. package/dist/guards/chatGuard.d.ts +18 -0
  32. package/dist/guards/chatGuard.js +62 -0
  33. package/dist/guards/chatGuard.js.map +1 -0
  34. package/dist/guards/envelopes.d.ts +8 -0
  35. package/dist/guards/envelopes.js +49 -0
  36. package/dist/guards/envelopes.js.map +1 -0
  37. package/dist/guards/index.d.ts +8 -0
  38. package/dist/guards/index.js +8 -0
  39. package/dist/guards/index.js.map +1 -0
  40. package/dist/guards/policy.d.ts +28 -0
  41. package/dist/guards/policy.js +20 -0
  42. package/dist/guards/policy.js.map +1 -0
  43. package/dist/guards/questionGuard.d.ts +8 -0
  44. package/dist/guards/questionGuard.js +53 -0
  45. package/dist/guards/questionGuard.js.map +1 -0
  46. package/dist/index.d.ts +22 -0
  47. package/dist/index.js +16 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/mcpToolSource.d.ts +13 -0
  50. package/dist/mcpToolSource.js +54 -0
  51. package/dist/mcpToolSource.js.map +1 -0
  52. package/dist/toolLoop.d.ts +18 -0
  53. package/dist/toolLoop.js +153 -0
  54. package/dist/toolLoop.js.map +1 -0
  55. package/dist/types.d.ts +98 -0
  56. package/dist/types.js +6 -0
  57. package/dist/types.js.map +1 -0
  58. package/dist/visitorBrowser.d.ts +17 -0
  59. package/dist/visitorBrowser.js +72 -0
  60. package/dist/visitorBrowser.js.map +1 -0
  61. package/dist/walletProvider.d.ts +25 -0
  62. package/dist/walletProvider.js +42 -0
  63. package/dist/walletProvider.js.map +1 -0
  64. package/dist/webAccounts/finishSignIn.d.ts +2 -0
  65. package/dist/webAccounts/finishSignIn.js +46 -0
  66. package/dist/webAccounts/finishSignIn.js.map +1 -0
  67. package/dist/webAccounts/openAiCompatibleSession.d.ts +15 -0
  68. package/dist/webAccounts/openAiCompatibleSession.js +84 -0
  69. package/dist/webAccounts/openAiCompatibleSession.js.map +1 -0
  70. package/dist/webAccounts/openAiWire.d.ts +39 -0
  71. package/dist/webAccounts/openAiWire.js +133 -0
  72. package/dist/webAccounts/openAiWire.js.map +1 -0
  73. package/dist/webAccounts/openRouterAccount.d.ts +3 -0
  74. package/dist/webAccounts/openRouterAccount.js +64 -0
  75. package/dist/webAccounts/openRouterAccount.js.map +1 -0
  76. package/dist/webAccounts/pkce.d.ts +2 -0
  77. package/dist/webAccounts/pkce.js +17 -0
  78. package/dist/webAccounts/pkce.js.map +1 -0
  79. package/dist/webAccounts/serverSentEvents.d.ts +1 -0
  80. package/dist/webAccounts/serverSentEvents.js +62 -0
  81. package/dist/webAccounts/serverSentEvents.js.map +1 -0
  82. package/dist/webAccounts/signInWindow.d.ts +27 -0
  83. package/dist/webAccounts/signInWindow.js +164 -0
  84. package/dist/webAccounts/signInWindow.js.map +1 -0
  85. package/dist/webAccounts/tensorPassAccount.d.ts +9 -0
  86. package/dist/webAccounts/tensorPassAccount.js +128 -0
  87. package/dist/webAccounts/tensorPassAccount.js.map +1 -0
  88. package/dist/webAccounts/tensorPassPlan.d.ts +27 -0
  89. package/dist/webAccounts/tensorPassPlan.js +36 -0
  90. package/dist/webAccounts/tensorPassPlan.js.map +1 -0
  91. package/dist/webAccounts/webAccount.d.ts +30 -0
  92. package/dist/webAccounts/webAccount.js +19 -0
  93. package/dist/webAccounts/webAccount.js.map +1 -0
  94. package/dist/webAccounts/webAccountSource.d.ts +43 -0
  95. package/dist/webAccounts/webAccountSource.js +216 -0
  96. package/dist/webAccounts/webAccountSource.js.map +1 -0
  97. package/dist/webAccounts/webAccountStore.d.ts +27 -0
  98. package/dist/webAccounts/webAccountStore.js +84 -0
  99. package/dist/webAccounts/webAccountStore.js.map +1 -0
  100. package/dist/wireProtocols/anthropicMessages.d.ts +2 -0
  101. package/dist/wireProtocols/anthropicMessages.js +181 -0
  102. package/dist/wireProtocols/anthropicMessages.js.map +1 -0
  103. package/dist/wireProtocols/eventStream.d.ts +4 -0
  104. package/dist/wireProtocols/eventStream.js +32 -0
  105. package/dist/wireProtocols/eventStream.js.map +1 -0
  106. package/dist/wireProtocols/geminiContents.d.ts +2 -0
  107. package/dist/wireProtocols/geminiContents.js +201 -0
  108. package/dist/wireProtocols/geminiContents.js.map +1 -0
  109. package/dist/wireProtocols/openAiChat.d.ts +2 -0
  110. package/dist/wireProtocols/openAiChat.js +161 -0
  111. package/dist/wireProtocols/openAiChat.js.map +1 -0
  112. package/dist/wireProtocols/openAiResponses.d.ts +2 -0
  113. package/dist/wireProtocols/openAiResponses.js +226 -0
  114. package/dist/wireProtocols/openAiResponses.js.map +1 -0
  115. package/dist/wireProtocols/walletAnswer.d.ts +7 -0
  116. package/dist/wireProtocols/walletAnswer.js +50 -0
  117. package/dist/wireProtocols/walletAnswer.js.map +1 -0
  118. package/dist/wireProtocols/walletFetch.d.ts +3 -0
  119. package/dist/wireProtocols/walletFetch.js +101 -0
  120. package/dist/wireProtocols/walletFetch.js.map +1 -0
  121. package/dist/wireProtocols/wireProtocol.d.ts +31 -0
  122. package/dist/wireProtocols/wireProtocol.js +44 -0
  123. package/dist/wireProtocols/wireProtocol.js.map +1 -0
  124. package/package.json +56 -4
@@ -0,0 +1,128 @@
1
+ // TensorPass's plan for a visitor without the wallet. The site names itself with its public site key:
2
+ // the visitor signs in on TensorPass's page, which names the site's origin, and comes back with a code the
3
+ // page trades, with its PKCE verifier, for a plan token of a few minutes bound to the site's origin and a
4
+ // refresh token that works once. The page calls the plan's gateway with the token and asks for the plan's
5
+ // level as the model. An account without a subscription reads the plans and subscribes on TensorPass's
6
+ // billing page (tensorPassPlan.ts).
7
+ //
8
+ // Every tab of the site shares the stored tokens, and a refresh token used twice ends the sign in, so a
9
+ // renewal runs under a lock the tabs share and reads the store again first: another tab may have renewed.
10
+ import { WalletRequestError } from "../walletProvider.js";
11
+ import { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from "./webAccount.js";
12
+ import { webSession } from "./openAiCompatibleSession.js";
13
+ import { planAccess } from "./tensorPassPlan.js";
14
+ export const PLAN_GATEWAY = 'https://plan.tensorpass.app';
15
+ const NAME = WEB_ACCOUNT_NAMES.tensorpass;
16
+ // A token this close to its end is renewed before the call.
17
+ const RENEW_BEFORE_MS = 60_000;
18
+ const RENEW_LOCK = 'aiconnect:tensorpass-renewal';
19
+ async function postForm(endpoint, path, fields) {
20
+ return endpoint.send(`${endpoint.url}${path}`, {
21
+ method: 'POST',
22
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
23
+ body: new URLSearchParams({ client_id: endpoint.siteKey, ...fields }).toString(),
24
+ });
25
+ }
26
+ async function tokensOf(response) {
27
+ const body = await jsonOf(response);
28
+ const { access_token: accessToken, refresh_token: refreshToken, expires_in: expiresIn } = body;
29
+ if (!response.ok || typeof accessToken !== 'string' || typeof refreshToken !== 'string') {
30
+ throw new WalletRequestError(`${NAME}: ${replyMessage(body, `the sign in answered ${response.status}`)}`, response.status);
31
+ }
32
+ const seconds = typeof expiresIn === 'number' ? expiresIn : 0;
33
+ return { account: 'tensorpass', accessToken, refreshToken, expiresAt: Date.now() + seconds * 1000 };
34
+ }
35
+ // Runs the work under a lock every tab of the origin shares, where the browser has Web Locks.
36
+ function underLock(work) {
37
+ const locks = globalThis.navigator?.locks;
38
+ return locks ? locks.request(RENEW_LOCK, work) : work();
39
+ }
40
+ // The stored credential renewed, or null once the gateway refuses the refresh token: the visitor signs in
41
+ // again. `stale` is the access token the caller found too old or refused.
42
+ function renewer(endpoint, store, onSignedOut) {
43
+ return (stale) => underLock(async () => {
44
+ const held = store.read();
45
+ if (held?.account !== 'tensorpass') {
46
+ return null;
47
+ }
48
+ if (held.accessToken !== stale && held.expiresAt - RENEW_BEFORE_MS > Date.now()) {
49
+ return held;
50
+ }
51
+ const response = await postForm(endpoint, '/oauth/token', {
52
+ grant_type: 'refresh_token', refresh_token: held.refreshToken,
53
+ });
54
+ if (response.status === 400 || response.status === 401) {
55
+ onSignedOut();
56
+ return null;
57
+ }
58
+ const renewed = await tokensOf(response);
59
+ store.save(renewed);
60
+ return renewed;
61
+ });
62
+ }
63
+ const bearer = (credential) => ({ Authorization: `Bearer ${credential.accessToken}` });
64
+ // The headers of the stored token, renewed first when it is close to its end, and after a refusal.
65
+ function tokenReader(endpoint, store, onSignedOut) {
66
+ const renew = renewer(endpoint, store, onSignedOut);
67
+ const held = () => {
68
+ const credential = store.read();
69
+ return credential?.account === 'tensorpass' ? credential : null;
70
+ };
71
+ return {
72
+ current: async () => {
73
+ const credential = held();
74
+ const fresh = credential && credential.expiresAt - RENEW_BEFORE_MS <= Date.now()
75
+ ? await renew(credential.accessToken) : credential;
76
+ return fresh ? bearer(fresh) : {};
77
+ },
78
+ renewed: async () => {
79
+ const renewed = await renew(held()?.accessToken ?? null);
80
+ return renewed ? bearer(renewed) : null;
81
+ },
82
+ };
83
+ }
84
+ export function tensorPassAccount(options) {
85
+ // The browser's fetch called as a method of another object throws, so it is wrapped.
86
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
87
+ const endpoint = { url: options.gateway, siteKey: options.siteKey, send };
88
+ return {
89
+ id: 'tensorpass',
90
+ name: NAME,
91
+ model: options.level,
92
+ authorizeUrl({ redirectUri, state, challenge }) {
93
+ const url = new URL(`${options.gateway}/signin`);
94
+ url.search = new URLSearchParams({
95
+ response_type: 'code', client_id: options.siteKey, redirect_uri: redirectUri, code_challenge: challenge,
96
+ code_challenge_method: 'S256', state,
97
+ }).toString();
98
+ return url.toString();
99
+ },
100
+ async exchange({ code, verifier, redirectUri }) {
101
+ return tokensOf(await postForm(endpoint, '/oauth/token', {
102
+ grant_type: 'authorization_code', code, code_verifier: verifier, redirect_uri: redirectUri,
103
+ }));
104
+ },
105
+ session(store, onSignedOut) {
106
+ const token = tokenReader(endpoint, store, onSignedOut);
107
+ return webSession({
108
+ providerId: 'tensorpass',
109
+ providerName: NAME,
110
+ model: options.level,
111
+ endpoint: `${options.gateway}/v1/chat/completions`,
112
+ fetch: options.fetch,
113
+ credential: token.current,
114
+ renew: token.renewed,
115
+ onRefused: onSignedOut,
116
+ });
117
+ },
118
+ plan(store, onSignedOut) {
119
+ return planAccess({ gateway: options.gateway, send, bearer: tokenReader(endpoint, store, onSignedOut).current });
120
+ },
121
+ async revoke(credential) {
122
+ if (credential.account === 'tensorpass') {
123
+ await postForm(endpoint, '/oauth/revoke', { token: credential.refreshToken }).catch(() => undefined);
124
+ }
125
+ },
126
+ };
127
+ }
128
+ //# sourceMappingURL=tensorPassAccount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tensorPassAccount.js","sourceRoot":"","sources":["../../src/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;YAC5C,OAAO,QAAQ,CAAC,MAAM,QAAQ,CAAC,QAAQ,EAAE,cAAc,EAAE;gBACvD,UAAU,EAAE,oBAAoB,EAAE,IAAI,EAAE,aAAa,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW;aAC3F,CAAC,CAAC,CAAC;QACN,CAAC;QACD,OAAO,CAAC,KAAK,EAAE,WAAW;YACxB,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;YACxD,OAAO,UAAU,CAAC;gBAChB,UAAU,EAAE,YAAY;gBACxB,YAAY,EAAE,IAAI;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,QAAQ,EAAE,GAAG,OAAO,CAAC,OAAO,sBAAsB;gBAClD,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,UAAU,EAAE,KAAK,CAAC,OAAO;gBACzB,KAAK,EAAE,KAAK,CAAC,OAAO;gBACpB,SAAS,EAAE,WAAW;aACvB,CAAC,CAAC;QACL,CAAC;QACD,IAAI,CAAC,KAAK,EAAE,WAAW;YACrB,OAAO,UAAU,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACnH,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,UAAU;YACrB,IAAI,UAAU,CAAC,OAAO,KAAK,YAAY,EAAE,CAAC;gBACxC,MAAM,QAAQ,CAAC,QAAQ,EAAE,eAAe,EAAE,EAAE,KAAK,EAAE,UAAU,CAAC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACvG,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// TensorPass's plan for a visitor without the wallet. The site names itself with its public site key:\n// the visitor signs in on TensorPass's page, which names the site's origin, and comes back with a code the\n// page trades, with its PKCE verifier, for a plan token of a few minutes bound to the site's origin and a\n// refresh token that works once. The page calls the plan's gateway with the token and asks for the plan's\n// level as the model. An account without a subscription reads the plans and subscribes on TensorPass's\n// billing page (tensorPassPlan.ts).\n//\n// Every tab of the site shares the stored tokens, and a refresh token used twice ends the sign in, so a\n// renewal runs under a lock the tabs share and reads the store again first: another tab may have renewed.\n\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { WebAccount, WebAccountContext } from './webAccount.ts';\nimport { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from './webAccount.ts';\nimport { webSession } from './openAiCompatibleSession.ts';\nimport type { HttpFetch } from './openAiCompatibleSession.ts';\nimport { planAccess } from './tensorPassPlan.ts';\nimport type { TensorPassCredential, WebAccountStore } from './webAccountStore.ts';\n\nexport const PLAN_GATEWAY = 'https://plan.tensorpass.app';\nexport type PlanLevel = 'quick' | 'smart' | 'expert';\nconst NAME = WEB_ACCOUNT_NAMES.tensorpass;\n// A token this close to its end is renewed before the call.\nconst RENEW_BEFORE_MS = 60_000;\nconst RENEW_LOCK = 'aiconnect:tensorpass-renewal';\n\nexport interface TensorPassOptions extends WebAccountContext {\n gateway: string;\n siteKey: string;\n level: PlanLevel;\n}\n\ninterface TokenEndpoint {\n url: string;\n siteKey: string;\n send: HttpFetch;\n}\n\nasync function postForm(endpoint: TokenEndpoint, path: string, fields: Record<string, string>) {\n return endpoint.send(`${endpoint.url}${path}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: endpoint.siteKey, ...fields }).toString(),\n });\n}\n\nasync function tokensOf(response: Response): Promise<TensorPassCredential> {\n const body = await jsonOf(response);\n const { access_token: accessToken, refresh_token: refreshToken, expires_in: expiresIn } = body;\n if (!response.ok || typeof accessToken !== 'string' || typeof refreshToken !== 'string') {\n throw new WalletRequestError(`${NAME}: ${replyMessage(body, `the sign in answered ${response.status}`)}`,\n response.status);\n }\n const seconds = typeof expiresIn === 'number' ? expiresIn : 0;\n return { account: 'tensorpass', accessToken, refreshToken, expiresAt: Date.now() + seconds * 1000 };\n}\n\n// Runs the work under a lock every tab of the origin shares, where the browser has Web Locks.\nfunction underLock<T>(work: () => Promise<T>): Promise<T> {\n const locks = (globalThis.navigator as Navigator | undefined)?.locks;\n return locks ? locks.request(RENEW_LOCK, work) : work();\n}\n\n// The stored credential renewed, or null once the gateway refuses the refresh token: the visitor signs in\n// again. `stale` is the access token the caller found too old or refused.\nfunction renewer(endpoint: TokenEndpoint, store: WebAccountStore, onSignedOut: () => void) {\n return (stale: string | null) => underLock(async () => {\n const held = store.read();\n if (held?.account !== 'tensorpass') {\n return null;\n }\n if (held.accessToken !== stale && held.expiresAt - RENEW_BEFORE_MS > Date.now()) {\n return held;\n }\n const response = await postForm(endpoint, '/oauth/token', {\n grant_type: 'refresh_token', refresh_token: held.refreshToken,\n });\n if (response.status === 400 || response.status === 401) {\n onSignedOut();\n return null;\n }\n const renewed = await tokensOf(response);\n store.save(renewed);\n return renewed;\n });\n}\n\nconst bearer = (credential: TensorPassCredential) => ({ Authorization: `Bearer ${credential.accessToken}` });\n\n// The headers of the stored token, renewed first when it is close to its end, and after a refusal.\nfunction tokenReader(endpoint: TokenEndpoint, store: WebAccountStore, onSignedOut: () => void) {\n const renew = renewer(endpoint, store, onSignedOut);\n const held = () => {\n const credential = store.read();\n return credential?.account === 'tensorpass' ? credential : null;\n };\n return {\n current: async (): Promise<Record<string, string>> => {\n const credential = held();\n const fresh = credential && credential.expiresAt - RENEW_BEFORE_MS <= Date.now()\n ? await renew(credential.accessToken) : credential;\n return fresh ? bearer(fresh) : {};\n },\n renewed: async () => {\n const renewed = await renew(held()?.accessToken ?? null);\n return renewed ? bearer(renewed) : null;\n },\n };\n}\n\nexport function tensorPassAccount(options: TensorPassOptions): WebAccount {\n // The browser's fetch called as a method of another object throws, so it is wrapped.\n const send: HttpFetch = options.fetch ?? ((input, init) => fetch(input, init));\n const endpoint = { url: options.gateway, siteKey: options.siteKey, send };\n return {\n id: 'tensorpass',\n name: NAME,\n model: options.level,\n authorizeUrl({ redirectUri, state, challenge }) {\n const url = new URL(`${options.gateway}/signin`);\n url.search = new URLSearchParams({\n response_type: 'code', client_id: options.siteKey, redirect_uri: redirectUri, code_challenge: challenge,\n code_challenge_method: 'S256', state,\n }).toString();\n return url.toString();\n },\n async exchange({ code, verifier, redirectUri }) {\n return tokensOf(await postForm(endpoint, '/oauth/token', {\n grant_type: 'authorization_code', code, code_verifier: verifier, redirect_uri: redirectUri,\n }));\n },\n session(store, onSignedOut) {\n const token = tokenReader(endpoint, store, onSignedOut);\n return webSession({\n providerId: 'tensorpass',\n providerName: NAME,\n model: options.level,\n endpoint: `${options.gateway}/v1/chat/completions`,\n fetch: options.fetch,\n credential: token.current,\n renew: token.renewed,\n onRefused: onSignedOut,\n });\n },\n plan(store, onSignedOut) {\n return planAccess({ gateway: options.gateway, send, bearer: tokenReader(endpoint, store, onSignedOut).current });\n },\n async revoke(credential) {\n if (credential.account === 'tensorpass') {\n await postForm(endpoint, '/oauth/revoke', { token: credential.refreshToken }).catch(() => undefined);\n }\n },\n };\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import type { HttpFetch } from './openAiCompatibleSession.ts';
2
+ export interface PlanPrice {
3
+ amount: number;
4
+ currency: string;
5
+ }
6
+ export interface PlanOffer {
7
+ id: string;
8
+ name: string;
9
+ levels: string[];
10
+ price: PlanPrice | null;
11
+ }
12
+ export interface PlanSubscription {
13
+ status: string;
14
+ plan: string | null;
15
+ levels: string[];
16
+ plans: PlanOffer[];
17
+ }
18
+ export interface PlanAccess {
19
+ subscription(): Promise<PlanSubscription>;
20
+ billingPage(plan: string): Promise<string>;
21
+ }
22
+ export interface PlanAccessConfig {
23
+ gateway: string;
24
+ send: HttpFetch;
25
+ bearer: () => Promise<Record<string, string>>;
26
+ }
27
+ export declare function planAccess({ gateway, send, bearer }: PlanAccessConfig): PlanAccess;
@@ -0,0 +1,36 @@
1
+ // The TensorPass plan of a visitor signed in on the page, as the chat offers it when the account has no
2
+ // subscription yet: the plans with their levels and price, read from the gateway, and the address of the
3
+ // gateway's billing page where the visitor subscribes. The web token opens a first subscription only, so
4
+ // the page can read and offer the plans without reaching the visitor's billing.
5
+ import { WalletRequestError } from "../walletProvider.js";
6
+ import { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from "./webAccount.js";
7
+ const NAME = WEB_ACCOUNT_NAMES.tensorpass;
8
+ async function answerOf(response) {
9
+ const body = await jsonOf(response);
10
+ if (!response.ok) {
11
+ const code = body.error?.code;
12
+ throw new WalletRequestError(`${NAME}: ${replyMessage(body, `the plan answered ${response.status}`)}`, response.status, undefined, typeof code === 'string' ? code : undefined);
13
+ }
14
+ return body;
15
+ }
16
+ export function planAccess({ gateway, send, bearer }) {
17
+ return {
18
+ async subscription() {
19
+ const response = await send(`${gateway}/_plan/web/subscription`, { headers: await bearer() });
20
+ return await answerOf(response);
21
+ },
22
+ async billingPage(plan) {
23
+ const response = await send(`${gateway}/_plan/web/billing-page`, {
24
+ method: 'POST',
25
+ headers: { 'Content-Type': 'application/json', ...await bearer() },
26
+ body: JSON.stringify({ plan }),
27
+ });
28
+ const { url } = await answerOf(response);
29
+ if (typeof url !== 'string') {
30
+ throw new WalletRequestError(`${NAME}: the plan sent no billing page`, 502);
31
+ }
32
+ return url;
33
+ },
34
+ };
35
+ }
36
+ //# sourceMappingURL=tensorPassPlan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tensorPassPlan.js","sourceRoot":"","sources":["../../src/webAccounts/tensorPassPlan.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,yGAAyG;AACzG,yGAAyG;AACzG,gFAAgF;AAEhF,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAoC1E,MAAM,IAAI,GAAG,iBAAiB,CAAC,UA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C;gBAC5B,MAAM,IAAI,kBAAkB,CAAC,GAAG,IAAI,iCAAiC,EAAE,GAAG,CAAC,CAAC;YAC9E,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// The TensorPass plan of a visitor signed in on the page, as the chat offers it when the account has no\n// subscription yet: the plans with their levels and price, read from the gateway, and the address of the\n// gateway's billing page where the visitor subscribes. The web token opens a first subscription only, so\n// the page can read and offer the plans without reaching the visitor's billing.\n\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { HttpFetch } from './openAiCompatibleSession.ts';\nimport { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from './webAccount.ts';\n\nexport interface PlanPrice {\n // In the currency's smallest unit, such as cents.\n amount: number;\n currency: string;\n}\n\nexport interface PlanOffer {\n id: string;\n name: string;\n levels: string[];\n price: PlanPrice | null;\n}\n\nexport interface PlanSubscription {\n // `active` once the plan answers; `none` for an account that never subscribed.\n status: string;\n plan: string | null;\n levels: string[];\n plans: PlanOffer[];\n}\n\nexport interface PlanAccess {\n subscription(): Promise<PlanSubscription>;\n // The billing page's address for the plan, with a ticket it opens with once.\n billingPage(plan: string): Promise<string>;\n}\n\nexport interface PlanAccessConfig {\n gateway: string;\n send: HttpFetch;\n // The headers of the current web token, renewed when it is close to its end.\n bearer: () => Promise<Record<string, string>>;\n}\n\nconst NAME = WEB_ACCOUNT_NAMES.tensorpass;\n\nasync function answerOf(response: Response): Promise<Record<string, unknown>> {\n const body = await jsonOf(response);\n if (!response.ok) {\n const code = (body.error as { code?: unknown } | undefined)?.code;\n throw new WalletRequestError(`${NAME}: ${replyMessage(body, `the plan answered ${response.status}`)}`,\n response.status, undefined, typeof code === 'string' ? code : undefined);\n }\n return body;\n}\n\nexport function planAccess({ gateway, send, bearer }: PlanAccessConfig): PlanAccess {\n return {\n async subscription() {\n const response = await send(`${gateway}/_plan/web/subscription`, { headers: await bearer() });\n return await answerOf(response) as unknown as PlanSubscription;\n },\n async billingPage(plan) {\n const response = await send(`${gateway}/_plan/web/billing-page`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...await bearer() },\n body: JSON.stringify({ plan }),\n });\n const { url } = await answerOf(response);\n if (typeof url !== 'string') {\n throw new WalletRequestError(`${NAME}: the plan sent no billing page`, 502);\n }\n return url;\n },\n };\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import type { ProviderSession } from '../types.ts';
2
+ import type { HttpFetch } from './openAiCompatibleSession.ts';
3
+ import type { PlanAccess } from './tensorPassPlan.ts';
4
+ import type { WebAccountId, WebAccountStore, WebCredential } from './webAccountStore.ts';
5
+ export declare const WEB_ACCOUNT_NAMES: Record<WebAccountId, string>;
6
+ export interface AuthorizeRequest {
7
+ redirectUri: string;
8
+ state: string;
9
+ challenge: string;
10
+ }
11
+ export interface CodeExchange {
12
+ code: string;
13
+ verifier: string;
14
+ redirectUri: string;
15
+ }
16
+ export interface WebAccount {
17
+ id: WebAccountId;
18
+ name: string;
19
+ model: string;
20
+ authorizeUrl(request: AuthorizeRequest): string;
21
+ exchange(request: CodeExchange): Promise<WebCredential>;
22
+ session(store: WebAccountStore, onSignedOut: () => void): ProviderSession;
23
+ plan?(store: WebAccountStore, onSignedOut: () => void): PlanAccess;
24
+ revoke(credential: WebCredential): Promise<void>;
25
+ }
26
+ export interface WebAccountContext {
27
+ fetch?: HttpFetch;
28
+ }
29
+ export declare function jsonOf(response: Response): Promise<Record<string, unknown>>;
30
+ export declare function replyMessage(body: Record<string, unknown>, fallback: string): string;
@@ -0,0 +1,19 @@
1
+ // What the client needs of each account a visitor signs in to on the page: its sign in page, the trade of
2
+ // the code it sends back for a credential, the chat session that credential opens, and how the
3
+ // credential is given up at sign out.
4
+ // The name of each account as the connect window and the chat show it.
5
+ export const WEB_ACCOUNT_NAMES = { tensorpass: 'TensorPass', openrouter: 'OpenRouter' };
6
+ // A reply's JSON body, or an empty object for a body that is not JSON.
7
+ export async function jsonOf(response) {
8
+ return await response.json().catch(() => ({}));
9
+ }
10
+ // The reason a token endpoint gives, OAuth's `error_description` or the gateway's `error.message`.
11
+ export function replyMessage(body, fallback) {
12
+ const described = body.error_description;
13
+ const nested = body.error?.message;
14
+ if (typeof described === 'string') {
15
+ return described;
16
+ }
17
+ return typeof nested === 'string' ? nested : fallback;
18
+ }
19
+ //# sourceMappingURL=webAccount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webAccount.js","sourceRoot":"","sources":["../../src/webAccounts/webAccount.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,+FAA+F;AAC/F,sCAAsC;AAOtC,uEAAuE;AACvE,MAAM,CAAC,MAAM,iBAAiB,GAAiC,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;AAgCtH,uEAAuE;AACvE,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,QAAkB;IAC7C,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAA4B,CAAC;AAC5E,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,YAAY,CAAC,IAA6B,EAAE,QAAgB;IAC1E,MAAM,SAAS,GAAG,IAAI,CAAC,iBAAiB,CAAC;IACzC,MAAM,MAAM,GAAI,IAAI,CAAC,KAA2C,EAAE,OAAO,CAAC;IAC1E,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;QAClC,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC","sourcesContent":["// What the client needs of each account a visitor signs in to on the page: its sign in page, the trade of\n// the code it sends back for a credential, the chat session that credential opens, and how the\n// credential is given up at sign out.\n\nimport type { ProviderSession } from '../types.ts';\nimport type { HttpFetch } from './openAiCompatibleSession.ts';\nimport type { PlanAccess } from './tensorPassPlan.ts';\nimport type { WebAccountId, WebAccountStore, WebCredential } from './webAccountStore.ts';\n\n// The name of each account as the connect window and the chat show it.\nexport const WEB_ACCOUNT_NAMES: Record<WebAccountId, string> = { tensorpass: 'TensorPass', openrouter: 'OpenRouter' };\n\nexport interface AuthorizeRequest {\n redirectUri: string;\n state: string;\n challenge: string;\n}\n\nexport interface CodeExchange {\n code: string;\n verifier: string;\n redirectUri: string;\n}\n\nexport interface WebAccount {\n id: WebAccountId;\n // The account's name as the connect window and the chat show it.\n name: string;\n model: string;\n authorizeUrl(request: AuthorizeRequest): string;\n exchange(request: CodeExchange): Promise<WebCredential>;\n // `onSignedOut` runs when the credential stops opening the account.\n session(store: WebAccountStore, onSignedOut: () => void): ProviderSession;\n // The plan of an account that sells one, TensorPass's, for the chat's offer to subscribe.\n plan?(store: WebAccountStore, onSignedOut: () => void): PlanAccess;\n revoke(credential: WebCredential): Promise<void>;\n}\n\nexport interface WebAccountContext {\n fetch?: HttpFetch;\n}\n\n// A reply's JSON body, or an empty object for a body that is not JSON.\nexport async function jsonOf(response: Response): Promise<Record<string, unknown>> {\n return await response.json().catch(() => ({})) as Record<string, unknown>;\n}\n\n// The reason a token endpoint gives, OAuth's `error_description` or the gateway's `error.message`.\nexport function replyMessage(body: Record<string, unknown>, fallback: string): string {\n const described = body.error_description;\n const nested = (body.error as { message?: unknown } | undefined)?.message;\n if (typeof described === 'string') {\n return described;\n }\n return typeof nested === 'string' ? nested : fallback;\n}\n"]}
@@ -0,0 +1,43 @@
1
+ import type { ConnectionState } from '../connectionState.ts';
2
+ import type { HttpFetch } from './openAiCompatibleSession.ts';
3
+ import type { PlanLevel } from './tensorPassAccount.ts';
4
+ import type { PlanAccess } from './tensorPassPlan.ts';
5
+ import { WebAccountStore } from './webAccountStore.ts';
6
+ import type { WebAccountId } from './webAccountStore.ts';
7
+ export interface WebAccountOptions {
8
+ siteKey?: string;
9
+ planGateway?: string;
10
+ openRouterModel?: string;
11
+ planLevel?: PlanLevel;
12
+ signInCallback?: string;
13
+ }
14
+ export interface WebAccountSourceDeps {
15
+ options: WebAccountOptions;
16
+ onChange: () => void;
17
+ store?: WebAccountStore;
18
+ fetch?: HttpFetch;
19
+ }
20
+ export declare class WebAccountSource {
21
+ private readonly accounts;
22
+ private readonly sessions;
23
+ private pending;
24
+ private signingIn;
25
+ private failure;
26
+ private readonly onChange;
27
+ private readonly store;
28
+ private readonly signInCallback?;
29
+ constructor({ options, onChange, store, fetch: fetchImpl }: WebAccountSourceDeps);
30
+ get ids(): WebAccountId[];
31
+ state(): ConnectionState;
32
+ takeCallback(): 'window' | 'redirect' | null;
33
+ signIn(id: WebAccountId): Promise<void>;
34
+ cancel(): void;
35
+ planAccess(): PlanAccess | null;
36
+ signOut(): Promise<void>;
37
+ private watch;
38
+ private expire;
39
+ private finish;
40
+ private signedOut;
41
+ private fail;
42
+ private sessionOf;
43
+ }
@@ -0,0 +1,216 @@
1
+ // The accounts a visitor without the wallet signs in to on the page: TensorPass's plan, offered when the
2
+ // site gave its site key, and OpenRouter, offered to every site. The source runs the sign in in a popup or,
3
+ // where the browser blocks it, in the page itself, keeps the credential in the site's storage, and answers
4
+ // the state the client shows while no wallet is found: signing in, connected with the account, or the
5
+ // wallet missing with the last sign in that failed.
6
+ import { challengeFor, randomToken } from "./pkce.js";
7
+ import { openRouterAccount, OPENROUTER_DEFAULT_MODEL } from "./openRouterAccount.js";
8
+ import { answerIn, callbackAddress, cleanAddress, pageAddress, forgetRedirected, keepForRedirect, listenForResult, markWindow, openSignInWindow, redirectedSignIn, returnToOpener, windowMark, } from "./signInWindow.js";
9
+ import { PLAN_GATEWAY, tensorPassAccount } from "./tensorPassAccount.js";
10
+ import { WEB_ACCOUNT_KEY, WebAccountStore } from "./webAccountStore.js";
11
+ // How long a sign in waits for its answer before it ends.
12
+ const SIGN_IN_WAIT_MS = 10 * 60_000;
13
+ function accountsOf(options, fetchImpl) {
14
+ const accounts = new Map();
15
+ if (options.siteKey) {
16
+ accounts.set('tensorpass', tensorPassAccount({
17
+ gateway: options.planGateway ?? PLAN_GATEWAY, siteKey: options.siteKey, level: options.planLevel ?? 'quick',
18
+ fetch: fetchImpl,
19
+ }));
20
+ }
21
+ const model = options.openRouterModel ?? OPENROUTER_DEFAULT_MODEL;
22
+ accounts.set('openrouter', openRouterAccount(model, { fetch: fetchImpl }));
23
+ return accounts;
24
+ }
25
+ const failureOf = (account, result) => ({
26
+ account,
27
+ reason: result.error === 'access_denied' ? 'declined' : 'failed',
28
+ message: result.error ?? 'No code came back from the sign in',
29
+ });
30
+ export class WebAccountSource {
31
+ accounts;
32
+ sessions = new Map();
33
+ pending = null;
34
+ signingIn = null;
35
+ failure;
36
+ onChange;
37
+ store;
38
+ signInCallback;
39
+ constructor({ options, onChange, store = new WebAccountStore(), fetch: fetchImpl }) {
40
+ this.onChange = onChange;
41
+ this.store = store;
42
+ this.accounts = accountsOf(options, fetchImpl);
43
+ this.signInCallback = options.signInCallback;
44
+ globalThis.addEventListener?.('storage', (event) => {
45
+ if (event.key === WEB_ACCOUNT_KEY) {
46
+ this.onChange();
47
+ }
48
+ });
49
+ }
50
+ // The accounts the connect window offers, TensorPass first when the site has a key.
51
+ get ids() {
52
+ return [...this.accounts.keys()];
53
+ }
54
+ state() {
55
+ if (this.signingIn) {
56
+ return { status: 'signingIn', account: this.signingIn };
57
+ }
58
+ const held = this.store.read();
59
+ const account = held ? this.accounts.get(held.account) : undefined;
60
+ if (!account) {
61
+ return { status: 'noWallet', ...(this.failure ? { signInFailure: this.failure } : {}) };
62
+ }
63
+ return { status: 'connected', providerName: account.name, model: account.model, session: this.sessionOf(account),
64
+ account: account.id };
65
+ }
66
+ // A page loaded as a sign in's callback: a popup hands the answer to its opener and closes, and a page
67
+ // that went to the sign in itself finishes it. Answers what the page was, or null for any other page.
68
+ takeCallback() {
69
+ const mark = windowMark();
70
+ const answer = mark ? answerIn(location.href, mark) : null;
71
+ if (answer) {
72
+ returnToOpener(answer);
73
+ return 'window';
74
+ }
75
+ const pending = redirectedSignIn();
76
+ const result = pending ? answerIn(location.href, pending.state) : null;
77
+ if (!pending || !result) {
78
+ return null;
79
+ }
80
+ forgetRedirected();
81
+ cleanAddress();
82
+ this.signingIn = pending.account;
83
+ void this.finish(pending, result);
84
+ return 'redirect';
85
+ }
86
+ // Starts a sign in. It must run from the visitor's click, which lets the browser open the popup.
87
+ signIn(id) {
88
+ const account = this.accounts.get(id);
89
+ if (!account) {
90
+ throw new Error(`This site offers no ${id} sign in`);
91
+ }
92
+ const state = randomToken(16);
93
+ const pending = {
94
+ account: id, state, verifier: randomToken(), redirectUri: callbackAddress(this.signInCallback),
95
+ returnTo: pageAddress(),
96
+ };
97
+ this.cancel();
98
+ const popup = openSignInWindow();
99
+ this.failure = undefined;
100
+ this.signingIn = id;
101
+ this.onChange();
102
+ return challengeFor(pending.verifier).then((challenge) => {
103
+ const url = account.authorizeUrl({ redirectUri: pending.redirectUri, state, challenge });
104
+ if (!popup) {
105
+ keepForRedirect(pending);
106
+ location.assign(url);
107
+ return;
108
+ }
109
+ this.watch(pending, popup);
110
+ popup.location.href = url;
111
+ }).catch((error) => this.fail({ account: id, reason: 'failed', message: error.message }));
112
+ }
113
+ // Ends the sign in in progress; an answer it gets later is ignored.
114
+ cancel() {
115
+ this.pending?.popup.close();
116
+ this.pending?.stop();
117
+ this.pending = null;
118
+ if (this.signingIn) {
119
+ this.signingIn = null;
120
+ this.onChange();
121
+ }
122
+ }
123
+ // The plan of the account that answers, when that account sells one: TensorPass's.
124
+ planAccess() {
125
+ const held = this.store.read();
126
+ const account = held ? this.accounts.get(held.account) : undefined;
127
+ return account?.plan ? account.plan(this.store, () => this.signedOut()) : null;
128
+ }
129
+ async signOut() {
130
+ const held = this.store.read();
131
+ this.store.forget();
132
+ this.failure = undefined;
133
+ this.onChange();
134
+ if (held) {
135
+ await this.accounts.get(held.account)?.revoke(held);
136
+ }
137
+ }
138
+ // Waits for the popup's answer. When the page regains focus with the popup gone, the connect window
139
+ // leaves its waiting step, and the answer is still taken if it comes: a provider page that isolates the
140
+ // popup from its opener also makes `popup.closed` read true while the visitor is still signing in.
141
+ watch(pending, popup) {
142
+ const stopListening = listenForResult(pending.state, (result) => {
143
+ if (result.state === this.pending?.state) {
144
+ this.pending.stop();
145
+ this.pending = null;
146
+ this.signingIn = pending.account;
147
+ void this.finish(pending, result);
148
+ }
149
+ });
150
+ const onFocus = () => {
151
+ if (popup.closed && this.signingIn === pending.account && this.pending?.state === pending.state) {
152
+ this.signingIn = null;
153
+ this.onChange();
154
+ }
155
+ };
156
+ window.addEventListener('focus', onFocus);
157
+ const timer = setTimeout(() => this.expire(pending), SIGN_IN_WAIT_MS);
158
+ markWindow(pending.state);
159
+ this.pending = {
160
+ ...pending,
161
+ popup,
162
+ stop: () => {
163
+ stopListening();
164
+ window.removeEventListener('focus', onFocus);
165
+ clearTimeout(timer);
166
+ markWindow(null);
167
+ },
168
+ };
169
+ }
170
+ // A sign in that got no answer in its time ends; one the connect window already left ends quietly.
171
+ expire(pending) {
172
+ if (this.signingIn) {
173
+ this.fail({ account: pending.account, reason: 'expired', message: 'The sign in took too long' });
174
+ return;
175
+ }
176
+ this.pending?.stop();
177
+ this.pending = null;
178
+ }
179
+ async finish(pending, result) {
180
+ const account = this.accounts.get(pending.account);
181
+ if (!account || !result.code) {
182
+ this.fail(failureOf(pending.account, result));
183
+ return;
184
+ }
185
+ try {
186
+ this.store.save(await account.exchange({ code: result.code, verifier: pending.verifier,
187
+ redirectUri: pending.redirectUri }));
188
+ this.signingIn = null;
189
+ this.onChange();
190
+ }
191
+ catch (error) {
192
+ this.fail({ account: pending.account, reason: 'failed', message: error.message ?? String(error) });
193
+ }
194
+ }
195
+ // The credential stopped opening its account: the visitor signs in again.
196
+ signedOut() {
197
+ this.store.forget();
198
+ this.onChange();
199
+ }
200
+ fail(failure) {
201
+ this.pending?.stop();
202
+ this.pending = null;
203
+ this.signingIn = null;
204
+ this.failure = failure;
205
+ this.onChange();
206
+ }
207
+ sessionOf(account) {
208
+ let session = this.sessions.get(account.id);
209
+ if (!session) {
210
+ session = account.session(this.store, () => this.signedOut());
211
+ this.sessions.set(account.id, session);
212
+ }
213
+ return session;
214
+ }
215
+ }
216
+ //# sourceMappingURL=webAccountSource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webAccountSource.js","sourceRoot":"","sources":["../../src/webAccounts/webAccountSource.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,4GAA4G;AAC5G,2GAA2G;AAC3G,sGAAsG;AACtG,oDAAoD;AAIpD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EACL,QAAQ,EAAE,eAAe,EAAE,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,UAAU,EACpH,gBAAgB,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,GAC/D,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAIzE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAcxE,0DAA0D;AAC1D,MAAM,eAAe,GAAG,EAAE,GAAG,MAAM,CAAC;AAepC,SAAS,UAAU,CAAC,OAA0B,EAAE,SAAqB;IACnE,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA4B,CAAC;IACrD,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACpB,QAAQ,CAAC,GAAG,CAAC,YAAY,EAAE,iBAAiB,CAAC;YAC3C,OAAO,EAAE,OAAO,CAAC,WAAW,IAAI,YAAY,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,SAAS,IAAI,OAAO;YAC3G,KAAK,EAAE,SAAS;SACjB,CAAC,CAAC,CAAC;IACN,CAAC;IACD,MAAM,KA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CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["// The accounts a visitor without the wallet signs in to on the page: TensorPass's plan, offered when the\n// site gave its site key, and OpenRouter, offered to every site. The source runs the sign in in a popup or,\n// where the browser blocks it, in the page itself, keeps the credential in the site's storage, and answers\n// the state the client shows while no wallet is found: signing in, connected with the account, or the\n// wallet missing with the last sign in that failed.\n\nimport type { ConnectionState, WebSignInFailure } from '../connectionState.ts';\nimport type { ProviderSession } from '../types.ts';\nimport { challengeFor, randomToken } from './pkce.ts';\nimport type { HttpFetch } from './openAiCompatibleSession.ts';\nimport { openRouterAccount, OPENROUTER_DEFAULT_MODEL } from './openRouterAccount.ts';\nimport {\n answerIn, callbackAddress, cleanAddress, pageAddress, forgetRedirected, keepForRedirect, listenForResult, markWindow,\n openSignInWindow, redirectedSignIn, returnToOpener, windowMark,\n} from './signInWindow.ts';\nimport type { PendingSignIn, SignInResult } from './signInWindow.ts';\nimport { PLAN_GATEWAY, tensorPassAccount } from './tensorPassAccount.ts';\nimport type { PlanLevel } from './tensorPassAccount.ts';\nimport type { PlanAccess } from './tensorPassPlan.ts';\nimport type { WebAccount } from './webAccount.ts';\nimport { WEB_ACCOUNT_KEY, WebAccountStore } from './webAccountStore.ts';\nimport type { WebAccountId } from './webAccountStore.ts';\n\nexport interface WebAccountOptions {\n // The site's public key from TensorPass, which offers the TensorPass plan's sign in.\n siteKey?: string;\n planGateway?: string;\n openRouterModel?: string;\n planLevel?: PlanLevel;\n // The site's return page for the sign ins, a path or an address on the page's origin that runs\n // `finishSignIn`. Without it, the provider sends the sign in back to the page itself.\n signInCallback?: string;\n}\n\n// How long a sign in waits for its answer before it ends.\nconst SIGN_IN_WAIT_MS = 10 * 60_000;\n\ninterface Watched extends PendingSignIn {\n stop: () => void;\n popup: Window;\n}\n\nexport interface WebAccountSourceDeps {\n options: WebAccountOptions;\n // Called whenever the state the source answers changes.\n onChange: () => void;\n store?: WebAccountStore;\n fetch?: HttpFetch;\n}\n\nfunction accountsOf(options: WebAccountOptions, fetchImpl?: HttpFetch): Map<WebAccountId, WebAccount> {\n const accounts = new Map<WebAccountId, WebAccount>();\n if (options.siteKey) {\n accounts.set('tensorpass', tensorPassAccount({\n gateway: options.planGateway ?? PLAN_GATEWAY, siteKey: options.siteKey, level: options.planLevel ?? 'quick',\n fetch: fetchImpl,\n }));\n }\n const model = options.openRouterModel ?? OPENROUTER_DEFAULT_MODEL;\n accounts.set('openrouter', openRouterAccount(model, { fetch: fetchImpl }));\n return accounts;\n}\n\nconst failureOf = (account: WebAccountId, result: SignInResult): WebSignInFailure => ({\n account,\n reason: result.error === 'access_denied' ? 'declined' : 'failed',\n message: result.error ?? 'No code came back from the sign in',\n});\n\nexport class WebAccountSource {\n private readonly accounts: Map<WebAccountId, WebAccount>;\n private readonly sessions = new Map<WebAccountId, ProviderSession>();\n private pending: Watched | null = null;\n private signingIn: WebAccountId | null = null;\n private failure: WebSignInFailure | undefined;\n private readonly onChange: () => void;\n private readonly store: WebAccountStore;\n private readonly signInCallback?: string;\n\n constructor({ options, onChange, store = new WebAccountStore(), fetch: fetchImpl }: WebAccountSourceDeps) {\n this.onChange = onChange;\n this.store = store;\n this.accounts = accountsOf(options, fetchImpl);\n this.signInCallback = options.signInCallback;\n globalThis.addEventListener?.('storage', (event: StorageEvent) => {\n if (event.key === WEB_ACCOUNT_KEY) {\n this.onChange();\n }\n });\n }\n\n // The accounts the connect window offers, TensorPass first when the site has a key.\n get ids(): WebAccountId[] {\n return [...this.accounts.keys()];\n }\n\n state(): ConnectionState {\n if (this.signingIn) {\n return { status: 'signingIn', account: this.signingIn };\n }\n const held = this.store.read();\n const account = held ? this.accounts.get(held.account) : undefined;\n if (!account) {\n return { status: 'noWallet', ...(this.failure ? { signInFailure: this.failure } : {}) };\n }\n return { status: 'connected', providerName: account.name, model: account.model, session: this.sessionOf(account),\n account: account.id };\n }\n\n // A page loaded as a sign in's callback: a popup hands the answer to its opener and closes, and a page\n // that went to the sign in itself finishes it. Answers what the page was, or null for any other page.\n takeCallback(): 'window' | 'redirect' | null {\n const mark = windowMark();\n const answer = mark ? answerIn(location.href, mark) : null;\n if (answer) {\n returnToOpener(answer);\n return 'window';\n }\n const pending = redirectedSignIn();\n const result = pending ? answerIn(location.href, pending.state) : null;\n if (!pending || !result) {\n return null;\n }\n forgetRedirected();\n cleanAddress();\n this.signingIn = pending.account;\n void this.finish(pending, result);\n return 'redirect';\n }\n\n // Starts a sign in. It must run from the visitor's click, which lets the browser open the popup.\n signIn(id: WebAccountId): Promise<void> {\n const account = this.accounts.get(id);\n if (!account) {\n throw new Error(`This site offers no ${id} sign in`);\n }\n const state = randomToken(16);\n const pending: PendingSignIn = {\n account: id, state, verifier: randomToken(), redirectUri: callbackAddress(this.signInCallback),\n returnTo: pageAddress(),\n };\n this.cancel();\n const popup = openSignInWindow();\n this.failure = undefined;\n this.signingIn = id;\n this.onChange();\n return challengeFor(pending.verifier).then((challenge) => {\n const url = account.authorizeUrl({ redirectUri: pending.redirectUri, state, challenge });\n if (!popup) {\n keepForRedirect(pending);\n location.assign(url);\n return;\n }\n this.watch(pending, popup);\n popup.location.href = url;\n }).catch((error: Error) => this.fail({ account: id, reason: 'failed', message: error.message }));\n }\n\n // Ends the sign in in progress; an answer it gets later is ignored.\n cancel(): void {\n this.pending?.popup.close();\n this.pending?.stop();\n this.pending = null;\n if (this.signingIn) {\n this.signingIn = null;\n this.onChange();\n }\n }\n\n // The plan of the account that answers, when that account sells one: TensorPass's.\n planAccess(): PlanAccess | null {\n const held = this.store.read();\n const account = held ? this.accounts.get(held.account) : undefined;\n return account?.plan ? account.plan(this.store, () => this.signedOut()) : null;\n }\n\n async signOut(): Promise<void> {\n const held = this.store.read();\n this.store.forget();\n this.failure = undefined;\n this.onChange();\n if (held) {\n await this.accounts.get(held.account)?.revoke(held);\n }\n }\n\n // Waits for the popup's answer. When the page regains focus with the popup gone, the connect window\n // leaves its waiting step, and the answer is still taken if it comes: a provider page that isolates the\n // popup from its opener also makes `popup.closed` read true while the visitor is still signing in.\n private watch(pending: PendingSignIn, popup: Window): void {\n const stopListening = listenForResult(pending.state, (result) => {\n if (result.state === this.pending?.state) {\n this.pending.stop();\n this.pending = null;\n this.signingIn = pending.account;\n void this.finish(pending, result);\n }\n });\n const onFocus = () => {\n if (popup.closed && this.signingIn === pending.account && this.pending?.state === pending.state) {\n this.signingIn = null;\n this.onChange();\n }\n };\n window.addEventListener('focus', onFocus);\n const timer = setTimeout(() => this.expire(pending), SIGN_IN_WAIT_MS);\n markWindow(pending.state);\n this.pending = {\n ...pending,\n popup,\n stop: () => {\n stopListening();\n window.removeEventListener('focus', onFocus);\n clearTimeout(timer);\n markWindow(null);\n },\n };\n }\n\n // A sign in that got no answer in its time ends; one the connect window already left ends quietly.\n private expire(pending: PendingSignIn): void {\n if (this.signingIn) {\n this.fail({ account: pending.account, reason: 'expired', message: 'The sign in took too long' });\n return;\n }\n this.pending?.stop();\n this.pending = null;\n }\n\n private async finish(pending: PendingSignIn, result: SignInResult): Promise<void> {\n const account = this.accounts.get(pending.account);\n if (!account || !result.code) {\n this.fail(failureOf(pending.account, result));\n return;\n }\n try {\n this.store.save(await account.exchange({ code: result.code, verifier: pending.verifier,\n redirectUri: pending.redirectUri }));\n this.signingIn = null;\n this.onChange();\n } catch (error) {\n this.fail({ account: pending.account, reason: 'failed', message: (error as Error).message ?? String(error) });\n }\n }\n\n // The credential stopped opening its account: the visitor signs in again.\n private signedOut(): void {\n this.store.forget();\n this.onChange();\n }\n\n private fail(failure: WebSignInFailure): void {\n this.pending?.stop();\n this.pending = null;\n this.signingIn = null;\n this.failure = failure;\n this.onChange();\n }\n\n private sessionOf(account: WebAccount): ProviderSession {\n let session = this.sessions.get(account.id);\n if (!session) {\n session = account.session(this.store, () => this.signedOut());\n this.sessions.set(account.id, session);\n }\n return session;\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ export type WebAccountId = 'tensorpass' | 'openrouter';
2
+ export interface OpenRouterCredential {
3
+ account: 'openrouter';
4
+ key: string;
5
+ }
6
+ export interface TensorPassCredential {
7
+ account: 'tensorpass';
8
+ accessToken: string;
9
+ refreshToken: string;
10
+ expiresAt: number;
11
+ }
12
+ export type WebCredential = OpenRouterCredential | TensorPassCredential;
13
+ export interface KeyValueStorage {
14
+ getItem(key: string): string | null;
15
+ setItem(key: string, value: string): void;
16
+ removeItem(key: string): void;
17
+ }
18
+ export declare const WEB_ACCOUNT_KEY = "aiconnect:web-account";
19
+ export declare class WebAccountStore {
20
+ private memory;
21
+ private memoryOnly;
22
+ private readonly storage;
23
+ constructor(storage?: KeyValueStorage | null);
24
+ read(): WebCredential | null;
25
+ save(credential: WebCredential): void;
26
+ forget(): void;
27
+ }