@celljs/ta-host 4.16.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 (179) hide show
  1. package/esm/node/app-commands.d.ts +111 -0
  2. package/esm/node/app-commands.js +646 -0
  3. package/esm/node/credentials.d.ts +12 -0
  4. package/esm/node/credentials.js +35 -0
  5. package/esm/node/delegate-extension.d.ts +11 -0
  6. package/esm/node/delegate-extension.js +33 -0
  7. package/esm/node/directory-relocator.d.ts +49 -0
  8. package/esm/node/directory-relocator.js +267 -0
  9. package/esm/node/extension-providers.d.ts +16 -1
  10. package/esm/node/extension-providers.js +23 -3
  11. package/esm/node/index.d.ts +8 -0
  12. package/esm/node/index.js +8 -0
  13. package/esm/node/keep-awake.d.ts +8 -1
  14. package/esm/node/keep-awake.js +24 -3
  15. package/esm/node/message-page.d.ts +6 -1
  16. package/esm/node/message-page.js +50 -2
  17. package/esm/node/package-hosts.d.ts +8 -0
  18. package/esm/node/package-hosts.js +41 -0
  19. package/esm/node/package-webhooks.d.ts +26 -0
  20. package/esm/node/package-webhooks.js +101 -0
  21. package/esm/node/page-book.d.ts +48 -0
  22. package/esm/node/page-book.js +117 -0
  23. package/esm/node/relay-bridge.d.ts +2 -0
  24. package/esm/node/relay-bridge.js +35 -1
  25. package/esm/node/rooms-bridge.d.ts +13 -1
  26. package/esm/node/rooms-bridge.js +29 -0
  27. package/esm/node/screen-share/desktop-picture.d.ts +51 -0
  28. package/esm/node/screen-share/desktop-picture.js +133 -0
  29. package/esm/node/screen-share/desktop-session.d.ts +128 -0
  30. package/esm/node/screen-share/desktop-session.js +437 -0
  31. package/esm/node/screen-share/desktop-targets.d.ts +24 -0
  32. package/esm/node/screen-share/desktop-targets.js +80 -0
  33. package/esm/node/screen-share/desktop-viewer.d.ts +146 -0
  34. package/esm/node/screen-share/desktop-viewer.js +339 -0
  35. package/esm/node/screen-share/index.d.ts +8 -0
  36. package/esm/node/screen-share/index.js +9 -0
  37. package/esm/node/screen-share/rfb-client.d.ts +54 -0
  38. package/esm/node/screen-share/rfb-client.js +179 -0
  39. package/esm/node/screen-share/rfb-des.d.ts +11 -0
  40. package/esm/node/screen-share/rfb-des.js +143 -0
  41. package/esm/node/screen-share/rfb-encodings.d.ts +71 -0
  42. package/esm/node/screen-share/rfb-encodings.js +288 -0
  43. package/esm/node/screen-share/rfb-framebuffer.d.ts +16 -0
  44. package/esm/node/screen-share/rfb-framebuffer.js +53 -0
  45. package/esm/node/screen-share/rfb-protocol.d.ts +90 -0
  46. package/esm/node/screen-share/rfb-protocol.js +36 -0
  47. package/esm/node/screen-share/rfb-reader.d.ts +34 -0
  48. package/esm/node/screen-share/rfb-reader.js +110 -0
  49. package/esm/node/screen-share/rfb-security.d.ts +30 -0
  50. package/esm/node/screen-share/rfb-security.js +136 -0
  51. package/esm/node/screen-share/rfb-test-server.d.ts +37 -0
  52. package/esm/node/screen-share/rfb-test-server.js +116 -0
  53. package/esm/node/screen-share/screen-share-server-impl.d.ts +37 -0
  54. package/esm/node/screen-share/screen-share-server-impl.js +76 -0
  55. package/esm/node/screen-share/screen-shares.d.ts +123 -0
  56. package/esm/node/screen-share/screen-shares.js +463 -0
  57. package/esm/node/session-info-util.d.ts +10 -9
  58. package/esm/node/session-info-util.js +16 -68
  59. package/esm/node/settings-store.d.ts +1 -1
  60. package/esm/node/settings-store.js +7 -4
  61. package/esm/node/sign-in/access-store.d.ts +1 -1
  62. package/esm/node/sign-in/access-store.js +4 -1
  63. package/esm/node/sign-in/index.d.ts +2 -0
  64. package/esm/node/sign-in/index.js +2 -0
  65. package/esm/node/sign-in/polled-sign-in.d.ts +50 -0
  66. package/esm/node/sign-in/polled-sign-in.js +83 -0
  67. package/esm/node/sign-in/sign-in-devices.d.ts +55 -0
  68. package/esm/node/sign-in/sign-in-devices.js +113 -0
  69. package/esm/node/sign-in/sign-in-flow.d.ts +38 -4
  70. package/esm/node/sign-in/sign-in-flow.js +79 -4
  71. package/esm/node/sign-in/sign-in-pages.d.ts +8 -0
  72. package/esm/node/sign-in/sign-in-pages.js +137 -8
  73. package/esm/node/sign-in/sign-in-provider.d.ts +6 -0
  74. package/esm/node/sign-in/sign-in-provider.js +15 -0
  75. package/esm/node/sources-extension.d.ts +10 -0
  76. package/esm/node/sources-extension.js +18 -0
  77. package/esm/node/ta-server-impl.d.ts +5 -1
  78. package/esm/node/ta-server-impl.js +25 -3
  79. package/esm/node/ta-session-factory.d.ts +13 -1
  80. package/esm/node/ta-session-factory.js +41 -4
  81. package/esm/node/ta-session.d.ts +2 -0
  82. package/esm/node/ta-session.js +1 -0
  83. package/esm/node/team/team-calls.js +49 -0
  84. package/esm/node/voice-bridge.d.ts +70 -0
  85. package/esm/node/voice-bridge.js +280 -0
  86. package/esm/node/voices-file.d.ts +38 -0
  87. package/esm/node/voices-file.js +100 -0
  88. package/esm/node/working-directory.d.ts +8 -2
  89. package/esm/node/working-directory.js +7 -0
  90. package/lib/node/app-commands.d.ts +112 -0
  91. package/lib/node/app-commands.js +650 -0
  92. package/lib/node/credentials.d.ts +13 -0
  93. package/lib/node/credentials.js +38 -0
  94. package/lib/node/delegate-extension.d.ts +12 -0
  95. package/lib/node/delegate-extension.js +37 -0
  96. package/lib/node/directory-relocator.d.ts +50 -0
  97. package/lib/node/directory-relocator.js +270 -0
  98. package/lib/node/extension-providers.d.ts +16 -1
  99. package/lib/node/extension-providers.js +23 -3
  100. package/lib/node/index.d.ts +8 -0
  101. package/lib/node/index.js +8 -0
  102. package/lib/node/keep-awake.d.ts +8 -1
  103. package/lib/node/keep-awake.js +24 -3
  104. package/lib/node/message-page.d.ts +6 -1
  105. package/lib/node/message-page.js +50 -2
  106. package/lib/node/package-hosts.d.ts +8 -0
  107. package/lib/node/package-hosts.js +41 -0
  108. package/lib/node/package-webhooks.d.ts +27 -0
  109. package/lib/node/package-webhooks.js +104 -0
  110. package/lib/node/page-book.d.ts +49 -0
  111. package/lib/node/page-book.js +120 -0
  112. package/lib/node/relay-bridge.d.ts +2 -0
  113. package/lib/node/relay-bridge.js +34 -0
  114. package/lib/node/rooms-bridge.d.ts +13 -1
  115. package/lib/node/rooms-bridge.js +29 -0
  116. package/lib/node/screen-share/desktop-picture.d.ts +52 -0
  117. package/lib/node/screen-share/desktop-picture.js +136 -0
  118. package/lib/node/screen-share/desktop-session.d.ts +129 -0
  119. package/lib/node/screen-share/desktop-session.js +442 -0
  120. package/lib/node/screen-share/desktop-targets.d.ts +25 -0
  121. package/lib/node/screen-share/desktop-targets.js +84 -0
  122. package/lib/node/screen-share/desktop-viewer.d.ts +147 -0
  123. package/lib/node/screen-share/desktop-viewer.js +343 -0
  124. package/lib/node/screen-share/index.d.ts +9 -0
  125. package/lib/node/screen-share/index.js +25 -0
  126. package/lib/node/screen-share/rfb-client.d.ts +55 -0
  127. package/lib/node/screen-share/rfb-client.js +183 -0
  128. package/lib/node/screen-share/rfb-des.d.ts +12 -0
  129. package/lib/node/screen-share/rfb-des.js +146 -0
  130. package/lib/node/screen-share/rfb-encodings.d.ts +72 -0
  131. package/lib/node/screen-share/rfb-encodings.js +295 -0
  132. package/lib/node/screen-share/rfb-framebuffer.d.ts +17 -0
  133. package/lib/node/screen-share/rfb-framebuffer.js +57 -0
  134. package/lib/node/screen-share/rfb-protocol.d.ts +91 -0
  135. package/lib/node/screen-share/rfb-protocol.js +39 -0
  136. package/lib/node/screen-share/rfb-reader.d.ts +35 -0
  137. package/lib/node/screen-share/rfb-reader.js +115 -0
  138. package/lib/node/screen-share/rfb-security.d.ts +31 -0
  139. package/lib/node/screen-share/rfb-security.js +141 -0
  140. package/lib/node/screen-share/rfb-test-server.d.ts +38 -0
  141. package/lib/node/screen-share/rfb-test-server.js +120 -0
  142. package/lib/node/screen-share/screen-share-server-impl.d.ts +38 -0
  143. package/lib/node/screen-share/screen-share-server-impl.js +79 -0
  144. package/lib/node/screen-share/screen-shares.d.ts +124 -0
  145. package/lib/node/screen-share/screen-shares.js +464 -0
  146. package/lib/node/session-info-util.d.ts +10 -9
  147. package/lib/node/session-info-util.js +15 -67
  148. package/lib/node/settings-store.d.ts +1 -1
  149. package/lib/node/settings-store.js +6 -3
  150. package/lib/node/sign-in/access-store.d.ts +1 -1
  151. package/lib/node/sign-in/access-store.js +4 -1
  152. package/lib/node/sign-in/index.d.ts +2 -0
  153. package/lib/node/sign-in/index.js +2 -0
  154. package/lib/node/sign-in/polled-sign-in.d.ts +51 -0
  155. package/lib/node/sign-in/polled-sign-in.js +87 -0
  156. package/lib/node/sign-in/sign-in-devices.d.ts +56 -0
  157. package/lib/node/sign-in/sign-in-devices.js +117 -0
  158. package/lib/node/sign-in/sign-in-flow.d.ts +38 -4
  159. package/lib/node/sign-in/sign-in-flow.js +80 -5
  160. package/lib/node/sign-in/sign-in-pages.d.ts +8 -0
  161. package/lib/node/sign-in/sign-in-pages.js +136 -7
  162. package/lib/node/sign-in/sign-in-provider.d.ts +6 -0
  163. package/lib/node/sign-in/sign-in-provider.js +15 -0
  164. package/lib/node/sources-extension.d.ts +11 -0
  165. package/lib/node/sources-extension.js +22 -0
  166. package/lib/node/ta-server-impl.d.ts +5 -1
  167. package/lib/node/ta-server-impl.js +24 -2
  168. package/lib/node/ta-session-factory.d.ts +13 -1
  169. package/lib/node/ta-session-factory.js +40 -3
  170. package/lib/node/ta-session.d.ts +2 -0
  171. package/lib/node/ta-session.js +1 -0
  172. package/lib/node/team/team-calls.js +49 -0
  173. package/lib/node/voice-bridge.d.ts +71 -0
  174. package/lib/node/voice-bridge.js +281 -0
  175. package/lib/node/voices-file.d.ts +39 -0
  176. package/lib/node/voices-file.js +104 -0
  177. package/lib/node/working-directory.d.ts +8 -2
  178. package/lib/node/working-directory.js +7 -0
  179. package/package.json +14 -10
