@celljs/ta-host 4.17.0 → 4.18.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 (143) hide show
  1. package/esm/node/app-commands.d.ts +1 -1
  2. package/esm/node/app-commands.js +46 -29
  3. package/esm/node/credentials.d.ts +12 -0
  4. package/esm/node/credentials.js +35 -0
  5. package/esm/node/index.d.ts +2 -0
  6. package/esm/node/index.js +2 -0
  7. package/esm/node/keep-awake.d.ts +3 -0
  8. package/esm/node/keep-awake.js +6 -1
  9. package/esm/node/package-hosts.d.ts +2 -0
  10. package/esm/node/package-hosts.js +6 -0
  11. package/esm/node/rooms-bridge.d.ts +10 -1
  12. package/esm/node/rooms-bridge.js +25 -0
  13. package/esm/node/screen-share/desktop-picture.d.ts +51 -0
  14. package/esm/node/screen-share/desktop-picture.js +133 -0
  15. package/esm/node/screen-share/desktop-session.d.ts +128 -0
  16. package/esm/node/screen-share/desktop-session.js +437 -0
  17. package/esm/node/screen-share/desktop-targets.d.ts +24 -0
  18. package/esm/node/screen-share/desktop-targets.js +80 -0
  19. package/esm/node/screen-share/desktop-viewer.d.ts +146 -0
  20. package/esm/node/screen-share/desktop-viewer.js +339 -0
  21. package/esm/node/screen-share/index.d.ts +8 -0
  22. package/esm/node/screen-share/index.js +9 -0
  23. package/esm/node/screen-share/rfb-client.d.ts +54 -0
  24. package/esm/node/screen-share/rfb-client.js +179 -0
  25. package/esm/node/screen-share/rfb-des.d.ts +11 -0
  26. package/esm/node/screen-share/rfb-des.js +143 -0
  27. package/esm/node/screen-share/rfb-encodings.d.ts +71 -0
  28. package/esm/node/screen-share/rfb-encodings.js +288 -0
  29. package/esm/node/screen-share/rfb-framebuffer.d.ts +16 -0
  30. package/esm/node/screen-share/rfb-framebuffer.js +53 -0
  31. package/esm/node/screen-share/rfb-protocol.d.ts +90 -0
  32. package/esm/node/screen-share/rfb-protocol.js +36 -0
  33. package/esm/node/screen-share/rfb-reader.d.ts +34 -0
  34. package/esm/node/screen-share/rfb-reader.js +110 -0
  35. package/esm/node/screen-share/rfb-security.d.ts +30 -0
  36. package/esm/node/screen-share/rfb-security.js +136 -0
  37. package/esm/node/screen-share/rfb-test-server.d.ts +37 -0
  38. package/esm/node/screen-share/rfb-test-server.js +116 -0
  39. package/esm/node/screen-share/screen-share-server-impl.d.ts +37 -0
  40. package/esm/node/screen-share/screen-share-server-impl.js +76 -0
  41. package/esm/node/screen-share/screen-shares.d.ts +123 -0
  42. package/esm/node/screen-share/screen-shares.js +463 -0
  43. package/esm/node/session-info-util.d.ts +10 -11
  44. package/esm/node/session-info-util.js +16 -94
  45. package/esm/node/settings-store.d.ts +1 -1
  46. package/esm/node/settings-store.js +7 -4
  47. package/esm/node/sign-in/access-store.d.ts +1 -1
  48. package/esm/node/sign-in/access-store.js +4 -1
  49. package/esm/node/sign-in/index.d.ts +2 -0
  50. package/esm/node/sign-in/index.js +2 -0
  51. package/esm/node/sign-in/polled-sign-in.d.ts +50 -0
  52. package/esm/node/sign-in/polled-sign-in.js +83 -0
  53. package/esm/node/sign-in/sign-in-devices.d.ts +55 -0
  54. package/esm/node/sign-in/sign-in-devices.js +113 -0
  55. package/esm/node/sign-in/sign-in-flow.d.ts +38 -4
  56. package/esm/node/sign-in/sign-in-flow.js +79 -4
  57. package/esm/node/sign-in/sign-in-pages.d.ts +8 -0
  58. package/esm/node/sign-in/sign-in-pages.js +137 -8
  59. package/esm/node/sign-in/sign-in-provider.d.ts +6 -0
  60. package/esm/node/sign-in/sign-in-provider.js +15 -0
  61. package/esm/node/sources-extension.d.ts +10 -0
  62. package/esm/node/sources-extension.js +18 -0
  63. package/esm/node/ta-server-impl.js +3 -3
  64. package/esm/node/ta-session-factory.js +2 -0
  65. package/esm/node/team/team-calls.js +27 -0
  66. package/esm/node/voice-bridge.d.ts +3 -1
  67. package/esm/node/voice-bridge.js +10 -3
  68. package/esm/node/voices-file.d.ts +5 -0
  69. package/esm/node/voices-file.js +14 -3
  70. package/esm/node/working-directory.d.ts +8 -2
  71. package/esm/node/working-directory.js +7 -0
  72. package/lib/node/app-commands.d.ts +1 -1
  73. package/lib/node/app-commands.js +46 -29
  74. package/lib/node/credentials.d.ts +13 -0
  75. package/lib/node/credentials.js +38 -0
  76. package/lib/node/index.d.ts +2 -0
  77. package/lib/node/index.js +2 -0
  78. package/lib/node/keep-awake.d.ts +3 -0
  79. package/lib/node/keep-awake.js +6 -1
  80. package/lib/node/package-hosts.d.ts +2 -0
  81. package/lib/node/package-hosts.js +6 -0
  82. package/lib/node/rooms-bridge.d.ts +10 -1
  83. package/lib/node/rooms-bridge.js +25 -0
  84. package/lib/node/screen-share/desktop-picture.d.ts +52 -0
  85. package/lib/node/screen-share/desktop-picture.js +136 -0
  86. package/lib/node/screen-share/desktop-session.d.ts +129 -0
  87. package/lib/node/screen-share/desktop-session.js +442 -0
  88. package/lib/node/screen-share/desktop-targets.d.ts +25 -0
  89. package/lib/node/screen-share/desktop-targets.js +84 -0
  90. package/lib/node/screen-share/desktop-viewer.d.ts +147 -0
  91. package/lib/node/screen-share/desktop-viewer.js +343 -0
  92. package/lib/node/screen-share/index.d.ts +9 -0
  93. package/lib/node/screen-share/index.js +25 -0
  94. package/lib/node/screen-share/rfb-client.d.ts +55 -0
  95. package/lib/node/screen-share/rfb-client.js +183 -0
  96. package/lib/node/screen-share/rfb-des.d.ts +12 -0
  97. package/lib/node/screen-share/rfb-des.js +146 -0
  98. package/lib/node/screen-share/rfb-encodings.d.ts +72 -0
  99. package/lib/node/screen-share/rfb-encodings.js +295 -0
  100. package/lib/node/screen-share/rfb-framebuffer.d.ts +17 -0
  101. package/lib/node/screen-share/rfb-framebuffer.js +57 -0
  102. package/lib/node/screen-share/rfb-protocol.d.ts +91 -0
  103. package/lib/node/screen-share/rfb-protocol.js +39 -0
  104. package/lib/node/screen-share/rfb-reader.d.ts +35 -0
  105. package/lib/node/screen-share/rfb-reader.js +115 -0
  106. package/lib/node/screen-share/rfb-security.d.ts +31 -0
  107. package/lib/node/screen-share/rfb-security.js +141 -0
  108. package/lib/node/screen-share/rfb-test-server.d.ts +38 -0
  109. package/lib/node/screen-share/rfb-test-server.js +120 -0
  110. package/lib/node/screen-share/screen-share-server-impl.d.ts +38 -0
  111. package/lib/node/screen-share/screen-share-server-impl.js +79 -0
  112. package/lib/node/screen-share/screen-shares.d.ts +124 -0
  113. package/lib/node/screen-share/screen-shares.js +464 -0
  114. package/lib/node/session-info-util.d.ts +10 -11
  115. package/lib/node/session-info-util.js +15 -93
  116. package/lib/node/settings-store.d.ts +1 -1
  117. package/lib/node/settings-store.js +6 -3
  118. package/lib/node/sign-in/access-store.d.ts +1 -1
  119. package/lib/node/sign-in/access-store.js +4 -1
  120. package/lib/node/sign-in/index.d.ts +2 -0
  121. package/lib/node/sign-in/index.js +2 -0
  122. package/lib/node/sign-in/polled-sign-in.d.ts +51 -0
  123. package/lib/node/sign-in/polled-sign-in.js +87 -0
  124. package/lib/node/sign-in/sign-in-devices.d.ts +56 -0
  125. package/lib/node/sign-in/sign-in-devices.js +117 -0
  126. package/lib/node/sign-in/sign-in-flow.d.ts +38 -4
  127. package/lib/node/sign-in/sign-in-flow.js +80 -5
  128. package/lib/node/sign-in/sign-in-pages.d.ts +8 -0
  129. package/lib/node/sign-in/sign-in-pages.js +136 -7
  130. package/lib/node/sign-in/sign-in-provider.d.ts +6 -0
  131. package/lib/node/sign-in/sign-in-provider.js +15 -0
  132. package/lib/node/sources-extension.d.ts +11 -0
  133. package/lib/node/sources-extension.js +22 -0
  134. package/lib/node/ta-server-impl.js +2 -2
  135. package/lib/node/ta-session-factory.js +2 -0
  136. package/lib/node/team/team-calls.js +27 -0
  137. package/lib/node/voice-bridge.d.ts +3 -1
  138. package/lib/node/voice-bridge.js +9 -2
  139. package/lib/node/voices-file.d.ts +5 -0
  140. package/lib/node/voices-file.js +14 -3
  141. package/lib/node/working-directory.d.ts +8 -2
  142. package/lib/node/working-directory.js +7 -0
  143. package/package.json +14 -10
