oorja 1.11.4 → 2.0.1

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 (52) hide show
  1. package/README.md +14 -52
  2. package/dist/commands/signout.d.ts +1 -1
  3. package/dist/commands/signout.js +4 -4
  4. package/dist/commands/teletype/index.d.ts +7 -6
  5. package/dist/commands/teletype/index.js +49 -47
  6. package/dist/lib/config.d.ts +7 -10
  7. package/dist/lib/config.js +29 -49
  8. package/dist/lib/{surya → connect}/index.d.ts +8 -8
  9. package/dist/lib/{surya → connect}/index.js +39 -36
  10. package/dist/lib/{surya → connect}/resources.js +2 -2
  11. package/dist/lib/{surya → connect}/types.d.ts +1 -3
  12. package/dist/lib/encryption.d.ts +2 -3
  13. package/dist/lib/encryption.js +6 -10
  14. package/dist/lib/oorja/client.d.ts +3 -0
  15. package/dist/lib/oorja/client.js +52 -0
  16. package/dist/lib/oorja/index.d.ts +7 -7
  17. package/dist/lib/oorja/index.js +40 -29
  18. package/dist/lib/oorja/preflight.d.ts +8 -8
  19. package/dist/lib/oorja/preflight.js +45 -41
  20. package/dist/lib/teletype/auxiliary.d.ts +2 -2
  21. package/dist/lib/teletype/auxiliary.js +5 -5
  22. package/dist/lib/teletype/index.d.ts +3 -4
  23. package/dist/lib/teletype/index.js +16 -16
  24. package/dist/lib/utils.js +5 -5
  25. package/oclif.manifest.json +11 -10
  26. package/package.json +22 -18
  27. package/dist/lib/surya/vendor/phoenix/ajax.d.ts +0 -8
  28. package/dist/lib/surya/vendor/phoenix/ajax.js +0 -82
  29. package/dist/lib/surya/vendor/phoenix/channel.d.ts +0 -154
  30. package/dist/lib/surya/vendor/phoenix/channel.js +0 -308
  31. package/dist/lib/surya/vendor/phoenix/constants.d.ts +0 -33
  32. package/dist/lib/surya/vendor/phoenix/constants.js +0 -29
  33. package/dist/lib/surya/vendor/phoenix/index.d.ts +0 -199
  34. package/dist/lib/surya/vendor/phoenix/index.js +0 -200
  35. package/dist/lib/surya/vendor/phoenix/longpoll.d.ts +0 -12
  36. package/dist/lib/surya/vendor/phoenix/longpoll.js +0 -126
  37. package/dist/lib/surya/vendor/phoenix/presence.d.ts +0 -44
  38. package/dist/lib/surya/vendor/phoenix/presence.js +0 -152
  39. package/dist/lib/surya/vendor/phoenix/push.d.ts +0 -57
  40. package/dist/lib/surya/vendor/phoenix/push.js +0 -122
  41. package/dist/lib/surya/vendor/phoenix/serializer.d.ts +0 -53
  42. package/dist/lib/surya/vendor/phoenix/serializer.js +0 -100
  43. package/dist/lib/surya/vendor/phoenix/socket.d.ts +0 -222
  44. package/dist/lib/surya/vendor/phoenix/socket.js +0 -541
  45. package/dist/lib/surya/vendor/phoenix/timer.d.ts +0 -25
  46. package/dist/lib/surya/vendor/phoenix/timer.js +0 -40
  47. package/dist/lib/surya/vendor/phoenix/utils.d.ts +0 -1
  48. package/dist/lib/surya/vendor/phoenix/utils.js +0 -11
  49. /package/dist/lib/{surya → connect}/errors.d.ts +0 -0
  50. /package/dist/lib/{surya → connect}/errors.js +0 -0
  51. /package/dist/lib/{surya → connect}/resources.d.ts +0 -0
  52. /package/dist/lib/{surya → connect}/types.js +0 -0
@@ -1,37 +1,37 @@
1
1
  // backend api client