@@ -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
  }
@@ -1,4 +1,5 @@
1
- import { TA_SIGN_IN_PATH } from '@celljs/ta-protocol';
1
+ import { TA_DEVICE_SIGN_IN_PATH, TA_SIGN_IN_PATH } from '@celljs/ta-protocol';
2
+ import { DEVICE_POLL_MS, SignInDevicesUtil } from './sign-in-devices.js';
2
3
  import { SignInUtil } from './sign-in-flow.js';
3
4
  /** Ties the browser that comes back from the provider to the one that went: login CSRF. */
4
5
  const STATE_COOKIE = 'ta_sign_in';
@@ -26,6 +27,40 @@ export var SignInPageUtil;
26
27
  return `/#${params.toString()}`;
27
28
  }
28
29
  SignInPageUtil.back = back;
30
+ /**
31
+ * The page of the web client for the device of `code` (TA_DEVICE_SIGN_IN_PATH): where the user lets it in, and after
32
+ * the provider how it went (`done`: it gets its token; `waiting`: once the account is let in; `failed`).
33
+ */
34
+ function deviceBack(code, outcome, from) {
35
+ return `/#${new URLSearchParams({ device: code, ...(outcome ? { 'device-sign-in': outcome } : {}), ...(from ? { from } : {}) }).toString()}`;
36
+ }
37
+ SignInPageUtil.deviceBack = deviceBack;
38
+ function json(response, status, body) {
39
+ response.statusCode = status;
40
+ response.setHeader('Content-Type', 'application/json');
41
+ response.end(JSON.stringify(body));
42
+ }
43
+ SignInPageUtil.json = json;
44
+ /** A small JSON body; undefined for one too big or not JSON. */
45
+ async function body(request, max = 4096) {
46
+ const chunks = [];
47
+ let size = 0;
48
+ for await (const chunk of request) {
49
+ size += chunk.length;
50
+ if (size > max) {
51
+ return undefined;
52
+ }
53
+ chunks.push(chunk);
54
+ }
55
+ try {
56
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
57
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
58
+ }
59
+ catch (_a) {
60
+ return undefined;
61
+ }
62
+ }
63
+ SignInPageUtil.body = body;
29
64
  function redirect(response, location) {
30
65
  response.statusCode = 302;
31
66
  response.setHeader('Location', location);
@@ -52,10 +87,14 @@ export var SignInPages;
52
87
  }