@@ -11,7 +11,7 @@ import { mkdir, readFile, rename, rmdir, stat, writeFile } from 'node:fs/promise
11
11
  import { dirname, join } from 'node:path';
12
12
  import { CODING_AGENT_OPTIONS, ModelRuntimeProvider, PiSdkUtil } from '@celljs/ai-coding-agent';
13
13
  import { Autowired, Component, Value } from '@celljs/core';
14
- import { TA_SETTINGS } from '@celljs/ta-protocol';
14
+ import { TA_AGENT_API_PREFIX, TA_SETTINGS } from '@celljs/ta-protocol';
15
15
  import { ExtensionProviders } from './extension-providers.js';
16
16
  import { TaSessionRegistry } from './host-protocol.js';
17
17
  import { PiDirectories } from './remote/remote-protocol.js';
@@ -204,7 +204,7 @@ let TaSettingsStoreImpl = class TaSettingsStoreImpl {
204
204
  }
205
205
  async get(cwd) {
206
206
  const { userFile, projectFile, trusted } = await this.files(cwd);
207
- const [user, project, { models, modelNames, providerNames }] = await Promise.all([this.read(userFile), this.read(projectFile), this.models()]);
207
+ const [user, project, { models, agents, modelNames, providerNames }] = await Promise.all([this.read(userFile), this.read(projectFile), this.models()]);
208
208
  return {
209
209
  user: TaSettingsUtil.read(user),
210
210
  project: TaSettingsUtil.read(project),
@@ -213,6 +213,7 @@ let TaSettingsStoreImpl = class TaSettingsStoreImpl {
213
213
  projectFile,
214
214
  projectTrusted: trusted !== false,
215
215
  models,
216
+ agents,
216
217
  modelNames,
217
218
  providerNames,
218
219
  };
@@ -312,10 +313,12 @@ let TaSettingsStoreImpl = class TaSettingsStoreImpl {
312
313
  providerNames[provider.id] = provider.name;
313
314
  }
314
315
  }
315
- return { models: available.map(model => `${model.provider}/${model.id}`), modelNames, providerNames };
316
+ const name = (model) => `${model.provider}/${model.id}`;
317
+ const agents = available.filter(model => String(model.api).startsWith(TA_AGENT_API_PREFIX)).map(name);
318
+ return { models: available.map(name), agents, modelNames, providerNames };
316
319
  }
