@homelib/xiaomi 0.0.0-wip.01265bf1cc90

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 (183) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +26 -0
  3. package/bld/library/backend/client.d.ts +73 -0
  4. package/bld/library/backend/client.js +490 -0
  5. package/bld/library/backend/client.js.map +1 -0
  6. package/bld/library/backend/constants.d.ts +7 -0
  7. package/bld/library/backend/constants.js +11 -0
  8. package/bld/library/backend/constants.js.map +1 -0
  9. package/bld/library/backend/index.d.ts +3 -0
  10. package/bld/library/backend/index.js +4 -0
  11. package/bld/library/backend/index.js.map +1 -0
  12. package/bld/library/backend/oauth.d.ts +24 -0
  13. package/bld/library/backend/oauth.js +121 -0
  14. package/bld/library/backend/oauth.js.map +1 -0
  15. package/bld/library/binding.d.ts +44 -0
  16. package/bld/library/binding.js +212 -0
  17. package/bld/library/binding.js.map +1 -0
  18. package/bld/library/cloud/client.d.ts +27 -0
  19. package/bld/library/cloud/client.js +109 -0
  20. package/bld/library/cloud/client.js.map +1 -0
  21. package/bld/library/cloud/constants.d.ts +9 -0
  22. package/bld/library/cloud/constants.js +11 -0
  23. package/bld/library/cloud/constants.js.map +1 -0
  24. package/bld/library/cloud/device.d.ts +84 -0
  25. package/bld/library/cloud/device.js +686 -0
  26. package/bld/library/cloud/device.js.map +1 -0
  27. package/bld/library/cloud/index.d.ts +5 -0
  28. package/bld/library/cloud/index.js +6 -0
  29. package/bld/library/cloud/index.js.map +1 -0
  30. package/bld/library/cloud/mqtt.d.ts +69 -0
  31. package/bld/library/cloud/mqtt.js +517 -0
  32. package/bld/library/cloud/mqtt.js.map +1 -0
  33. package/bld/library/cloud/transport.d.ts +8 -0
  34. package/bld/library/cloud/transport.js +34 -0
  35. package/bld/library/cloud/transport.js.map +1 -0
  36. package/bld/library/command.d.ts +6 -0
  37. package/bld/library/command.js +6 -0
  38. package/bld/library/command.js.map +1 -0
  39. package/bld/library/configuration.d.ts +62 -0
  40. package/bld/library/configuration.js +303 -0
  41. package/bld/library/configuration.js.map +1 -0
  42. package/bld/library/device.d.ts +69 -0
  43. package/bld/library/device.js +266 -0
  44. package/bld/library/device.js.map +1 -0
  45. package/bld/library/devices/air-conditioner.d.ts +48 -0
  46. package/bld/library/devices/air-conditioner.js +155 -0
  47. package/bld/library/devices/air-conditioner.js.map +1 -0
  48. package/bld/library/devices/command-effect.d.ts +35 -0
  49. package/bld/library/devices/command-effect.js +269 -0
  50. package/bld/library/devices/command-effect.js.map +1 -0
  51. package/bld/library/devices/dehumidifier.d.ts +41 -0
  52. package/bld/library/devices/dehumidifier.js +124 -0
  53. package/bld/library/devices/dehumidifier.js.map +1 -0
  54. package/bld/library/devices/fan.d.ts +37 -0
  55. package/bld/library/devices/fan.js +135 -0
  56. package/bld/library/devices/fan.js.map +1 -0
  57. package/bld/library/devices/index.d.ts +9 -0
  58. package/bld/library/devices/index.js +10 -0
  59. package/bld/library/devices/index.js.map +1 -0
  60. package/bld/library/devices/light.d.ts +22 -0
  61. package/bld/library/devices/light.js +112 -0
  62. package/bld/library/devices/light.js.map +1 -0
  63. package/bld/library/devices/pet-feeder.d.ts +36 -0
  64. package/bld/library/devices/pet-feeder.js +116 -0
  65. package/bld/library/devices/pet-feeder.js.map +1 -0
  66. package/bld/library/devices/placeholder.d.ts +3 -0
  67. package/bld/library/devices/placeholder.js +4 -0
  68. package/bld/library/devices/placeholder.js.map +1 -0
  69. package/bld/library/devices/temperature-humidity-sensor.d.ts +14 -0
  70. package/bld/library/devices/temperature-humidity-sensor.js +56 -0
  71. package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
  72. package/bld/library/devices/value-range.d.ts +2 -0
  73. package/bld/library/devices/value-range.js +6 -0
  74. package/bld/library/devices/value-range.js.map +1 -0
  75. package/bld/library/endpoint-connection.d.ts +168 -0
  76. package/bld/library/endpoint-connection.js +510 -0
  77. package/bld/library/endpoint-connection.js.map +1 -0
  78. package/bld/library/index.d.ts +26 -0
  79. package/bld/library/index.js +33 -0
  80. package/bld/library/index.js.map +1 -0
  81. package/bld/library/local/certificate.d.ts +31 -0
  82. package/bld/library/local/certificate.js +298 -0
  83. package/bld/library/local/certificate.js.map +1 -0
  84. package/bld/library/local/controller.d.ts +70 -0
  85. package/bld/library/local/controller.js +498 -0
  86. package/bld/library/local/controller.js.map +1 -0
  87. package/bld/library/local/discovery.d.ts +29 -0
  88. package/bld/library/local/discovery.js +321 -0
  89. package/bld/library/local/discovery.js.map +1 -0
  90. package/bld/library/local/index.d.ts +6 -0
  91. package/bld/library/local/index.js +7 -0
  92. package/bld/library/local/index.js.map +1 -0
  93. package/bld/library/local/message.d.ts +11 -0
  94. package/bld/library/local/message.js +128 -0
  95. package/bld/library/local/message.js.map +1 -0
  96. package/bld/library/local/mqtt.d.ts +113 -0
  97. package/bld/library/local/mqtt.js +1074 -0
  98. package/bld/library/local/mqtt.js.map +1 -0
  99. package/bld/library/local/routed-message-client.d.ts +49 -0
  100. package/bld/library/local/routed-message-client.js +326 -0
  101. package/bld/library/local/routed-message-client.js.map +1 -0
  102. package/bld/library/miot/index.d.ts +4 -0
  103. package/bld/library/miot/index.js +5 -0
  104. package/bld/library/miot/index.js.map +1 -0
  105. package/bld/library/miot/matcher.d.ts +84 -0
  106. package/bld/library/miot/matcher.js +326 -0
  107. package/bld/library/miot/matcher.js.map +1 -0
  108. package/bld/library/miot/request.d.ts +33 -0
  109. package/bld/library/miot/request.js +57 -0
  110. package/bld/library/miot/request.js.map +1 -0
  111. package/bld/library/miot/result.d.ts +8 -0
  112. package/bld/library/miot/result.js +5 -0
  113. package/bld/library/miot/result.js.map +1 -0
  114. package/bld/library/miot/spec.d.ts +96 -0
  115. package/bld/library/miot/spec.js +86 -0
  116. package/bld/library/miot/spec.js.map +1 -0
  117. package/bld/library/provider.d.ts +78 -0
  118. package/bld/library/provider.js +600 -0
  119. package/bld/library/provider.js.map +1 -0
  120. package/bld/library/session-manager.d.ts +34 -0
  121. package/bld/library/session-manager.js +177 -0
  122. package/bld/library/session-manager.js.map +1 -0
  123. package/bld/library/session.d.ts +36 -0
  124. package/bld/library/session.js +370 -0
  125. package/bld/library/session.js.map +1 -0
  126. package/bld/library/storage.d.ts +2 -0
  127. package/bld/library/storage.js +66 -0
  128. package/bld/library/storage.js.map +1 -0
  129. package/bld/library/terminal/bindings.d.ts +3 -0
  130. package/bld/library/terminal/bindings.js +306 -0
  131. package/bld/library/terminal/bindings.js.map +1 -0
  132. package/bld/library/terminal/index.d.ts +2 -0
  133. package/bld/library/terminal/index.js +3 -0
  134. package/bld/library/terminal/index.js.map +1 -0
  135. package/bld/library/terminal/provider-details.d.ts +3 -0
  136. package/bld/library/terminal/provider-details.js +477 -0
  137. package/bld/library/terminal/provider-details.js.map +1 -0
  138. package/package.json +29 -0
  139. package/src/library/backend/client.ts +737 -0
  140. package/src/library/backend/constants.ts +17 -0
  141. package/src/library/backend/index.ts +3 -0
  142. package/src/library/backend/oauth.ts +170 -0
  143. package/src/library/binding.ts +387 -0
  144. package/src/library/cloud/client.ts +155 -0
  145. package/src/library/cloud/constants.ts +19 -0
  146. package/src/library/cloud/device.ts +938 -0
  147. package/src/library/cloud/index.ts +5 -0
  148. package/src/library/cloud/mqtt.ts +671 -0
  149. package/src/library/cloud/transport.ts +46 -0
  150. package/src/library/command.ts +7 -0
  151. package/src/library/configuration.ts +480 -0
  152. package/src/library/device.ts +601 -0
  153. package/src/library/devices/air-conditioner.ts +171 -0
  154. package/src/library/devices/command-effect.ts +425 -0
  155. package/src/library/devices/dehumidifier.ts +131 -0
  156. package/src/library/devices/fan.ts +140 -0
  157. package/src/library/devices/index.ts +9 -0
  158. package/src/library/devices/light.ts +119 -0
  159. package/src/library/devices/pet-feeder.ts +129 -0
  160. package/src/library/devices/placeholder.ts +3 -0
  161. package/src/library/devices/temperature-humidity-sensor.ts +49 -0
  162. package/src/library/devices/value-range.ts +14 -0
  163. package/src/library/endpoint-connection.ts +841 -0
  164. package/src/library/index.ts +71 -0
  165. package/src/library/local/certificate.ts +401 -0
  166. package/src/library/local/controller.ts +693 -0
  167. package/src/library/local/discovery.ts +485 -0
  168. package/src/library/local/index.ts +6 -0
  169. package/src/library/local/message.ts +174 -0
  170. package/src/library/local/mqtt.ts +1555 -0
  171. package/src/library/local/routed-message-client.ts +377 -0
  172. package/src/library/miot/index.ts +4 -0
  173. package/src/library/miot/matcher.ts +683 -0
  174. package/src/library/miot/request.ts +70 -0
  175. package/src/library/miot/result.ts +14 -0
  176. package/src/library/miot/spec.ts +114 -0
  177. package/src/library/provider.ts +745 -0
  178. package/src/library/session-manager.ts +224 -0
  179. package/src/library/session.ts +528 -0
  180. package/src/library/storage.ts +83 -0
  181. package/src/library/terminal/bindings.tsx +692 -0
  182. package/src/library/terminal/index.ts +2 -0
  183. package/src/library/terminal/provider-details.tsx +871 -0