53
88
  SignInPages.matches = matches;
54
89
  async function handle(request, response, flow, options) {
55
- var _a, _b;
90
+ var _a, _b, _c, _d;
56
91
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://localhost');
57
92
  response.setHeader('Cache-Control', 'no-store');
58
93
  response.setHeader('Referrer-Policy', 'no-referrer');
94
+ if (url.pathname === TA_DEVICE_SIGN_IN_PATH || url.pathname.startsWith(`${TA_DEVICE_SIGN_IN_PATH}/`)) {
95
+ await device(request, response, flow, url, options);
96
+ return;
97
+ }
59
98
  if (request.method !== 'GET' && request.method !== 'HEAD') {
60
99
  response.setHeader('Allow', 'GET, HEAD');
61
100
  SignInPageUtil.end(response, 405);
@@ -63,33 +102,56 @@ export var SignInPages;
63
102
  }
64
103
  const [providerId, step, ...rest] = url.pathname.slice(TA_SIGN_IN_PATH.length + 1).split('/');
65
104
  if (!providerId) {
66
- const ways = { providers: flow.providers.map(({ id, name }) => ({ id, name })) };
105
+ const ways = {
106
+ providers: [
107
+ ...flow.providers.map(({ id, name }) => ({ id, name })),
108
+ ...flow.polled.map(({ id, name }) => ({ id, name, polled: true })),
109
+ ],
110
+ };
67
111
  response.setHeader('Content-Type', 'application/json');
112
+ // Which ways there are is no secret: the app and Ta Desktop, of another origin, offer them on their sign-in.
113
+ response.setHeader('Access-Control-Allow-Origin', '*');
68
114
  SignInPageUtil.end(response, 200, JSON.stringify(ways));
69
115
  return;
70
116
  }
117
+ const polled = flow.polled.some(one => one.id === providerId);
118
+ if (polled && !step && rest.length === 0) {
119
+ await goPolled(response, flow, providerId, (_b = url.searchParams.get('device')) !== null && _b !== void 0 ? _b : '', options);
120
+ return;
121
+ }
71
122
  if (!flow.provider(providerId) || rest.length > 0 || (step && step !== 'callback')) {
72
123
  SignInPageUtil.end(response, 404);
73
124
  return;
74
125
  }
75
126
  if (!step) {
76
- await go(request, response, flow, providerId, (_b = url.searchParams.get('bind')) !== null && _b !== void 0 ? _b : undefined, options);
127
+ await go(request, response, flow, providerId, (_c = url.searchParams.get('bind')) !== null && _c !== void 0 ? _c : undefined, options, (_d = url.searchParams.get('device')) !== null && _d !== void 0 ? _d : undefined);
77
128
  return;
78
129
  }
79
130
  await back(request, response, flow, providerId, url.searchParams, options);
80
131
  }