317
320
  catch (_a) {
318
- return { models: [], modelNames: {}, providerNames: {} };
321
+ return { models: [], agents: [], modelNames: {}, providerNames: {} };
319
322
  }
320
323
  }
321
324
  async reloadSessions(scope, cwd) {
@@ -25,7 +25,7 @@ interface AccessFile {
25
25
  export declare namespace AccessUtil {
26
26
  /** Logins and addresses are the same whatever their case; the ids of WeChat and `sub`s are not. */
27
27
  function normalize(account: string): string;
28
- /** `google:*@corp.com` lets in every address of the domain; anything else, one account. */
28
+ /** `google:*@corp.com` lets in every address of the domain, `oidc:*` every account of the provider; anything else, one account. */
29
29
  function matches(pattern: string, account: string): boolean;
30
30
  /** TA_ALLOWED_USERS: accounts separated by commas, spaces or new lines. */
31
31
  function parseList(list: string | undefined): string[];
@@ -14,9 +14,12 @@ export var AccessUtil;
14
14
  return value.startsWith('github:') || value.includes('@') ? value.toLowerCase() : value;
15
15
  }
16
16
  AccessUtil.normalize = normalize;
17
- /** `google:*@corp.com` lets in every address of the domain; anything else, one account. */
17
+ /** `google:*@corp.com` lets in every address of the domain, `oidc:*` every account of the provider; anything else, one account. */
18
18
  function matches(pattern, account) {
19
19
  const [want, have] = [normalize(pattern), normalize(account)];
20
+ if (want.endsWith(':*') && want.indexOf(':') === want.length - 2) {
21
+ return have.startsWith(want.slice(0, -1)) && have.length > want.length - 1;
22
+ }
20
23
  const star = want.indexOf(':*@');
21
24
  if (star > 0) {
22
25
  return have.startsWith(want.slice(0, star + 1)) && have.endsWith(want.slice(star + 2));
@@ -1,5 +1,7 @@
1
1
  export * from './access-server-impl.js';
2
2
  export * from './access-store.js';
3
+ export * from './polled-sign-in.js';
4
+ export * from './sign-in-devices.js';
3
5
  export * from './sign-in-flow.js';
4
6
  export * from './sign-in-middleware.js';
5
7
  export * from './sign-in-pages.js';
@@ -1,5 +1,7 @@
1
1
  export * from './access-server-impl.js';
2
2
  export * from './access-store.js';
3
+ export * from './polled-sign-in.js';
4
+ export * from './sign-in-devices.js';
3
5
  export * from './sign-in-flow.js';
4
6
  export * from './sign-in-middleware.js';
5
7
  export * from './sign-in-pages.js';
@@ -0,0 +1,50 @@
1
+ import type { TaSignInProvider } from '@celljs/ta-protocol';
2
+ import { type SignInAccount } from './sign-in-provider.js';
3
+ /**
4
+ * A provider the browser signs in at without coming back to Ta: the request is pushed to it (PAR, RFC 9126), the user
5
+ * agrees in a browser, and Ta asks it for the result until it has one (a company's sign-in for CLIs, as
6
+ * `<par endpoint>/poll`). Needs no secret and no address to come back to: a client id is all.
7
+ */
8
+ export interface PolledSignInProvider extends TaSignInProvider {
9
+ readonly polled: true;
10
+ /** A sign-in under way: where the browser goes, how long it is good for, and its result asked for. */
11
+ begin(): Promise<PolledSignIn>;
12
+ }
13
+ export interface PolledSignIn {
14
+ url: string;
15
+ /** Seconds. */
16
+ expiresIn: number;
17
+ /** The account once agreed to; `pending` while not yet. Throws once refused or too late. */
18
+ poll(): Promise<SignInAccount | 'pending'>;
19
+ }
20
+ interface PolledConfiguration {
21
+ authorization_endpoint: string;
22
+ token_endpoint: string;
23
+ userinfo_endpoint: string;
24
+ pushed_authorization_request_endpoint: string;
25
+ }
26
+ export interface PushedSignInOptions {
27
+ /** The account is `<id>:<sub>`. */
28
+ id: string;
29
+ name: string;
30
+ issuer: string;
31
+ clientId: string;
32
+ /** What the provider shows the user its sign-in is for, when it knows several of one client. */
33
+ cliId?: string;
34
+ }
35
+ /**
36
+ * The server of `issuer` (its openid-configuration says where): PAR, then `<par endpoint>/poll`, the code and userinfo. The
37
+ * account is `<id>:<username>` (as TA_GATEWAY_ADMINS and Settings, Access name it), `<id>:<sub>` without one.
38
+ */
39
+ export declare class PushedSignIn implements PolledSignInProvider {
40
+ protected readonly options: PushedSignInOptions;
41
+ readonly id: string;
42
+ readonly name: string;
43
+ readonly polled: true;
44
+ protected configuration?: Promise<PolledConfiguration>;
45
+ constructor(options: PushedSignInOptions);
46
+ begin(): Promise<PolledSignIn>;
47
+ protected poll(config: PolledConfiguration, url: string, verifier: string): Promise<SignInAccount | 'pending'>;
48
+ protected discover(): Promise<PolledConfiguration>;
49
+ }
50
+ export {};
@@ -0,0 +1,83 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { SignInUtil } from './sign-in-flow.js';
3
+ import { SignInError, SignInHttp } from './sign-in-provider.js';
4
+ /**
5
+ * The server of `issuer` (its openid-configuration says where): PAR, then `<par endpoint>/poll`, the code and userinfo. The
6
+ * account is `<id>:<username>` (as TA_GATEWAY_ADMINS and Settings, Access name it), `<id>:<sub>` without one.
7
+ */
8
+ export class PushedSignIn {
9
+ constructor(options) {
10
+ this.options = options;
11
+ this.polled = true;
12
+ this.id = options.id;
13
+ this.name = options.name;
14
+ }
15
+ async begin() {
16
+ var _a, _b;
17
+ const config = await this.discover();
18
+ if (!config.pushed_authorization_request_endpoint) {
19
+ throw new SignInError(`${this.name}: no pushed authorization requests`);
20
+ }
21
+ const { verifier, challenge } = SignInUtil.pkce();
22
+ const pushed = await SignInHttp.json(config.pushed_authorization_request_endpoint, SignInHttp.form({
23
+ client_id: this.options.clientId,
24
+ response_type: 'code',
25
+ code_challenge: challenge,
26
+ code_challenge_method: 'S256',
27
+ state: randomBytes(18).toString('base64url'),
28
+ scope: 'openid profile email',
29
+ login_only: 'true',
30
+ }));
31
+ if (!pushed.request_uri) {
32
+ throw new SignInError(`${this.name}: ${(_b = (_a = pushed.error_description) !== null && _a !== void 0 ? _a : pushed.error) !== null && _b !== void 0 ? _b : 'no request'}`);
33
+ }
34
+ const requestUri = pushed.request_uri;
35
+ const url = SignInHttp.url(config.authorization_endpoint, { client_id: this.options.clientId, request_uri: requestUri, cliId: this.options.cliId });
36
+ const poll = SignInHttp.url(`${config.pushed_authorization_request_endpoint}/poll`, { request_uri: requestUri, client_id: this.options.clientId });
37
+ return { url, expiresIn: Number(pushed.expires_in) || 300, poll: () => this.poll(config, poll, verifier) };
38
+ }
39
+ async poll(config, url, verifier) {
40
+ var _a;
41
+ var _b, _c, _d, _e;
42
+ const response = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(10000) });
43
+ if (response.status === 404) {
44
+ throw new SignInError(`${this.name}: the sign-in expired`);
45
+ }
46
+ if (!response.ok) {
47
+ // Down for a moment: asked again.
48
+ return 'pending';
49
+ }
50
+ const result = (await response.json().catch(() => ({})));
51
+ if (result.status === 'pending' || (result.status === 'completed' && !result.code) || !result.status) {
52
+ return 'pending';
53
+ }
54
+ if (result.status !== 'completed' || !result.code) {
55
+ throw new SignInError(`${this.name}: ${(_c = (_b = result.error_description) !== null && _b !== void 0 ? _b : result.error) !== null && _c !== void 0 ? _c : result.status}`);
56
+ }
57
+ const token = await SignInHttp.json(config.token_endpoint, SignInHttp.form({
58
+ grant_type: 'authorization_code',
59
+ code: result.code,
60
+ code_verifier: verifier,
61
+ client_id: this.options.clientId,
62
+ ...(result.redirect_uri ? { redirect_uri: result.redirect_uri } : {}),
63
+ }));
64
+ if (!token.access_token) {
65
+ throw new SignInError(`${this.name}: ${(_e = (_d = token.error_description) !== null && _d !== void 0 ? _d : token.error) !== null && _e !== void 0 ? _e : 'no access token'}`);
66
+ }
67
+ const user = await SignInHttp.json(config.userinfo_endpoint, { headers: { Authorization: `Bearer ${token.access_token}`, Accept: 'application/json' } });
68
+ // The login a company's people know each other by (`username`), else the id it gives: `iam:<login>`, as `user:<login>` of a link.
69
+ const login = (_a = (user.username || user.preferred_username || user.sub)) === null || _a === void 0 ? void 0 : _a.trim();
70
+ if (!login) {
71
+ throw new SignInError(`${this.name}: the account has no id`);
72
+ }
73
+ return { id: `${this.id}:${login}`, name: user.name || user.nickname || login, avatar: user.picture };
74
+ }
75
+ discover() {
76
+ if (!this.configuration) {
77
+ this.configuration = SignInHttp.json(`${this.options.issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`);
78
+ this.configuration.catch(() => (this.configuration = undefined));
79
+ }
80
+ return this.configuration;
81
+ }
82
+ }
83
+ //# sourceMappingURL=polled-sign-in.js.map
@@ -0,0 +1,55 @@
1
+ import type { TaDeviceSignInState } from '@celljs/ta-protocol';
2
+ import type { AccessStore } from './access-store.js';
3
+ import type { SignInAccount } from './sign-in-provider.js';
4
+ /** How long the user has to sign in in a browser once the device asked. */
5
+ export declare const DEVICE_CODE_TTL_MS: number;
6
+ /** How long a device signed in by an account not let in yet waits for it to be: it gets its token once it is. */
7
+ export declare const DEVICE_WAIT_TTL_MS: number;
8
+ /** How often a device polls. */
9
+ export declare const DEVICE_POLL_MS = 2000;
10
+ /** Devices under way at most: anyone may ask for a code. */
11
+ export declare const MAX_DEVICE_SIGN_INS = 1000;
12
+ interface DeviceSignIn {
13
+ device: string;
14
+ code: string;
15
+ /** What the device says it is, for the list of sign-ins. */
16
+ name?: string;
17
+ at: number;
18
+ /** Who signed in for it, in a browser. */
19
+ account?: SignInAccount;
20
+ }
21
+ export declare namespace SignInDevicesUtil {
22
+ /** `ABCD-EFGH`: 25⁸ codes, of which a few hundred live at once, each for minutes. */
23
+ function code(): string;
24
+ /** A code as the user may type it: any case, with or without its dash. */
25
+ function normalize(code: string): string;
26
+ }
27
+ /**
28
+ * Devices signing in as OAuth 2.0's device flow (TA_DEVICE_SIGN_IN_PATH): kept in memory, as the sign-ins under way
29
+ * of SignInFlow; a device that asked before a restart asks again. Whether an account is let in stays the store's: a
30
+ * device of one not let in waits, its account among the requests, and gets its token once let in.
31
+ */
32
+ export declare class SignInDevices {
33
+ protected readonly store: AccessStore;
34
+ protected readonly byCode: Map<string, DeviceSignIn>;
35
+ protected readonly byDevice: Map<string, DeviceSignIn>;
36
+ constructor(store: AccessStore);
37
+ start(name: string | undefined, now?: number): {
38
+ device: string;
39
+ code: string;
40
+ expiresAt: number;
41
+ };
42
+ /** What the device of a code said it is (its user agent), for the page that lets it in to show; none once used or late. */
43
+ name(code: string, now?: number): string | undefined;
44
+ /** Whether a code waits for someone to sign in for it, as a browser takes it to the provider and back. */
45
+ open(code: string, now?: number): boolean;
46
+ /**
47
+ * `account` signed in for the device of `code`, in a browser: let in, the device gets its token at its next poll; not,
48
+ * it waits among the requests. False for a code unknown, too late or signed in for already.
49
+ */
50
+ signedIn(code: string, account: SignInAccount, now?: number): boolean;
51
+ poll(device: string, now?: number): TaDeviceSignInState;
52
+ protected remove(entry: DeviceSignIn): void;
53
+ protected prune(now: number): void;
54
+ }
55
+ export {};
@@ -0,0 +1,113 @@
1
+ import { randomBytes, randomInt } from 'node:crypto';
2
+ /** How long the user has to sign in in a browser once the device asked. */
3
+ export const DEVICE_CODE_TTL_MS = 10 * 60 * 1000;
4
+ /** How long a device signed in by an account not let in yet waits for it to be: it gets its token once it is. */
5
+ export const DEVICE_WAIT_TTL_MS = 24 * 3600 * 1000;
6
+ /** How often a device polls. */
7
+ export const DEVICE_POLL_MS = 2000;
8
+ /** Devices under way at most: anyone may ask for a code. */
9
+ export const MAX_DEVICE_SIGN_INS = 1000;
10
+ /** No 0/O, 1/I/L, 2/Z, 5/S, 8/B: read off one screen and checked against another. */
11
+ const ALPHABET = 'ACDEFGHJKMNPQRTUVWXY34679';
12
+ export var SignInDevicesUtil;
13
+ (function (SignInDevicesUtil) {
14
+ /** `ABCD-EFGH`: 25⁸ codes, of which a few hundred live at once, each for minutes. */
15
+ function code() {
16
+ let text = '';
17
+ for (let i = 0; i < 8; i++) {
18
+ text += ALPHABET[randomInt(ALPHABET.length)];
19
+ }
20
+ return `${text.slice(0, 4)}-${text.slice(4)}`;
21
+ }
22
+ SignInDevicesUtil.code = code;
23
+ /** A code as the user may type it: any case, with or without its dash. */
24
+ function normalize(code) {
25
+ const plain = code.toUpperCase().replace(/[^A-Z0-9]/g, '');
26
+ return plain.length === 8 ? `${plain.slice(0, 4)}-${plain.slice(4)}` : '';
27
+ }
28
+ SignInDevicesUtil.normalize = normalize;
29
+ })(SignInDevicesUtil || (SignInDevicesUtil = {}));
30
+ /**
31
+ * Devices signing in as OAuth 2.0's device flow (TA_DEVICE_SIGN_IN_PATH): kept in memory, as the sign-ins under way
32
+ * of SignInFlow; a device that asked before a restart asks again. Whether an account is let in stays the store's: a
33
+ * device of one not let in waits, its account among the requests, and gets its token once let in.
34
+ */
35
+ export class SignInDevices {
36
+ constructor(store) {
37
+ this.store = store;
38
+ this.byCode = new Map();
39
+ this.byDevice = new Map();
40
+ }
41
+ start(name, now = Date.now()) {
42
+ this.prune(now);
43
+ for (const oldest of this.byCode.values()) {
44
+ if (this.byCode.size < MAX_DEVICE_SIGN_INS) {
45
+ break;
46
+ }
47
+ this.remove(oldest);
48
+ }
49
+ let code = SignInDevicesUtil.code();
50
+ while (this.byCode.has(code)) {
51
+ code = SignInDevicesUtil.code();
52
+ }
53
+ const entry = { device: randomBytes(32).toString('base64url'), code, name: (name === null || name === void 0 ? void 0 : name.trim().slice(0, 100)) || undefined, at: now };
54
+ this.byCode.set(code, entry);
55
+ this.byDevice.set(entry.device, entry);
56
+ return { device: entry.device, code, expiresAt: now + DEVICE_CODE_TTL_MS };
57
+ }
58
+ /** What the device of a code said it is (its user agent), for the page that lets it in to show; none once used or late. */
59
+ name(code, now = Date.now()) {
60
+ const entry = this.byCode.get(SignInDevicesUtil.normalize(code));
61
+ return entry && !entry.account && now - entry.at <= DEVICE_CODE_TTL_MS ? entry.name : undefined;
62
+ }
63
+ /** Whether a code waits for someone to sign in for it, as a browser takes it to the provider and back. */
64
+ open(code, now = Date.now()) {
65
+ const entry = this.byCode.get(SignInDevicesUtil.normalize(code));
66
+ return Boolean(entry && !entry.account && now - entry.at <= DEVICE_CODE_TTL_MS);
67
+ }
68
+ /**
69
+ * `account` signed in for the device of `code`, in a browser: let in, the device gets its token at its next poll; not,
70
+ * it waits among the requests. False for a code unknown, too late or signed in for already.
71
+ */
72
+ signedIn(code, account, now = Date.now()) {
73
+ const entry = this.byCode.get(SignInDevicesUtil.normalize(code));
74
+ if (!entry || entry.account || now - entry.at > DEVICE_CODE_TTL_MS) {
75
+ return false;
76
+ }
77
+ entry.account = account;
78
+ entry.at = now;
79
+ if (!this.store.allows(account.id)) {
80
+ this.store.request(account, now);
81
+ }
82
+ return true;
83
+ }
84
+ poll(device, now = Date.now()) {
85
+ const entry = this.byDevice.get(device);
86
+ if (!entry || now - entry.at > (entry.account ? DEVICE_WAIT_TTL_MS : DEVICE_CODE_TTL_MS)) {
87
+ if (entry) {
88
+ this.remove(entry);
89
+ }
90
+ return { status: 'expired' };
91
+ }
92
+ if (!entry.account) {
93
+ return { status: 'pending' };
94
+ }
95
+ if (!this.store.allows(entry.account.id)) {
96
+ return { status: 'waiting', account: entry.account.id };
97
+ }
98
+ this.remove(entry);
99
+ return { status: 'done', token: this.store.signIn(entry.account, entry.name, now), account: entry.account.id };
100
+ }
101
+ remove(entry) {
102
+ this.byCode.delete(entry.code);
103
+ this.byDevice.delete(entry.device);
104
+ }
105
+ prune(now) {
106
+ for (const entry of this.byCode.values()) {
107
+ if (now - entry.at > (entry.account ? DEVICE_WAIT_TTL_MS : DEVICE_CODE_TTL_MS)) {
108
+ this.remove(entry);
109
+ }
110
+ }
111
+ }
112
+ }
113
+ //# sourceMappingURL=sign-in-devices.js.map
@@ -1,8 +1,12 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { AccessStore } from './access-store.js';
3
+ import type { PolledSignInProvider } from './polled-sign-in.js';
4
+ import { SignInDevices } from './sign-in-devices.js';
3
5
  import { type SignInAccount, type SignInProvider } from './sign-in-provider.js';
4
6
  /** Sign-ins under way at most: anyone may start one without a token, and each is kept until it ends or expires. */
5
7
  export declare const MAX_PENDING_SIGN_INS = 1000;
8
+ /** How often a polled provider is asked whether the user agreed. */
9
+ export declare const POLL_MS = 2000;
6
10
  interface Pending {
7
11
  provider: string;
8
12
  verifier: string;
@@ -11,13 +15,20 @@ interface Pending {
11
15
  bind: boolean;
12
16
  /** Only says who signed in (TaHostAccounts.verify): lets no one into ta serve. */
13
17
  verify?: true;
18
+ /** For the device of this code (SignInDevices), not the browser: the browser gets no token. */
19
+ device?: string;
14
20
  at: number;
15
21
  }
22
+ /** In with a token, told to wait, or signed in for a device (`allowed`: it gets its token at once, else once let in). */
16
23
  export type SignInResult = {
17
24
  token: string;
18
25
  account: SignInAccount;
19
26
  } | {
20
27
  denied: SignInAccount;
28
+ } | {
29
+ device: string;
30
+ account: SignInAccount;
31
+ allowed: boolean;
21
32
  };
22
33
  export declare namespace SignInUtil {
23
34
  /**
@@ -41,8 +52,31 @@ export declare class SignInFlow {
41
52
  providers: SignInProvider[];
42
53
  readonly store: AccessStore;
43
54
  readonly publicUrl?: string | undefined;
44
- constructor(providers: SignInProvider[], store: AccessStore, publicUrl?: string | undefined);
55
+ /** Those the browser signs in at without coming back (PolledSignInProvider): for devices, whose code they sign in for. */
56
+ polled: PolledSignInProvider[];
57
+ constructor(providers: SignInProvider[], store: AccessStore, publicUrl?: string | undefined,
58
+ /** Those the browser signs in at without coming back (PolledSignInProvider): for devices, whose code they sign in for. */
59
+ polled?: PolledSignInProvider[]);
60
+ /** What Ta asks each polled provider for, by the code of the device it is for: one at a time for a code. */
61
+ protected readonly polling: Map<string, {
62
+ stopped: boolean;
63
+ }>;
64
+ protected pollMs: number;
65
+ /**
66
+ * Signs in with a polled provider for the device of `code`: where the browser goes; Ta asks the provider until it says
67
+ * who agreed, and lets the device in as them (SignInDevices.signedIn), or until it is too late or the code taken.
68
+ */
69
+ startPolled(providerId: string, code: string, now?: number): Promise<string>;
70
+ protected pollUntil(provider: PolledSignInProvider, signIn: {
71
+ poll(): Promise<SignInAccount | 'pending'>;
72
+ }, code: string, run: {
73
+ stopped: boolean;
74
+ }, deadline: number): Promise<void>;
75
+ /** Stops what is asked of polled providers: the server closes. */
76
+ stopPolling(): void;
45
77
  protected readonly pending: Map<string, Pending>;
78
+ /** The devices that sign in through a browser (TA_DEVICE_SIGN_IN_PATH). */
79
+ readonly devices: SignInDevices;
46
80
  protected readonly binds: Map<string, {
47
81
  provider: string;
48
82
  at: number;
@@ -50,8 +84,8 @@ export declare class SignInFlow {
50
84
  provider(id: string): SignInProvider | undefined;
51
85
  /** A link, used once, that signs in with `provider` and lets the account in. */
52
86
  bindUrl(provider: string, now?: number): string;
53
- /** Where the browser goes, and the state that comes back with it. */
54
- start(providerId: string, origin: string, bind?: string, now?: number): Promise<{
87
+ /** Where the browser goes, and the state that comes back with it; with `device`, it signs in for the device of that code. */
88
+ start(providerId: string, origin: string, bind?: string, now?: number, device?: string): Promise<{
55
89
  url: string;
56
90
  state: string;
57
91
  }>;
@@ -62,7 +96,7 @@ export declare class SignInFlow {
62
96
  }>;
63
97
  /** The account of a sign-in of {@link startVerify}: no token, nothing let in. */
64
98
  verify(state: string, code: string, now?: number): Promise<SignInAccount>;
65
- protected begin(providerId: string, redirectUri: string, kind: Pick<Pending, 'bind' | 'verify'>, now: number): Promise<{
99
+ protected begin(providerId: string, redirectUri: string, kind: Pick<Pending, 'bind' | 'verify' | 'device'>, now: number): Promise<{
66
100
  url: string;
67
101
  state: string;
68
102
  }>;
@@ -1,11 +1,14 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { TA_SIGN_IN_PATH } from '@celljs/ta-protocol';
3
+ import { SignInDevices } from './sign-in-devices.js';
3
4
  import { SignInError } from './sign-in-provider.js';
4
5
  /** How long the browser has with the provider, and a link of {@link SignInFlow.bindUrl}. */
5
6
  const PENDING_TTL_MS = 10 * 60 * 1000;
6
7
  const BIND_TTL_MS = 5 * 60 * 1000;
7
8
  /** Sign-ins under way at most: anyone may start one without a token, and each is kept until it ends or expires. */
8
9
  export const MAX_PENDING_SIGN_INS = 1000;
10
+ /** How often a polled provider is asked whether the user agreed. */
11
+ export const POLL_MS = 2000;
9
12
  export var SignInUtil;
10
13
  (function (SignInUtil) {
11
14
  /**
@@ -39,12 +42,75 @@ export var SignInUtil;
39
42
  * gateway (`ta gateway`) use it alike.
40
43
  */
41
44
  export class SignInFlow {
42
- constructor(providers, store, publicUrl) {
45
+ constructor(providers, store, publicUrl,
46
+ /** Those the browser signs in at without coming back (PolledSignInProvider): for devices, whose code they sign in for. */
47
+ polled = []) {
43
48
  this.providers = providers;
44
49
  this.store = store;
45
50
  this.publicUrl = publicUrl;
51
+ this.polled = polled;
52
+ /** What Ta asks each polled provider for, by the code of the device it is for: one at a time for a code. */
53
+ this.polling = new Map();
54
+ this.pollMs = POLL_MS;
46
55
  this.pending = new Map();
47
56
  this.binds = new Map();
57
+ this.devices = new SignInDevices(store);
58
+ }
59
+ /**
60
+ * Signs in with a polled provider for the device of `code`: where the browser goes; Ta asks the provider until it says
61
+ * who agreed, and lets the device in as them (SignInDevices.signedIn), or until it is too late or the code taken.
62
+ */
63
+ async startPolled(providerId, code, now = Date.now()) {
64
+ const provider = this.polled.find(one => one.id === providerId);
65
+ if (!provider) {
66
+ throw new SignInError(`No provider ${providerId}`);
67
+ }
68
+ if (!this.devices.open(code, now)) {
69
+ throw new SignInError('The code of the device expired or is not known here');
70
+ }
71
+ if (!this.polling.has(code) && this.polling.size >= MAX_PENDING_SIGN_INS) {
72
+ throw new SignInError('Too many sign-ins under way');
73
+ }
74
+ const signIn = await provider.begin();
75
+ const previous = this.polling.get(code);
76
+ if (previous) {
77
+ previous.stopped = true;
78
+ }
79
+ const run = { stopped: false };
80
+ this.polling.set(code, run);
81
+ void this.pollUntil(provider, signIn, code, run, now + signIn.expiresIn * 1000);
82
+ return signIn.url;
83
+ }
84
+ async pollUntil(provider, signIn, code, run, deadline) {
85
+ try {
86
+ while (!run.stopped && Date.now() < deadline && this.devices.open(code)) {
87
+ await new Promise(resolve => setTimeout(resolve, this.pollMs));
88
+ if (run.stopped) {
89
+ return;
90
+ }
91
+ const answer = await signIn.poll().catch(error => (error instanceof SignInError ? error : 'pending'));
92
+ if (answer instanceof SignInError) {
93
+ console.warn(`signing in with ${provider.id} failed: ${answer.message}`);
94
+ return;
95
+ }
96
+ if (answer !== 'pending') {
97
+ this.devices.signedIn(code, answer);
98
+ return;
99
+ }
100
+ }
101
+ }
102
+ finally {
103
+ if (this.polling.get(code) === run) {
104
+ this.polling.delete(code);
105
+ }
106
+ }
107
+ }
108
+ /** Stops what is asked of polled providers: the server closes. */
109
+ stopPolling() {
110
+ for (const run of this.polling.values()) {
111
+ run.stopped = true;
112
+ }
113
+ this.polling.clear();
48
114
  }
49
115
  provider(id) {
50
116
  return this.providers.find(provider => provider.id === id);
@@ -55,14 +121,17 @@ export class SignInFlow {
55
121
  this.binds.set(nonce, { provider, at: now });
56
122
  return `${TA_SIGN_IN_PATH}/${provider}?bind=${nonce}`;
57
123
  }
58
- /** Where the browser goes, and the state that comes back with it. */
59
- async start(providerId, origin, bind, now = Date.now()) {
124
+ /** Where the browser goes, and the state that comes back with it; with `device`, it signs in for the device of that code. */
125
+ async start(providerId, origin, bind, now = Date.now(), device) {
60
126
  this.prune(now);
61
127
  const binding = bind ? this.binds.get(bind) : undefined;
62
128
  if (bind) {
63
129
  this.binds.delete(bind);
64
130
  }
65
- return this.begin(providerId, SignInUtil.redirectUri(origin, providerId), { bind: (binding === null || binding === void 0 ? void 0 : binding.provider) === providerId }, now);
131
+ if (device !== undefined && !this.devices.open(device, now)) {
132
+ throw new SignInError('The code of the device expired or is not known here');
133
+ }
134
+ return this.begin(providerId, SignInUtil.redirectUri(origin, providerId), { bind: (binding === null || binding === void 0 ? void 0 : binding.provider) === providerId, ...(device !== undefined ? { device } : {}) }, now);
66
135
  }
67
136
  /** A sign-in that only says who it is ({@link verify}), coming back to `redirectUri`: the page of a relay, say. */
68
137
  startVerify(providerId, redirectUri, now = Date.now()) {
@@ -108,6 +177,12 @@ export class SignInFlow {
108
177
  if (pending.bind) {
109
178
  this.store.allow(account.id, account.name, now);
110
179
  }
180
+ if (pending.device !== undefined) {
181
+ if (!this.devices.signedIn(pending.device, account, now)) {
182
+ throw new SignInError('The code of the device expired or was used');
183
+ }
184
+ return { device: pending.device, account, allowed: this.store.allows(account.id) };
185
+ }
111
186
  if (!this.store.allows(account.id)) {
112
187
  this.store.request(account, now);
113
188
  return { denied: account };
@@ -11,6 +11,14 @@ export declare namespace SignInPageUtil {
11
11
  outcome: TaSignInOutcome;
12
12
  account?: string;
13
13
  }): string;
14
+ /**
15
+ * The page of the web client for the device of `code` (TA_DEVICE_SIGN_IN_PATH): where the user lets it in, and after
16
+ * the provider how it went (`done`: it gets its token; `waiting`: once the account is let in; `failed`).
17
+ */
18
+ function deviceBack(code: string, outcome?: 'done' | 'waiting' | 'failed', from?: string): string;
19
+ function json(response: ServerResponse, status: number, body: unknown): void;
20
+ /** A small JSON body; undefined for one too big or not JSON. */
21
+ function body(request: IncomingMessage, max?: number): Promise<Record<string, unknown> | undefined>;
14
22
  function redirect(response: ServerResponse, location: string): void;
15
23
  function end(response: ServerResponse, status: number, body?: string): void;
16
24
  }