2
- import https from "https";
3
- import axios, { AxiosError } from "axios";
4
- import { encode, decode } from "@msgpack/msgpack";
5
- import { defaultParser } from "./resources.js";
6
- import { getSuryaConfig } from "../config.js";
7
- import { Unauthorized, BadRequest } from "./errors.js";
8
- import { Socket, Presence } from "./vendor/phoenix/index.js";
9
- import camelcaseKeys from "camelcase-keys";
10
- export class SuryaError extends Error {
2
+ import https from 'https';
3
+ import axios, { AxiosError } from 'axios';
4
+ import { encode, decode } from '@msgpack/msgpack';
5
+ import { defaultParser } from './resources.js';
6
+ import { getConnectConfig } from '../config.js';
7
+ import { Unauthorized, BadRequest } from './errors.js';
8
+ import { Socket, Presence } from 'phoenix';
9
+ import camelcaseKeys from 'camelcase-keys';
10
+ export class ApiClientError extends Error {
11
11
  }
12
- export class SuryaClient {
12
+ export class ConnectClient {
13
13
  config;
14
14
  client;
15
15
  socket;
16
- constructor(env) {
17
- const config = getSuryaConfig(env);
16
+ constructor(env, region) {
17
+ const config = getConnectConfig(env, region);
18
18
  this.client = axios.create({
19
19
  httpsAgent: new https.Agent({
20
- minVersion: "TLSv1.2",
21
- maxVersion: "TLSv1.2",
20
+ minVersion: 'TLSv1.2',
21
+ maxVersion: 'TLSv1.2',
22
22
  }),
23
- baseURL: suryaBaseURL(config.host, config.enableTLS),
23
+ baseURL: connectBaseURL(config.host),
24
24
  timeout: 5000,
25
- responseType: "json",
25
+ responseType: 'json',
26
26
  headers: {
27
- "x-access-token": config.token || "",
27
+ 'x-access-token': config.token || '',
28
28
  },
29
29
  });
30
30
  this.config = config;
31
31
  }
32
32
  fetchCliManifest = async () => {
33
33
  try {
34
- const response = await this.client.get("/cli");
34
+ const response = await this.client.get('/cli');
35
35
  return camelcaseKeys(response.data);
36
36
  }
37
37
  catch (error) {
@@ -40,7 +40,7 @@ export class SuryaClient {
40
40
  };
41
41
  fetchSessionUser = async () => {
42
42
  try {
43
- const response = await this.client.get("/session/user");
43
+ const response = await this.client.get('/session/user');
44
44
  return defaultParser(response.data.data);
45
45
  }
46
46
  catch (error) {
@@ -52,11 +52,11 @@ export class SuryaClient {
52
52
  room: {
53
53
  apps,
54
54
  locked: false,
55
- name: roomName || "-",
55
+ name: roomName || '-',
56
56
  },
57
57
  };
58
58
  try {
59
- const response = await this.client.post("/rooms", body);
59
+ const response = await this.client.post('/rooms', body);
60
60
  return defaultParser(response.data.data);
61
61
  }
62
62
  catch (error) {
@@ -65,7 +65,7 @@ export class SuryaClient {
65
65
  };
66
66
  createAnonymousUser = async () => {
67
67
  try {
68
- const response = await this.client.post("/session/anon");
68
+ const response = await this.client.post('/session/anon');
69
69
  return response.data.access_token;
70
70
  }
71
71
  catch (error) {
@@ -74,7 +74,7 @@ export class SuryaClient {
74
74
  };
75
75
  accessTokenFromRoomParticipantOTP = async (roomId, otp) => {
76
76
  try {
77
- const response = await this.client.post("/access_tokens/from_room_participant_otp", {
77
+ const response = await this.client.post('/access_tokens/from_room_participant_otp', {
78
78
  room_id: roomId,
79
79
  otp: otp,
80
80
  });
@@ -94,7 +94,7 @@ export class SuryaClient {
94
94
  }
95
95
  };
96
96
  establishSocket = async () => {
97
- const protocolPrefix = this.config.enableTLS ? `wss://` : `ws://`;
97
+ const protocolPrefix = `wss://`;
98
98
  const host = this.config.host;
99
99
  let encodeMessage = (rawdata, callback) => {
100
100
  if (!rawdata)
@@ -113,8 +113,9 @@ export class SuryaClient {
113
113
  params: {
114
114
  access_token: this.config.token,
115
115
  },
116
+ transport: WebSocket,
116
117
  heartbeatIntervalMs: 10000,
117
- binaryType: "arraybuffer",
118
+ binaryType: 'arraybuffer',
118
119
  encode: encodeMessage,
119
120
  decode: decodeMessage,
120
121
  });
@@ -127,7 +128,7 @@ export class SuryaClient {
127
128
  reject();
128
129
  return;
129
130
  }
130
- console.error("connection error");
131
+ console.error('connection error');
131
132
  process.exit(2);
132
133
  });
133
134
  // @ts-ignore
@@ -136,33 +137,33 @@ export class SuryaClient {
136
137
  };
137
138
  joinChannel = ({ channel, params, onJoin, onClose, onError, onMessage, handleSessionJoin, handleSessionLeave, }) => {
138
139
  if (!this.socket)
139
- throw Error("no socket connection");
140
+ throw Error('no socket connection');
140
141
  const chan = this.socket.channel(channel, params);
141
142
  if (onError)
142
143
  chan.onError(onError);
143
144
  if (onClose)
144
145
  chan.onClose(onClose);
145
146
  let presences = [];
146
- chan.on("new_msg", (msg) => {
147
+ chan.on('new_msg', (msg) => {
147
148
  onMessage(msg);
148
149
  });
149
- chan.on("presence_state", (response) => {
150
+ chan.on('presence_state', (response) => {
150
151
  Presence.syncState(presences, response, handleSessionJoin, undefined);
151
152
  presences = response;
152
153
  });
153
- chan.on("presence_diff", (newPresence) => {
154
+ chan.on('presence_diff', (newPresence) => {
154
155
  presences = Presence.syncDiff(presences, newPresence, handleSessionJoin, handleSessionLeave);
155
156
  });
156
157
  chan
157
158
  .join()
158
- .receive("ok", () => {
159
+ .receive('ok', () => {
159
160
  if (onJoin)
160
161
  onJoin();
161
162
  })
162
- .receive("error", (resp) => {
163
- if (resp && resp.reason === "unauthorized") {
163
+ .receive('error', (resp) => {
164
+ if (resp && resp.reason === 'unauthorized') {
164
165
  if (onError)
165
- onError(new Unauthorized("unauthorized: user needs to join the room before a stream can be started."));
166
+ onError(new Unauthorized('unauthorized: user needs to join the room before a stream can be started.'));
166
167
  return;
167
168
  }
168
169
  process.exit(3);
@@ -172,7 +173,9 @@ export class SuryaClient {
172
173
  destroy = async () => {
173
174
  return new Promise((resolve) => {
174
175
  if (this.socket) {
175
- this.socket.disconnect(resolve, 1000, "disconnecting surya client");
176
+ this.socket.disconnect(() => {
177
+ resolve(undefined);
178
+ }, 1000, 'disconnecting connect client');
176
179
  }
177
180
  else {
178
181
  resolve(undefined);
@@ -180,7 +183,7 @@ export class SuryaClient {
180
183
  });
181
184
  };
182
185
  }
183
- const suryaBaseURL = (host, tlsEnabled) => `${tlsEnabled ? "https" : "http"}://${host}/api/v1`;
186
+ const connectBaseURL = (host) => `https://${host}/api/v1`;
184
187
  const handleError = (error) => {
185
188
  if (error instanceof AxiosError) {
186
189
  const { response } = error;
@@ -1,5 +1,5 @@
1
- import camelcaseKeys from "camelcase-keys";
2
- const parseDateFields = (resource, fields = ["createdAt", "updatedAt"]) => {
1
+ import camelcaseKeys from 'camelcase-keys';
2
+ const parseDateFields = (resource, fields = ['createdAt', 'updatedAt']) => {
3
3
  fields.forEach((key) => {
4
4
  const val = resource[key];
5
5
  if (val)
@@ -1,5 +1,4 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- type ProfileType = "GitHub" | "Google" | "anon";
1
+ type ProfileType = 'GitHub' | 'Google' | 'anon';
3
2
  export type RoomApp = {
4
3
  appId: string;
5
4
  config: any;
@@ -21,7 +20,6 @@ type ResourceTimestamps = {
21
20
  };
22
21
  export type CliManifest = {
23
22
  cliVersion: number;
24
- suryaHosts: string[];
25
23
  };
26
24
  export type User = UserProfile & ResourceTimestamps;
27
25
  export type Room = {
@@ -1,11 +1,10 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import { RoomKey } from "./surya/types.js";
1
+ import { RoomKey } from './connect/types.js';
3
2
  export type EncryptedPayload = {
4
3
  iv: Buffer | Uint8Array;
5
4
  data: Buffer | Uint8Array;
6
5
  };
7
6
  export declare const createRoomKey: (roomId: string) => RoomKey;
8
7
  export declare const exportKey: (key: Buffer) => string;
9
- export declare const importKey: (exportedKey: string) => Buffer;
8
+ export declare const importKey: (exportedKey: string) => Buffer<ArrayBuffer>;
10
9
  export declare const encrypt: (data: any, roomKey: RoomKey) => EncryptedPayload;
11
10
  export declare const decrypt: (payload: EncryptedPayload, roomKey: RoomKey) => any;
@@ -1,6 +1,6 @@
1
- import * as crypto from "crypto";
2
- import { encode, decode } from "@msgpack/msgpack";
3
- const ALG = "aes-128-gcm";
1
+ import * as crypto from 'crypto';
2
+ import { encode, decode } from '@msgpack/msgpack';
3
+ const ALG = 'aes-128-gcm';
4
4
  const KEY_SIZE = 16; // 128 bit AES
5
5
  const AUTH_TAG_LEN = 16;
6
6
  export const createRoomKey = (roomId) => ({
@@ -8,19 +8,15 @@ export const createRoomKey = (roomId) => ({
8
8
  key: createAESEncryptionKey(),
9
9
  });
10
10
  const createAESEncryptionKey = () => crypto.randomBytes(KEY_SIZE);
11
- export const exportKey = (key) => key.toString("base64");
12
- export const importKey = (exportedKey) => Buffer.from(exportedKey, "base64");
11
+ export const exportKey = (key) => key.toString('base64');
12
+ export const importKey = (exportedKey) => Buffer.from(exportedKey, 'base64');
13
13
  const createIV = () => crypto.randomBytes(16);
14
14
  export const encrypt = (data, roomKey) => {
15
15
  const iv = createIV();
16
16
  const cipher = crypto.createCipheriv(ALG, roomKey.key, iv);
17
17
  return {
18
18
  iv,
19
- data: Buffer.concat([
20
- cipher.update(encode(data)),
21
- cipher.final(),
22
- cipher.getAuthTag(),
23
- ]),
19
+ data: Buffer.concat([cipher.update(encode(data)), cipher.final(), cipher.getAuthTag()]),
24
20
  };
25
21
  };
26
22
  export const decrypt = (payload, roomKey) => {
@@ -0,0 +1,3 @@
1
+ export declare class OorjaClientError extends Error {
2
+ }
3
+ export declare const getRegion: () => Promise<string>;
@@ -0,0 +1,52 @@
1
+ import haversine from 'haversine-distance';
2
+ export class OorjaClientError extends Error {
3
+ }
4
+ const _maybeError = (response) => {
5
+ const { status } = response;
6
+ if (status >= 400) {
7
+ throw new OorjaClientError('oorja network client error');
8
+ }
9
+ };
10
+ class Client {
11
+ async get(url, options = {}) {
12
+ const response = await fetch(url, {
13
+ ...options,
14
+ method: options.method || 'GET',
15
+ headers: { ...options.headers },
16
+ cache: 'no-store',
17
+ redirect: 'follow',
18
+ signal: AbortSignal.timeout(options.timeout || 6_000),
19
+ });
20
+ _maybeError(response);
21
+ return response;
22
+ }
23
+ }
24
+ const _client = new Client();
25
+ export const getRegion = async () => {
26
+ const response = await _client.get('https://oorja.io/nudge', {
27
+ method: 'GET',
28
+ });
29
+ if (response.status !== 200) {
30
+ console.error('There seems to be an issue with the network');
31
+ process.exit(1);
32
+ }
33
+ const settings = (await response.json());
34
+ try {
35
+ const clientLocation = {
36
+ lat: parseFloat(response.headers.get('oorja-lat')),
37
+ lng: parseFloat(response.headers.get('oorja-lon')),
38
+ };
39
+ const distances = settings.regions.map((region) => {
40
+ return {
41
+ name: region.name,
42
+ distance: haversine(clientLocation, region.location),
43
+ };
44
+ });
45
+ const minDistance = distances.reduce((a, b) => (a.distance < b.distance ? a : b));
46
+ return minDistance.name;
47
+ }
48
+ catch {
49
+ console.error('error determining region');
50
+ process.exit(1);
51
+ }
52
+ };
@@ -1,16 +1,16 @@
1
- import { oorjaConfig } from "../config.js";
2
- import { User, RoomKey } from "../surya/types.js";
3
- import { TeletypeOptions } from "../teletype/index.js";
4
- import { CreateRoomOptions, SuryaClient } from "../surya/index.js";
1
+ import { oorjaConfig } from '../config.js';
2
+ import { User, RoomKey } from '../connect/types.js';
3
+ import { TeletypeOptions } from '../teletype/index.js';
4
+ import { CreateRoomOptions, ConnectClient } from '../connect/index.js';
5
5
  export declare class InvalidRoomLink extends Error {
6
6
  }
7
7
  declare class OORJA {
8
8
  private config;
9
- private suryaClient;
9
+ private connectClient;
10
10
  user: User;
11
- constructor(config: oorjaConfig, suryaClient: SuryaClient, user: User);
11
+ constructor(config: oorjaConfig, connectClient: ConnectClient, user: User);
12
12
  createRoom: (options: CreateRoomOptions) => Promise<{
13
- room: import("../surya/types.js").Room;
13
+ room: import("../connect/types.js").Room;
14
14
  roomKey: RoomKey;
15
15
  }>;
16
16
  linkForRoom: (roomKey: RoomKey) => string;
@@ -1,23 +1,25 @@
1
- import { determineENV, getoorjaConfig, INVALID_ROOM_LINK_MESSAGE, setENVAccessToken, } from "../config.js";
2
- import { teletypeApp } from "../teletype/index.js";
3
- import { SuryaClient } from "../surya/index.js";
4
- import { URL, URLSearchParams } from "url";
5
- import { importKey, createRoomKey, exportKey } from "../encryption.js";
6
- import { loginByRoomOTP, preflight, promptAuth, resumeSession, validateCliVersion, } from "./preflight.js";
1
+ import { determineENV, getoorjaConfig, INVALID_ROOM_LINK_MESSAGE, setENVAccessToken, } from '../config.js';
2
+ import { teletypeApp } from '../teletype/index.js';
3
+ import { ConnectClient } from '../connect/index.js';
4
+ import { URL, URLSearchParams } from 'url';
5
+ import { importKey, createRoomKey, exportKey } from '../encryption.js';
6
+ import { loginByRoomOTP, preflight, promptAuth, resumeSession, validateCliVersion } from './preflight.js';
7
+ import { getRegion } from './client.js';
8
+ import ora from 'ora';
7
9
  export class InvalidRoomLink extends Error {
8
10
  }
9
11
  class OORJA {
10
12
  config;
11
- suryaClient;
13
+ connectClient;
12
14
  user;
13
15
  // should capture domain related commands and queries
14
- constructor(config, suryaClient, user) {
16
+ constructor(config, connectClient, user) {
15
17
  this.config = config;
16
- this.suryaClient = suryaClient;
18
+ this.connectClient = connectClient;
17
19
  this.user = user;
18
20
  }
19
21
  createRoom = async (options) => {
20
- const room = await this.suryaClient.createRoom(options);
22
+ const room = await this.connectClient.createRoom(options);
21
23
  const roomKey = createRoomKey(room.id);
22
24
  return {
23
25
  room,
@@ -37,7 +39,7 @@ class OORJA {
37
39
  teletype = (options) => {
38
40
  return teletypeApp({
39
41
  userId: this.user.id,
40
- joinChannel: this.suryaClient.joinChannel,
42
+ joinChannel: this.connectClient.joinChannel,
41
43
  ...options,
42
44
  });
43
45
  };
@@ -52,48 +54,57 @@ const parseRoomURL = (roomLink) => {
52
54
  };
53
55
  const getRoomId = (roomURL) => {
54
56
  const params = new URLSearchParams(roomURL.search);
55
- return params.get("id") || undefined;
57
+ return params.get('id') || undefined;
56
58
  };
57
59
  const oorjaURL = (config) => {
58
- const { host, enableTLS } = config;
59
- return enableTLS ? `https://${host}` : `http://${host}`;
60
+ const { host } = config;
61
+ return `https://${host}`;
60
62
  };
61
63
  const linkForTokenGen = (config) => `${oorjaURL(config)}/access_token`;
62
64
  const init = async (env, options = {}) => {
63
65
  const config = getoorjaConfig(env);
64
- let suryaClient = new SuryaClient(env);
65
- await validateCliVersion(suryaClient);
66
- let user = await resumeSession(env, suryaClient, options.roomId);
66
+ const spinner = ora({
67
+ text: 'Connecting...',
68
+ discardStdin: true,
69
+ }).start();
70
+ const region = await getRegion();
71
+ let connectClient = new ConnectClient(env, region);
72
+ await validateCliVersion(connectClient);
73
+ let user = await resumeSession(env, connectClient, options.roomId);
74
+ spinner.succeed('Online');
67
75
  if (!user) {
68
- let token = "";
76
+ let token = '';
69
77
  if (options.roomId) {
70
- token = await loginByRoomOTP(suryaClient, options.roomId);
78
+ token = await loginByRoomOTP(connectClient, options.roomId);
71
79
  }
72
80
  else {
73
- token = await promptAuth(suryaClient, linkForTokenGen(config));
81
+ token = await promptAuth(connectClient, linkForTokenGen(config));
74
82
  if (!token) {
75
- console.log("Token not provided :(");
83
+ console.log('Token not provided :(');
76
84
  process.exit(12);
77
85
  }
78
86
  }
79
87
  setENVAccessToken(env, token);
80
88
  }
81
- await suryaClient.destroy();
82
- suryaClient = new SuryaClient(env);
83
- user = await preflight(env, suryaClient);
84
- return new OORJA(config, suryaClient, user);
89
+ await connectClient.destroy();
90
+ connectClient = new ConnectClient(env, region);
91
+ user = await preflight(env, connectClient);
92
+ return new OORJA(config, connectClient, user);
85
93
  };
86
94
  let currentEnv;
87
- let oorja;
95
+ let oorja = null;
88
96
  export const getApp = async (options = {}) => {
89
97
  const { roomLink } = options;
90
98
  const roomURL = roomLink ? parseRoomURL(roomLink) : undefined;
91
- const env = determineENV(undefined);
99
+ const env = determineENV(roomURL);
92
100
  if (oorja) {
93
101
  if (env !== currentEnv) {
94
- return Promise.reject("Attempt to run different env in same session");
102
+ return Promise.reject('Attempt to run different env in same session');
95
103
  }
96
104
  return Promise.resolve(oorja);
97
105
  }
98
- return await init(env, { roomId: roomURL ? getRoomId(roomURL) : undefined });
106
+ const app = await init(env, { roomId: roomURL ? getRoomId(roomURL) : undefined });
107
+ currentEnv = env;
108
+ oorja = app;
109
+ return app;
99
110
  };
@@ -1,9 +1,9 @@
1
- import { env } from "../config.js";
2
- import { SuryaClient } from "../surya/index.js";
3
- import { User } from "../surya/types.js";
1
+ import { env } from '../config.js';
2
+ import { ConnectClient } from '../connect/index.js';
3
+ import { User } from '../connect/types.js';
4
4
  export declare const promptRoomParticipantOTP: () => Promise<string>;
5
- export declare const promptAuth: (suryaClient: SuryaClient, generateTokenLink: string) => Promise<string>;
6
- export declare const loginByRoomOTP: (suryaClient: SuryaClient, roomId: string) => Promise<string>;
7
- export declare const validateCliVersion: (suryaClient: SuryaClient) => Promise<void>;
8
- export declare const resumeSession: (env: env, suryaClient: SuryaClient, roomId?: string) => Promise<User | null>;
9
- export declare const preflight: (env: env, suryaClient: SuryaClient) => Promise<User>;
5
+ export declare const promptAuth: (connectClient: ConnectClient, generateTokenLink: string) => Promise<string>;
6
+ export declare const loginByRoomOTP: (connectClient: ConnectClient, roomId: string) => Promise<string>;
7
+ export declare const validateCliVersion: (connectClient: ConnectClient) => Promise<void>;
8
+ export declare const resumeSession: (env: env, connectClient: ConnectClient, roomId?: string) => Promise<User | null>;
9
+ export declare const preflight: (env: env, connectClient: ConnectClient) => Promise<User>;
@@ -1,124 +1,128 @@
1
- import chalk from "chalk";
1
+ import chalk from 'chalk';
2
2
  import inquirer from 'inquirer';
3
- import ora from "ora";
4
- import { setENVAccessToken, CLI_VERSION, getENVAccessToken, } from "../config.js";
5
- import { BadRequest, Unauthorized } from "../surya/errors.js";
6
- const promptToken = () => inquirer.prompt([
3
+ import ora from 'ora';
4
+ import { setENVAccessToken, CLI_VERSION, getENVAccessToken } from '../config.js';
5
+ import { BadRequest, Unauthorized } from '../connect/errors.js';
6
+ const promptToken = () => inquirer
7
+ .prompt([
7
8
  {
8
9
  type: 'input',
9
10
  name: 'accessToken',
10
11
  message: 'Please enter your access token for authentication:',
11
- }
12
- ]).then(answers => answers.accessToken);
13
- export const promptRoomParticipantOTP = () => inquirer.prompt([
12
+ },
13
+ ])
14
+ .then((answers) => answers.accessToken);
15
+ export const promptRoomParticipantOTP = () => inquirer
16
+ .prompt([
14
17
  {
15
18
  type: 'input',
16
19
  name: 'otp',
17
20
  message: 'Please enter your OTP for authentication (switch to teletype app in the room and click on blue "Generate OTP" button):',
18
- }
19
- ]).then(answers => answers.otp);
21
+ },
22
+ ])
23
+ .then((answers) => answers.otp);
20
24
  const OTP_HELP_MESSAGE = "You can generate OTP from the room, it's in the instruction steps";
21
- export const promptAuth = async (suryaClient, generateTokenLink) => {
22
- const ANON = "Proceed as an anonymous user";
23
- const SIGN_IN = "Sign-in with oorja";
24
- console.log(`\n${chalk.bold("PRO-TIP:")} If you sign-in, you can control your shell from the web-ui as well, without enabling collaboration mode for the other participants\n`);
25
+ export const promptAuth = async (connectClient, generateTokenLink) => {
26
+ const ANON = 'Proceed as an anonymous user';
27
+ const SIGN_IN = 'Sign-in with oorja';
28
+ console.log(`\n${chalk.bold('PRO-TIP:')} If you sign-in, you can control your shell from the web-ui as well, without enabling collaboration mode for the other participants\n`);
25
29
  const { answer } = await inquirer.prompt([
26
30
  {
27
31
  type: 'list',
28
32
  name: 'answer',
29
33
  message: 'You need an access-token for authentication.\n ',
30
34
  choices: [ANON, SIGN_IN],
31
- }
35
+ },
32
36
  ]);
33
37
  switch (answer) {
34
38
  case ANON:
35
- console.log("Creating anonymous user...");
36
- return suryaClient.createAnonymousUser();
39
+ console.log('Creating anonymous user...');
40
+ return connectClient.createAnonymousUser();
37
41
  case SIGN_IN:
38
42
  console.log(`You can sign-in and generate your token here: ${chalk.blue(generateTokenLink)}`);
39
43
  return promptToken();
40
44
  }
41
- throw Error("Unexpected input");
45
+ throw Error('Unexpected input');
42
46
  };
43
- export const loginByRoomOTP = async (suryaClient, roomId) => {
47
+ export const loginByRoomOTP = async (connectClient, roomId) => {
44
48
  const otp = await promptRoomParticipantOTP();
45
49
  if (!otp) {
46
- console.log("OTP not provided :(");
50
+ console.log('OTP not provided :(');
47
51
  console.log(OTP_HELP_MESSAGE);
48
52
  process.exit(213);
49
53
  }
50
54
  try {
51
- return await suryaClient.accessTokenFromRoomParticipantOTP(roomId, otp);
55
+ return await connectClient.accessTokenFromRoomParticipantOTP(roomId, otp);
52
56
  }
53
57
  catch (e) {
54
58
  if (e instanceof BadRequest) {
55
- console.log(chalk.redBright("Invalid otp. It may have expired."));
59
+ console.log(chalk.redBright('Invalid otp. It may have expired.'));
56
60
  console.log(OTP_HELP_MESSAGE);
57
61
  process.exit();
58
62
  }
59
63
  throw e;
60
64
  }
61
65
  };
62
- export const validateCliVersion = async (suryaClient) => {
63
- const manifest = await suryaClient.fetchCliManifest();
66
+ export const validateCliVersion = async (connectClient) => {
67
+ const manifest = await connectClient.fetchCliManifest();
64
68
  if (manifest.cliVersion > CLI_VERSION) {
65
- console.log(chalk.redBright("Your oorja cli is outdated. Please run: npm update -g oorja"));
69
+ console.log(chalk.redBright('Your oorja cli is outdated. Please run: npm update -g oorja'));
66
70
  process.exit(1);
67
71
  }
68
72
  };
69
- export const resumeSession = async (env, suryaClient, roomId) => {
73
+ export const resumeSession = async (env, connectClient, roomId) => {
70
74
  const token = getENVAccessToken(env);
71
75
  if (!token)
72
76
  return null;
73
77
  // try to validate authorization with existing token
74
78
  try {
75
- const user = await suryaClient.fetchSessionUser();
79
+ const user = await connectClient.fetchSessionUser();
76
80
  if (roomId) {
77
- await suryaClient.fetchRoom(roomId);
81
+ await connectClient.fetchRoom(roomId);
78
82
  }
79
83
  return user;
80
84
  }
81
85
  catch (e) {
82
86
  if (e instanceof Unauthorized) {
83
- setENVAccessToken(env, "");
87
+ setENVAccessToken(env, '');
84
88
  return null;
85
89
  }
86
90
  throw e;
87
91
  }
88
92
  };
89
- export const preflight = async (env, suryaClient) => {
93
+ export const preflight = async (env, connectClient) => {
90
94
  const spinner = ora({
91
- text: "Authenticating",
95
+ text: 'Authenticating',
92
96
  discardStdin: false,
93
97
  }).start();
94
98
  try {
95
- const user = await suryaClient.fetchSessionUser();
99
+ const user = await connectClient.fetchSessionUser();
96
100
  spinner.succeed(`Authenticated: Welcome ${user.name}`);
97
- if (user.profileType === "anon") {
101
+ if (user.profileType === 'anon') {
98
102
  // don't persist tokens for anonymous users
99
- setENVAccessToken(env, "");
103
+ setENVAccessToken(env, '');
100
104
  console.log(chalk.yellowBright("You're an anonymous user. CLI will not remember the auth-token"));
101
105
  }
102
- spinner.start("Connecting..");
103
- return suryaClient
106
+ spinner.start('Connecting..');
107
+ return connectClient
104
108
  .establishSocket()
105
109
  .then(() => {
106
- spinner.succeed("Connected").clear();
110
+ spinner.succeed('Connected').clear();
107
111
  return user;
108
112
  })
109
113
  .catch((e) => {
110
- spinner.fail("Socket connection failure..");
114
+ spinner.fail('Socket connection failure..');
111
115
  throw e;
112
116
  });
113
117
  }
114
118
  catch (e) {
115
- setENVAccessToken(env, "");
119
+ setENVAccessToken(env, '');
116
120
  if (e instanceof Unauthorized) {
117
- spinner.fail("Your access token failed authentication, resetting...");
121
+ spinner.fail('Your access token failed authentication, resetting...');
118
122
  process.exit(33);
119
123
  }
120
124
  else {
121
- spinner.fail("Something went wrong :(");
125
+ spinner.fail('Something went wrong :(');
122
126
  }
123
127
  throw e;
124
128
  }