81
132
  SignInPages.handle = handle;
82
- async function go(request, response, flow, providerId, bind, options) {
133
+ async function go(request, response, flow, providerId, bind, options, device) {
83
134
  const origin = SignInUtil.origin(request, flow.publicUrl);
84
135
  try {
85
- const { url, state } = await flow.start(providerId, origin, bind);
136
+ const { url, state } = await flow.start(providerId, origin, bind, Date.now(), device === undefined ? undefined : SignInDevicesUtil.normalize(device));
86
137
  const secure = origin.startsWith('https:') ? '; Secure' : '';
87
138
  response.setHeader('Set-Cookie', `${STATE_COOKIE}=${state}; Path=${TA_SIGN_IN_PATH}; Max-Age=600; HttpOnly; SameSite=Lax${secure}`);
88
139
  SignInPageUtil.redirect(response, url);
89
140
  }
90
141
  catch (error) {
91
142
  console.warn(`${options.name}: signing in with ${providerId} failed: ${error instanceof Error ? error.message : error}`);
92
- SignInPageUtil.redirect(response, SignInPageUtil.back({ outcome: 'failed' }));
143
+ SignInPageUtil.redirect(response, device === undefined ? SignInPageUtil.back({ outcome: 'failed' }) : SignInPageUtil.deviceBack(SignInDevicesUtil.normalize(device), 'failed'));
144
+ }
145
+ }
146
+ /** To a polled provider for the device of `code`; Ta asks it who agreed. Only for a device: a browser does not come back. */
147
+ async function goPolled(response, flow, providerId, given, options) {
148
+ const code = SignInDevicesUtil.normalize(given);
149
+ try {
150
+ SignInPageUtil.redirect(response, await flow.startPolled(providerId, code));
151
+ }
152
+ catch (error) {
153
+ console.warn(`${options.name}: signing in with ${providerId} failed: ${error instanceof Error ? error.message : error}`);
154
+ SignInPageUtil.redirect(response, SignInPageUtil.deviceBack(code, 'failed'));
93
155
  }
94
156
  }
95
157
  async function back(request, response, flow, providerId, params, options) {
@@ -105,7 +167,11 @@ export var SignInPages;
105
167
  }
106
168
  try {
107
169
  const result = await flow.finish(providerId, state, code, request.headers['user-agent']);
108
- if ('token' in result) {
170
+ if ('device' in result) {
171
+ console.log(`${options.name}: ${result.account.id} signed in for a device${result.allowed ? '' : ', which waits for the account to be let in'}`);
172
+ SignInPageUtil.redirect(response, SignInPageUtil.deviceBack(result.device, result.allowed ? 'done' : 'waiting'));
173
+ }
174
+ else if ('token' in result) {
109
175
  console.log(`${options.name}: ${result.account.id} signed in`);
110
176
  await ((_a = options.onSignedIn) === null || _a === void 0 ? void 0 : _a.call(options, response, result.token, result.account, SignInUtil.origin(request, flow.publicUrl)));
111
177
  SignInPageUtil.redirect(response, SignInPageUtil.back({ token: result.token }));
@@ -121,4 +187,67 @@ export var SignInPages;
121
187
  }
122
188
  }
123
189
  })(SignInPages || (SignInPages = {}));