@@ -0,0 +1,528 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {readFile} from 'node:fs/promises';
3
+ import {type Server, createServer} from 'node:http';
4
+
5
+ import * as x from 'x-value';
6
+
7
+ import {
8
+ CLOUD_SERVERS,
9
+ type CloudServer,
10
+ OAUTH_REDIRECT_URL,
11
+ OAuthClient,
12
+ type OAuthToken,
13
+ } from './backend/index.js';
14
+ import {createPrivateJsonFile, writePrivateJsonFile} from './storage.js';
15
+
16
+ const TOKEN_REFRESH_MARGIN = 60_000;
17
+ const OAUTH_CALLBACK_TIMEOUT = 5 * 60_000;
18
+ const OAUTH_SESSION_REFRESH_PROMISE_MAP = new Map<
19
+ string,
20
+ Promise<OAuthSession>
21
+ >();
22
+ const OAUTH_SESSION_LOAD_PROMISE_MAP = new Map<string, Promise<OAuthSession>>();
23
+ const OAUTH_UUID_PROMISE_MAP = new Map<string, Promise<string>>();
24
+
25
+ const OAuthTokenValue = x.object({
26
+ accessToken: x.string,
27
+ refreshToken: x.string,
28
+ expiresIn: x.number,
29
+ macKey: x.string.optional(),
30
+ });
31
+
32
+ const OAuthSessionValue = x.object({
33
+ uuid: x.string,
34
+ cloudServer: x.string,
35
+ redirectUrl: x.string,
36
+ expiresAt: x.string,
37
+ token: OAuthTokenValue,
38
+ });
39
+
40
+ export function loadValidOAuthSession(path: string): Promise<OAuthSession> {
41
+ let promise = OAUTH_SESSION_LOAD_PROMISE_MAP.get(path);
42
+
43
+ if (promise === undefined) {
44
+ promise = loadValidOAuthSessionValue(path);
45
+ OAUTH_SESSION_LOAD_PROMISE_MAP.set(path, promise);
46
+ void promise.then(
47
+ () => {
48
+ if (OAUTH_SESSION_LOAD_PROMISE_MAP.get(path) === promise) {
49
+ OAUTH_SESSION_LOAD_PROMISE_MAP.delete(path);
50
+ }
51
+ },
52
+ () => {
53
+ if (OAUTH_SESSION_LOAD_PROMISE_MAP.get(path) === promise) {
54
+ OAUTH_SESSION_LOAD_PROMISE_MAP.delete(path);
55
+ }
56
+ },
57
+ );
58
+ }
59
+
60
+ return promise;
61
+ }
62
+
63
+ async function loadValidOAuthSessionValue(path: string): Promise<OAuthSession> {
64
+ const session = await readOAuthSession(path);
65
+ const expiresAt = Date.parse(session.expiresAt);
66
+
67
+ if (Number.isNaN(expiresAt)) {
68
+ throw new Error('OAuth session has an invalid expiration time.');
69
+ } else if (expiresAt > Date.now() + TOKEN_REFRESH_MARGIN) {
70
+ return session;
71
+ }
72
+
73
+ return joinOAuthSessionRefresh(path, session);
74
+ }
75
+
76
+ export async function beginOAuthSessionAuthorization(options: {
77
+ readonly sessionPath: string;
78
+ readonly uuidPath: string;
79
+ readonly cloudServer: CloudServer;
80
+ readonly redirectUrl?: string;
81
+ }): Promise<OAuthSessionAuthorization> {
82
+ const {sessionPath, uuidPath, cloudServer} = options;
83
+ const uuid = await loadOrCreateOAuthUuid(uuidPath);
84
+ const redirectUrl = options.redirectUrl ?? getOAuthRedirectUrl(uuid);
85
+ const oauthClient = new OAuthClient(uuid, cloudServer);
86
+ const authorization = oauthClient.createAuthorization(redirectUrl);
87
+ const callback = await startOAuthCallbackListener({
88
+ expectedState: authorization.state,
89
+ redirectUrl,
90
+ });
91
+ const completion = (async () => {
92
+ const code = await callback.wait();
93
+ const token = await oauthClient.exchangeCode(code, redirectUrl);
94
+ const session = createOAuthSession(uuid, cloudServer, redirectUrl, token);
95
+
96
+ await saveOAuthSession(sessionPath, session);
97
+ return session;
98
+ })();
99
+
100
+ void completion.catch(() => undefined);
101
+ return {
102
+ url: authorization.url,
103
+ wait: () => completion,
104
+ cancel: () => callback.close(),
105
+ submitCallbackUrl: callbackUrl => callback.submitCallbackUrl(callbackUrl),
106
+ };
107
+ }
108
+
109
+ export async function saveOAuthSession(
110
+ path: string,
111
+ session: OAuthSession,
112
+ ): Promise<void> {
113
+ await writePrivateJsonFile(path, session);
114
+ }
115
+
116
+ export function createOAuthSession(
117
+ uuid: string,
118
+ cloudServer: CloudServer,
119
+ redirectUrl: string,
120
+ token: OAuthToken,
121
+ ): OAuthSession {
122
+ return {
123
+ uuid: validateUuid(uuid),
124
+ cloudServer,
125
+ redirectUrl,
126
+ expiresAt: new Date(Date.now() + token.expiresIn * 1000).toISOString(),
127
+ token,
128
+ };
129
+ }
130
+
131
+ export type OAuthSessionAuthorization = {
132
+ readonly url: string;
133
+ wait(): Promise<OAuthSession>;
134
+ cancel(): Promise<void>;
135
+ submitCallbackUrl(callbackUrl: string): Promise<void>;
136
+ };
137
+
138
+ export type OAuthSession = {
139
+ readonly uuid: string;
140
+ readonly cloudServer: CloudServer;
141
+ readonly redirectUrl: string;
142
+ readonly expiresAt: string;
143
+ readonly token: OAuthToken;
144
+ };
145
+
146
+ export class OAuthSessionMissingError extends Error {
147
+ constructor() {
148
+ super('OAuth session is missing.');
149
+ }
150
+ }
151
+
152
+ async function readOAuthSession(path: string): Promise<OAuthSession> {
153
+ let source: string;
154
+
155
+ try {
156
+ source = await readFile(path, 'utf8');
157
+ } catch (error) {
158
+ if (isFileNotFoundError(error)) {
159
+ throw new OAuthSessionMissingError();
160
+ }
161
+
162
+ throw error;
163
+ }
164
+
165
+ return parseOAuthSession(JSON.parse(source) as unknown);
166
+ }
167
+
168
+ function parseOAuthSession(value: unknown): OAuthSession {
169
+ const session = OAuthSessionValue.satisfies(value);
170
+ const {cloudServer} = session;
171
+
172
+ if (!isCloudServer(cloudServer)) {
173
+ throw new Error('OAuth session has an invalid cloud server.');
174
+ }
175
+
176
+ return {...session, uuid: validateUuid(session.uuid), cloudServer};
177
+ }
178
+
179
+ function joinOAuthSessionRefresh(
180
+ path: string,
181
+ session: OAuthSession,
182
+ ): Promise<OAuthSession> {
183
+ let refreshPromise = OAUTH_SESSION_REFRESH_PROMISE_MAP.get(path);
184
+
185
+ if (refreshPromise === undefined) {
186
+ const newRefreshPromise = refreshOAuthSession(path, session);
187
+
188
+ refreshPromise = newRefreshPromise;
189
+ OAUTH_SESSION_REFRESH_PROMISE_MAP.set(path, newRefreshPromise);
190
+
191
+ const complete = (): void => {
192
+ if (OAUTH_SESSION_REFRESH_PROMISE_MAP.get(path) === newRefreshPromise) {
193
+ OAUTH_SESSION_REFRESH_PROMISE_MAP.delete(path);
194
+ }
195
+ };
196
+
197
+ void newRefreshPromise.then(complete, complete);
198
+ }
199
+
200
+ return refreshPromise;
201
+ }
202
+
203
+ async function refreshOAuthSession(
204
+ path: string,
205
+ session: OAuthSession,
206
+ ): Promise<OAuthSession> {
207
+ const oauthClient = new OAuthClient(session.uuid, session.cloudServer);
208
+ const token = await oauthClient.refreshToken(
209
+ session.token.refreshToken,
210
+ session.redirectUrl,
211
+ );
212
+
213
+ const refreshedSession = createOAuthSession(
214
+ session.uuid,
215
+ session.cloudServer,
216
+ session.redirectUrl,
217
+ token,
218
+ );
219
+
220
+ await saveOAuthSession(path, refreshedSession);
221
+ return refreshedSession;
222
+ }
223
+
224
+ async function loadOrCreateOAuthUuid(path: string): Promise<string> {
225
+ let uuidPromise = OAUTH_UUID_PROMISE_MAP.get(path);
226
+
227
+ if (uuidPromise === undefined) {
228
+ uuidPromise = loadOrCreateOAuthUuidFromStorage(path);
229
+ OAUTH_UUID_PROMISE_MAP.set(path, uuidPromise);
230
+
231
+ const complete = (): void => {
232
+ if (OAUTH_UUID_PROMISE_MAP.get(path) === uuidPromise) {
233
+ OAUTH_UUID_PROMISE_MAP.delete(path);
234
+ }
235
+ };
236
+
237
+ void uuidPromise.then(complete, complete);
238
+ }
239
+
240
+ return uuidPromise;
241
+ }
242
+
243
+ async function loadOrCreateOAuthUuidFromStorage(path: string): Promise<string> {
244
+ try {
245
+ return await readOAuthUuid(path);
246
+ } catch (error) {
247
+ if (!isFileNotFoundError(error)) {
248
+ throw error;
249
+ }
250
+ }
251
+
252
+ const uuid = randomUUID().replaceAll('-', '');
253
+ const created = await createPrivateJsonFile(path, uuid);
254
+
255
+ return created ? uuid : readOAuthUuid(path);
256
+ }
257
+
258
+ async function readOAuthUuid(path: string): Promise<string> {
259
+ return validateUuid(
260
+ x.string.satisfies(JSON.parse(await readFile(path, 'utf8')) as unknown),
261
+ );
262
+ }
263
+
264
+ function getOAuthRedirectUrl(uuid: string): string {
265
+ // This is called virtual_did by the HA integration. Here it is only used as
266
+ // the provider's stable webhook identifier required by Xiaomi's redirect URL.
267
+ const virtualDid = BigInt(`0x${validateUuid(uuid).slice(0, 16)}`).toString();
268
+
269
+ return `${OAUTH_REDIRECT_URL}/api/webhook/${virtualDid}`;
270
+ }
271
+
272
+ export async function startOAuthCallbackListener(options: {
273
+ readonly expectedState: string;
274
+ readonly redirectUrl: string;
275
+ readonly timeout?: number;
276
+ }): Promise<OAuthCallbackListener> {
277
+ const {expectedState} = options;
278
+ const redirectUrl = new URL(options.redirectUrl);
279
+ const result = createResult<string>();
280
+ let outcome: OAuthCallbackOutcome | undefined;
281
+ let settlementPromise: Promise<void> | undefined;
282
+ const server = createServer((request, response) => {
283
+ if (outcome !== undefined) {
284
+ response.writeHead(409);
285
+ response.end('OAuth callback already received.');
286
+ return;
287
+ }
288
+
289
+ try {
290
+ outcome = readOAuthCallback(
291
+ request.url ?? '/',
292
+ redirectUrl,
293
+ expectedState,
294
+ redirectUrl,
295
+ );
296
+ } catch (error) {
297
+ if (!(error instanceof OAuthCallbackValidationError)) {
298
+ throw error;
299
+ }
300
+
301
+ response.writeHead(error.status);
302
+ response.end(error.responseMessage);
303
+ return;
304
+ }
305
+
306
+ if (outcome.type === 'error') {
307
+ response.writeHead(400);
308
+ response.end('OAuth failed.', closeConnections);
309
+ } else {
310
+ response.writeHead(200, {'content-type': 'text/plain; charset=utf-8'});
311
+ response.end(
312
+ 'OAuth authorization received. You can close this tab.',
313
+ closeConnections,
314
+ );
315
+ }
316
+
317
+ void settle(false);
318
+ });
319
+ const handleError = (error: Error): void => {
320
+ outcome ??= {type: 'error', error};
321
+ void settle(true);
322
+ };
323
+
324
+ await listen(server, getRedirectPort(redirectUrl));
325
+ server.on('error', handleError);
326
+ const timeout = setTimeout(() => {
327
+ outcome ??= {
328
+ type: 'error',
329
+ error: new Error('OAuth callback timed out.'),
330
+ };
331
+ void settle(true);
332
+ }, options.timeout ?? OAUTH_CALLBACK_TIMEOUT);
333
+
334
+ return {
335
+ wait: () => result.promise,
336
+ close: () => {
337
+ outcome ??= {
338
+ type: 'error',
339
+ error: new Error('OAuth callback listener closed.'),
340
+ };
341
+ return settle(outcome.type !== 'code');
342
+ },
343
+ submitCallbackUrl: async callbackUrl => {
344
+ if (outcome !== undefined) {
345
+ throw new Error('OAuth callback already received.');
346
+ }
347
+
348
+ outcome = readOAuthCallback(callbackUrl, redirectUrl, expectedState);
349
+ await settle(false);
350
+ },
351
+ };
352
+
353
+ function settle(force: boolean): Promise<void> {
354
+ if (settlementPromise !== undefined) {
355
+ return settlementPromise;
356
+ }
357
+
358
+ clearTimeout(timeout);
359
+
360
+ server.off('error', handleError);
361
+
362
+ const finalOutcome = outcome;
363
+
364
+ if (finalOutcome === undefined) {
365
+ throw new TypeError('OAuth callback settled without an outcome.');
366
+ }
367
+
368
+ const promise = closeServer(server, force).then(() => {
369
+ if (finalOutcome.type === 'code') {
370
+ result.resolve(finalOutcome.code);
371
+ } else {
372
+ result.reject(finalOutcome.error);
373
+ }
374
+ });
375
+
376
+ settlementPromise = promise;
377
+ return promise;
378
+ }
379
+
380
+ function closeConnections(): void {
381
+ server.closeAllConnections();
382
+ }
383
+ }
384
+
385
+ export type OAuthCallbackListener = {
386
+ wait(): Promise<string>;
387
+ close(): Promise<void>;
388
+ submitCallbackUrl(callbackUrl: string): Promise<void>;
389
+ };
390
+
391
+ type OAuthCallbackOutcome =
392
+ | {readonly type: 'code'; readonly code: string}
393
+ | {readonly type: 'error'; readonly error: unknown};
394
+
395
+ class OAuthCallbackValidationError extends Error {
396
+ constructor(
397
+ message: string,
398
+ readonly status: number,
399
+ readonly responseMessage = message,
400
+ ) {
401
+ super(message);
402
+ }
403
+ }
404
+
405
+ function readOAuthCallback(
406
+ value: string,
407
+ redirectUrl: URL,
408
+ expectedState: string,
409
+ baseUrl?: URL,
410
+ ): OAuthCallbackOutcome {
411
+ let callbackUrl: URL;
412
+
413
+ try {
414
+ callbackUrl =
415
+ baseUrl === undefined ? new URL(value) : new URL(value, baseUrl);
416
+ } catch {
417
+ throw new OAuthCallbackValidationError('Invalid OAuth callback URL.', 400);
418
+ }
419
+
420
+ if (callbackUrl.pathname !== redirectUrl.pathname) {
421
+ throw new OAuthCallbackValidationError(
422
+ 'Invalid OAuth callback path.',
423
+ 404,
424
+ 'Not found.',
425
+ );
426
+ }
427
+
428
+ const state = callbackUrl.searchParams.get('state');
429
+
430
+ if (state !== expectedState) {
431
+ throw new OAuthCallbackValidationError('Invalid OAuth state.', 400);
432
+ }
433
+
434
+ const error = callbackUrl.searchParams.get('error');
435
+
436
+ if (error !== null) {
437
+ return {type: 'error', error: new Error(`OAuth failed: ${error}.`)};
438
+ }
439
+
440
+ const code = callbackUrl.searchParams.get('code');
441
+
442
+ if (code === null || code.trim().length === 0) {
443
+ throw new OAuthCallbackValidationError('Missing OAuth code.', 400);
444
+ }
445
+
446
+ return {type: 'code', code};
447
+ }
448
+
449
+ function createResult<T>(): {
450
+ readonly promise: Promise<T>;
451
+ readonly resolve: (value: T) => void;
452
+ readonly reject: (error: unknown) => void;
453
+ } {
454
+ let resolve: (value: T) => void = () => undefined;
455
+ let reject: (error: unknown) => void = () => undefined;
456
+ const promise = new Promise<T>((resolveValue, rejectValue) => {
457
+ resolve = resolveValue;
458
+ reject = rejectValue;
459
+ });
460
+
461
+ void promise.catch(() => undefined);
462
+ return {promise, resolve, reject};
463
+ }
464
+
465
+ function listen(server: Server, port: number): Promise<void> {
466
+ return new Promise((resolve, reject) => {
467
+ const handleError = (error: Error): void => {
468
+ server.off('listening', handleListening);
469
+ reject(error);
470
+ };
471
+ const handleListening = (): void => {
472
+ server.off('error', handleError);
473
+ resolve();
474
+ };
475
+
476
+ server.once('error', handleError);
477
+ server.once('listening', handleListening);
478
+ server.listen(port);
479
+ });
480
+ }
481
+
482
+ function closeServer(server: Server, force: boolean): Promise<void> {
483
+ if (!server.listening) {
484
+ return Promise.resolve();
485
+ }
486
+
487
+ return new Promise(resolve => {
488
+ server.close(() => {
489
+ resolve();
490
+ });
491
+
492
+ if (force) {
493
+ server.closeAllConnections();
494
+ }
495
+ });
496
+ }
497
+
498
+ function getRedirectPort(url: URL): number {
499
+ if (url.protocol !== 'http:') {
500
+ throw new TypeError('OAuth callback URL must use HTTP.');
501
+ }
502
+
503
+ if (url.port !== '') {
504
+ return Number(url.port);
505
+ }
506
+
507
+ return 80;
508
+ }
509
+
510
+ function validateUuid(uuid: string): string {
511
+ if (!/^[\da-f]{32}$/u.test(uuid)) {
512
+ throw new Error('OAuth environment UUID is invalid.');
513
+ }
514
+
515
+ return uuid;
516
+ }
517
+
518
+ function isCloudServer(value: string): value is CloudServer {
519
+ return (CLOUD_SERVERS as readonly string[]).includes(value);
520
+ }
521
+
522
+ function isFileNotFoundError(error: unknown): boolean {
523
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
524
+ return false;
525
+ }
526
+
527
+ return error.code === 'ENOENT';
528
+ }
@@ -0,0 +1,83 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {chmod, link, mkdir, open, rename, rm} from 'node:fs/promises';
3
+ import {dirname} from 'node:path';
4
+
5
+ export async function writePrivateJsonFile(
6
+ path: string,
7
+ value: unknown,
8
+ ): Promise<void> {
9
+ const directory = dirname(path);
10
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
11
+ const source = serializeJson(value);
12
+
13
+ await preparePrivateDirectory(directory);
14
+
15
+ try {
16
+ await writePrivateFile(temporaryPath, source);
17
+ await rename(temporaryPath, path);
18
+ } finally {
19
+ await rm(temporaryPath, {force: true});
20
+ }
21
+ }
22
+
23
+ export async function createPrivateJsonFile(
24
+ path: string,
25
+ value: unknown,
26
+ ): Promise<boolean> {
27
+ const directory = dirname(path);
28
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
29
+ const source = serializeJson(value);
30
+
31
+ await preparePrivateDirectory(directory);
32
+
33
+ try {
34
+ await writePrivateFile(temporaryPath, source);
35
+
36
+ try {
37
+ await link(temporaryPath, path);
38
+ return true;
39
+ } catch (error) {
40
+ if (isFileExistsError(error)) {
41
+ return false;
42
+ }
43
+
44
+ throw error;
45
+ }
46
+ } finally {
47
+ await rm(temporaryPath, {force: true});
48
+ }
49
+ }
50
+
51
+ function serializeJson(value: unknown): string {
52
+ const source = JSON.stringify(value, undefined, 2);
53
+
54
+ if (source === undefined) {
55
+ throw new TypeError('Private JSON file value is not serializable.');
56
+ }
57
+
58
+ return source;
59
+ }
60
+
61
+ async function preparePrivateDirectory(directory: string): Promise<void> {
62
+ await mkdir(directory, {recursive: true, mode: 0o700});
63
+ await chmod(directory, 0o700);
64
+ }
65
+
66
+ async function writePrivateFile(path: string, source: string): Promise<void> {
67
+ const file = await open(path, 'wx', 0o600);
68
+
69
+ try {
70
+ await file.writeFile(source);
71
+ await file.sync();
72
+ } finally {
73
+ await file.close();
74
+ }
75
+ }
76
+
77
+ function isFileExistsError(error: unknown): boolean {
78
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
79
+ return false;
80
+ }
81
+
82
+ return error.code === 'EEXIST';
83
+ }