190
+ /** Answers any origin: what these give goes to who holds the secret of the device, and no cookie is read. */
191
+ const DEVICE_CORS = {
192
+ 'Access-Control-Allow-Origin': '*',
193
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
194
+ 'Access-Control-Allow-Headers': 'Content-Type',
195
+ 'Access-Control-Max-Age': '600',
196
+ };
197
+ /**
198
+ * TA_DEVICE_SIGN_IN_PATH: `POST` asks for a code, `POST /poll` takes the token once the user let the device in, from any
199
+ * origin; `GET ?code=` is where the user goes, the page of the web client; `POST /approve`, with the token of a browser
200
+ * signed in here, lets the device in as its account, with no provider (a sign-in by `ta gateway link` has none).
201
+ */
202
+ async function device(request, response, flow, url, options) {
203
+ var _a;
204
+ const step = url.pathname.slice(TA_DEVICE_SIGN_IN_PATH.length);
205
+ if (step !== '/approve') {
206
+ for (const [name, value] of Object.entries(DEVICE_CORS)) {
207
+ response.setHeader(name, value);
208
+ }
209
+ }
210
+ if (request.method === 'OPTIONS') {
211
+ SignInPageUtil.end(response, 204);
212
+ return;
213
+ }
214
+ if (step === '' && request.method === 'GET') {
215
+ const code = SignInDevicesUtil.normalize((_a = url.searchParams.get('code')) !== null && _a !== void 0 ? _a : '');
216
+ SignInPageUtil.redirect(response, SignInPageUtil.deviceBack(code, undefined, flow.devices.name(code)));
217
+ return;
218
+ }
219
+ if (request.method !== 'POST' || !['', '/poll', '/approve'].includes(step)) {
220
+ SignInPageUtil.end(response, step === '' || step === '/poll' || step === '/approve' ? 405 : 404);
221
+ return;
222
+ }
223
+ const body = await SignInPageUtil.body(request);
224
+ if (!body) {
225
+ SignInPageUtil.end(response, 400);
226
+ return;
227
+ }
228
+ if (step === '') {
229
+ const started = flow.devices.start(typeof body.name === 'string' ? body.name : undefined);
230
+ const origin = SignInUtil.origin(request, flow.publicUrl);
231
+ const answer = { ...started, url: `${origin}${TA_DEVICE_SIGN_IN_PATH}?code=${started.code}`, interval: DEVICE_POLL_MS };
232
+ SignInPageUtil.json(response, 200, answer);
233
+ return;
234
+ }
235
+ if (step === '/poll') {
236
+ const state = flow.devices.poll(typeof body.device === 'string' ? body.device : '');
237
+ if (state.status === 'done') {
238
+ console.log(`${options.name}: ${state.account} signed in on a device`);
239
+ }
240
+ SignInPageUtil.json(response, 200, state);
241
+ return;
242
+ }
243
+ const header = request.headers.authorization;
244
+ const signIn = (header === null || header === void 0 ? void 0 : header.startsWith('Bearer ')) ? flow.store.check(header.slice('Bearer '.length)) : undefined;
245
+ if (!signIn) {
246
+ SignInPageUtil.end(response, 401);
247
+ return;
248
+ }
249
+ const code = typeof body.code === 'string' ? body.code : '';
250
+ const ok = flow.devices.signedIn(code, { id: signIn.account, name: signIn.name, avatar: signIn.avatar });
251
+ SignInPageUtil.json(response, ok ? 200 : 404, { ok });
252
+ }
124
253
  //# sourceMappingURL=sign-in-pages.js.map
@@ -1,4 +1,5 @@
1
1
  import type { TaSignInKind, TaSignInProvider, TaSignInSetup } from '@celljs/ta-protocol';
2
+ import { type PolledSignInProvider } from './polled-sign-in.js';
2
3
  /** Who signed in, as the provider says: `id` is the account as TA_ALLOWED_USERS names it (`github:<login>`). */
3
4
  export interface SignInAccount {
4
5
  id: string;
@@ -209,6 +210,11 @@ export declare namespace SignInProviders {
209
210
  * one's own with its device flow on; by default Ta's own, on GitHub.com.
210
211
  */
211
212
  function device(env: Record<string, string | undefined>): DeviceSignInProvider | undefined;
213
+ /**
214
+ * The polled providers of the environment (PushedSignIn): `TA_IAM_ISSUER` and `TA_IAM_CLIENT_ID`, a company's sign-in
215
+ * for CLIs, whose accounts are `iam:<sub>`; `TA_IAM_CLI_ID` and `TA_IAM_NAME` (what its button says) optional.
216
+ */
217
+ function polled(env: Record<string, string | undefined>): PolledSignInProvider[];
212
218
  /**
213
219
  * The providers the operator configured in the environment of ta serve: a provider is offered when it
214
220
  * has its id and its secret.
@@ -1,3 +1,4 @@
1
+ import { PushedSignIn } from './polled-sign-in.js';
1
2
  /** A sign-in that failed with the provider (a code refused, an account without what it needs). */
2
3
  export class SignInError extends Error {
3
4
  }
@@ -382,6 +383,20 @@ export var SignInProviders;
382
383
  return new GitHubDeviceSignIn(clientId || GitHubDeviceSignIn.CLIENT_ID, GitHubSignIn.endpoints(url || undefined));
383
384
  }
384
385
  SignInProviders.device = device;
386
+ /**
387
+ * The polled providers of the environment (PushedSignIn): `TA_IAM_ISSUER` and `TA_IAM_CLIENT_ID`, a company's sign-in
388
+ * for CLIs, whose accounts are `iam:<sub>`; `TA_IAM_CLI_ID` and `TA_IAM_NAME` (what its button says) optional.
389
+ */
390
+ function polled(env) {
391
+ var _a, _b, _c, _d;
392
+ const issuer = (_a = env.TA_IAM_ISSUER) === null || _a === void 0 ? void 0 : _a.trim();
393
+ const clientId = (_b = env.TA_IAM_CLIENT_ID) === null || _b === void 0 ? void 0 : _b.trim();
394
+ if (!issuer || !clientId) {
395
+ return [];
396
+ }
397
+ return [new PushedSignIn({ id: 'iam', name: ((_c = env.TA_IAM_NAME) === null || _c === void 0 ? void 0 : _c.trim()) || 'SSO', issuer, clientId, cliId: ((_d = env.TA_IAM_CLI_ID) === null || _d === void 0 ? void 0 : _d.trim()) || undefined })];
398
+ }
399
+ SignInProviders.polled = polled;
385
400
  /**
386
401
  * The providers the operator configured in the environment of ta serve: a provider is offered when it
387
402
  * has its id and its secret.
@@ -0,0 +1,10 @@
1
+ import type { ExtensionAPI, TaExtension } from '@celljs/ta-harness';
2
+ /**
3
+ * Tells the model of every session who wrote a message (docs/design/ta-sources.md): the user, a part of Ta for them
4
+ * (`[ta:from …]`), or a notice of a part of Ta (`[ta:notice …]`), which it weighs below what the user said. A section
5
+ * of pi's system prompt of its own (`<ta-sources>`), which other coding agents get with Ta's other notes.
6
+ */
7
+ export declare class SourcesExtension implements TaExtension {
8
+ readonly name = "ta-sources";
9
+ register(pi: ExtensionAPI): void;
10
+ }
@@ -0,0 +1,18 @@
1
+ import { TaMessageSource } from '@celljs/ta-protocol';
2
+ /**
3
+ * Tells the model of every session who wrote a message (docs/design/ta-sources.md): the user, a part of Ta for them
4
+ * (`[ta:from …]`), or a notice of a part of Ta (`[ta:notice …]`), which it weighs below what the user said. A section
5
+ * of pi's system prompt of its own (`<ta-sources>`), which other coding agents get with Ta's other notes.
6
+ */
7
+ export class SourcesExtension {
8
+ constructor() {
9
+ this.name = 'ta-sources';
10
+ }
11
+ register(pi) {
12
+ pi.on('before_agent_start', event => {
13
+ const options = event.systemPromptOptions;
14
+ options.sections = { ...options.sections, [TaMessageSource.SECTION]: TaMessageSource.PROMPT };
15
+ });
16
+ }
17
+ }
18
+ //# sourceMappingURL=sources-extension.js.map
@@ -1,5 +1,6 @@
1
1
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
2
- import { type ImageContent, type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenedSession, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, type TaSavedSessionQuery, TaServer, type TaServerInfo, type TaSessionInfo, type TaSlashCommand, type ThinkingLevel } from '@celljs/ta-protocol';
2
+ import { type ImageContent, type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenedSession, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaRelocateResult, type TaSavedSessionInfo, type TaSavedSessionQuery, TaServer, type TaServerInfo, type TaSessionInfo, type TaSlashCommand, type ThinkingLevel } from '@celljs/ta-protocol';
3
+ import { TaDirectoryRelocator } from './directory-relocator.js';
3
4
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
4
5
  import { TaServeUpdates } from './serve-updates.js';
5
6
  import type { TaSession } from './ta-session.js';
@@ -21,6 +22,7 @@ export declare class TaServerImpl implements TaServer {
21
22
  protected readonly authority: TaAuthority;
22
23
  protected readonly visibility: TaVisibility;
23
24
  protected readonly updates: TaServeUpdates;
25
+ protected readonly relocator: TaDirectoryRelocator;
24
26
  getServerInfo(): Promise<TaServerInfo>;
25
27
  restartServer(): Promise<void>;
26
28
  setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
@@ -73,6 +75,8 @@ export declare class TaServerImpl implements TaServer {
73
75
  switchSession(sessionId: string, sessionPath: string): Promise<TaCommandResult<'switch_session'>>;
74
76
  fork(sessionId: string, entryId: string, position?: 'before' | 'at'): Promise<TaCommandResult<'fork'>>;
75
77
  forkToFile(sessionId: string, entryId: string, position?: 'before' | 'at'): Promise<TaForkFileResult>;
78
+ forkHere(sessionId: string): Promise<TaForkFileResult>;
79
+ relocateDirectory(from: string, to: string): Promise<TaRelocateResult>;
76
80
  clone(sessionId: string): Promise<TaCommandResult<'clone'>>;
77
81
  getForkMessages(sessionId: string): Promise<TaCommandResult<'get_fork_messages'>>;
78
82
  getEntries(sessionId: string, since?: string): Promise<TaCommandResult<'get_entries'>>;
@@ -15,10 +15,10 @@ import { Rpc } from '@celljs/rpc';
15
15
  import { RpcContext } from '@celljs/rpc/lib/node';
16
16
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
17
17
  import { TaServeRestart } from '@celljs/ta-harness/lib/node/serve-restart';
18
- import { TA_OWNER, TaMessageAuthor, TaServer, } from '@celljs/ta-protocol';
18
+ import { TA_OWNER, TaMessageAuthor, TaSaid, TaServer, } from '@celljs/ta-protocol';
19
+ import { TaDirectoryRelocator } from './directory-relocator.js';
19
20
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
20
21
  import { TaServeUpdates } from './serve-updates.js';
21
- import { SessionInfoUtil } from './session-info-util.js';
22
22
  import { SlashCommandUtil } from './slash-command-util.js';
23
23
  import { TaErrors } from './ta-errors.js';
24
24
  import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol.js';
@@ -301,7 +301,8 @@ let TaServerImpl = class TaServerImpl {
301
301
  if (!entry || (position === 'before' && !user)) {
302
302
  throw TaErrors.invalidArgument(`No entry to fork from has the id ${entryId}.`, 'Pass the id of a message of the user, or position "at".');
303
303
  }
304
- const text = position === 'before' && user ? SessionInfoUtil.text(user.content) : undefined;
304
+ // What the user typed, to edit again: the marks of the model are made again when it is sent.
305
+ const text = position === 'before' && user ? TaSaid.of(user) : undefined;
305
306
  const leafId = position === 'before' ? entry.parentId : entry.id;
306
307
  const file = manager.getSessionFile();
307
308
  if (!leafId || !file || !existsSync(file)) {
@@ -315,6 +316,23 @@ let TaServerImpl = class TaServerImpl {
315
316
  return { sessionFile, text };
316
317
  });
317
318
  }
319
+ forkHere(sessionId) {
320
+ return this.on(sessionId, async ({ pi }) => {
321
+ var _a;
322
+ var _b;
323
+ const file = pi.sessionManager.getSessionFile();
324
+ if (!file || !existsSync(file)) {
325
+ return {};
326
+ }
327
+ const sdk = await PiSdkUtil.load();
328
+ const sessionFile = sdk.SessionManager.forkFrom(file, pi.sessionManager.getCwd()).getSessionFile();
329
+ this.runs.created(sessionFile, (_b = (_a = this.sessions.locate(sessionId)) === null || _a === void 0 ? void 0 : _a.cwd) !== null && _b !== void 0 ? _b : '');
330
+ return { sessionFile };
331
+ });
332
+ }
333
+ relocateDirectory(from, to) {
334
+ return this.guard(() => this.relocator.relocate(from, to));
335
+ }
318
336
  clone(sessionId) {
319
337
  return this.authored(sessionId, async ({ pi, runtime }) => {
320
338
  const leafId = pi.sessionManager.getLeafId();
@@ -435,6 +453,10 @@ __decorate([
435
453
  Autowired(TaServeUpdates),
436
454
  __metadata("design:type", Object)
437
455
  ], TaServerImpl.prototype, "updates", void 0);
456
+ __decorate([
457
+ Autowired(TaDirectoryRelocator),
458
+ __metadata("design:type", Object)
459
+ ], TaServerImpl.prototype, "relocator", void 0);
438
460
  TaServerImpl = __decorate([
439
461
  Rpc(TaServer)
440
462
  ], TaServerImpl);
@@ -7,6 +7,7 @@ import { type TaHostOptions, TaSessionFactory } from './host-protocol.js';
7
7
  import { PackageHosts } from './package-hosts.js';
8
8
  import { PiDirectories } from './remote/remote-protocol.js';
9
9
  import { TaSession } from './ta-session.js';
10
+ import { TaWorkingDirectory } from './working-directory.js';
10
11
  type AgentsFilesOverride = (base: {
11
12
  agentsFiles: ContextFile[];
12
13
  }) => {
@@ -20,6 +21,8 @@ export declare namespace SessionFileUtil {
20
21
  * not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
21
22
  */
22
23
  function cwdOverride(sessionFile: string, cwd: string): string | undefined;
24
+ /** `path` when it is a directory there now. */
25
+ function existing(path: string | undefined): string | undefined;
23
26
  }
24
27
  type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).ModelRuntime;
25
28
  type AgentSessionServices = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSessionServices;
@@ -43,6 +46,7 @@ export declare class DefaultTaSessionFactory implements TaSessionFactory {
43
46
  protected readonly tools: AgentTool[];
44
47
  protected readonly packageHosts: PackageHosts;
45
48
  protected readonly directories: PiDirectories;
49
+ protected readonly workingDirectory?: TaWorkingDirectory;
46
50
  protected readonly extensionProviders: ExtensionProviders;
47
51
  create(requested: TaOpenSessionOptions, requestClose: (session: TaSession, idle?: boolean) => void, id?: string): Promise<TaSession>;
48
52
  commands(cwd: string): Promise<TaSlashCommand[]>;
@@ -51,7 +55,15 @@ export declare class DefaultTaSessionFactory implements TaSessionFactory {
51
55
  * those of Ta. `commandsOnly`: for what a session would have, the context files of another machine not read.
52
56
  */
53
57
  protected services(sdk: PiSdk, options: ServicesOptions): Promise<AgentSessionServices>;
54
- protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): SessionManager;
58
+ /**
59
+ * pi's manager of the session file asked, or of a new one. A file whose directory is no longer there goes on
60
+ * in the directory of the server (TaWorkingDirectory), else the home directory, as pi's Continue: `movedFrom`, the directory as
61
+ * the file says it.
62
+ */
63
+ protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): {
64
+ sessionManager: SessionManager;
65
+ movedFrom?: string;
66
+ };
55
67
  /**
56
68
  * For another machine, its context files (AGENTS.md...) instead of those pi finds above the directory
57
69
  * of this machine it works in; the user's own, in the agent directory, stay.