-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathutils.ts
More file actions
1934 lines (1658 loc) · 60.5 KB
/
utils.ts
File metadata and controls
1934 lines (1658 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright © 2024 Hardcore Engineering Inc.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import {
AccountRole,
type AccountUuid,
type Branding,
concatLink,
generateId,
groupByArray,
isActiveMode,
type MeasureContext,
type Person,
type PersonId,
type PersonUuid,
readOnlyGuestAccountUuid,
roleOrder,
SocialIdType,
type SocialKey,
systemAccountUuid,
type WorkspaceDataId,
type WorkspaceInfoWithStatus as WorkspaceInfoWithStatusCore,
type WorkspaceMode,
type WorkspaceUuid
} from '@hcengineering/core'
import { getMongoClient } from '@hcengineering/mongo' // TODO: get rid of this import later
import platform, { getMetadata, PlatformError, Severity, Status, translate } from '@hcengineering/platform'
import { getDBClient, setDBExtraOptions } from '@hcengineering/postgres'
import { pbkdf2Sync, randomBytes } from 'crypto'
import otpGenerator from 'otp-generator'
import { Analytics } from '@hcengineering/analytics'
import { decodeTokenVerbose, generateToken, type PermissionsGrant, TokenError } from '@hcengineering/server-token'
import { MongoAccountDB } from './collections/mongo'
import { PostgresAccountDB } from './collections/postgres/postgres'
import { accountPlugin } from './plugin'
import {
type Account,
type AccountDB,
AccountEventType,
type AccountMethodHandler,
type Integration,
type LoginInfo,
type LoginInfoRequestData,
type Meta,
type Operations,
type OtpInfo,
type RegionInfo,
type SocialId,
type Workspace,
type WorkspaceInfoWithStatus,
type WorkspaceInvite,
type WorkspaceJoinInfo,
type WorkspaceLoginInfo,
type WorkspaceStatus
} from './types'
import { isAdminEmail } from './admin'
export const GUEST_ACCOUNT = 'b6996120-416f-49cd-841e-e4a5d2e49c9b' as PersonUuid
export async function getAccountDB (
uri: string,
dbNs?: string,
appName: string = 'account'
): Promise<[AccountDB, () => void]> {
const isMongo = uri.startsWith('mongodb://')
if (isMongo) {
const client = getMongoClient(uri)
const db = (await client.getClient()).db(dbNs ?? 'global-account')
const mongoAccount = new MongoAccountDB(db)
await mongoAccount.init()
return [
mongoAccount,
() => {
client.close()
}
]
} else {
setDBExtraOptions({
connection: {
application_name: appName
}
})
const client = getDBClient(uri)
const pgClient = await client.getClient()
const pgAccount = new PostgresAccountDB(pgClient, dbNs ?? 'global_account')
let error = false
do {
try {
await pgAccount.init()
error = false
} catch (e) {
console.error('Error while initializing postgres account db', e)
error = true
await new Promise((resolve) => setTimeout(resolve, 1000))
}
} while (error)
return [
pgAccount,
() => {
client.close()
}
]
}
}
export const assignableRoles = [AccountRole.Guest, AccountRole.User, AccountRole.Maintainer, AccountRole.Owner]
export function getRolePower (role: AccountRole): number {
return roleOrder[role]
}
export function isReadOnlyOrGuest (account: AccountUuid, extra: Record<string, any> | undefined): boolean {
return isGuest(account, extra) || extra?.readonly === 'true'
}
export function isGuest (account: AccountUuid, extra: Record<string, any> | undefined): boolean {
return account === GUEST_ACCOUNT && extra?.guest === 'true'
}
export function wrap (
accountMethod: (ctx: MeasureContext, db: AccountDB, branding: Branding | null, ...args: any[]) => Promise<any>
): AccountMethodHandler {
return async function (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
request: any,
token?: string,
meta?: Meta
): Promise<any> {
return await accountMethod(ctx, db, branding, token, { ...request.params }, meta)
.then((result) => ({ id: request.id, result }))
.catch((err: Error) => {
const status =
err instanceof PlatformError
? err.status
: new Status(Severity.ERROR, platform.status.InternalServerError, {})
if (err instanceof TokenError) {
// Let's send un authorized
return {
error: new Status(Severity.ERROR, platform.status.Unauthorized, {})
}
}
if (status.code === platform.status.InternalServerError) {
Analytics.handleError(err)
ctx.error('Error while processing account method', {
method: accountMethod.name,
status,
origErr: err
})
} else {
ctx.error('Error while processing account method', { method: accountMethod.name, status })
}
return {
error: status
}
})
}
}
/**
* Returns a hash code for a string.
* (Compatible to Java's String.hashCode())
*
* The hash code for a string object is computed as
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* using number arithmetic, where s[i] is the i th character
* of the given string, n is the length of the string,
* and ^ indicates exponentiation.
* (The hash value of the empty string is zero.)
*
*/
function hashWorkspace (dbWorkspaceName: string): number {
return [...dbWorkspaceName].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0)
}
export enum EndpointKind {
Internal,
External
}
const toTransactor = (line: string): EndpointInfo => {
const [internalUrl, externalUrl, region] = line
.split(';')
.map((it) => it.trim())
.map((it) => (it.length === 0 ? undefined : it))
return { internalUrl: internalUrl ?? '', region: region ?? '', externalUrl: externalUrl ?? internalUrl ?? '' }
}
/**
* Internal. Exported for testing only.
* @returns list of endpoints
*/
export const getEndpoints = (): string[] => {
const transactorsUrl = getMetadata(accountPlugin.metadata.Transactors)
if (transactorsUrl === undefined) {
throw new Error('Please provide transactor endpoint url')
}
const endpoints = transactorsUrl
.split(',')
.map((it) => it.trim())
.filter((it) => it.length > 0)
if (endpoints.length === 0) {
throw new Error('Please provide transactor endpoint url')
}
return endpoints
}
// Info is static, so no need to calculate it every time.
let regionInfo: RegionInfo[] = []
export const getRegions = (): RegionInfo[] => {
if (regionInfo.length === 0) {
regionInfo = _getRegions()
}
return regionInfo
}
/**
* Internal. Exported for tests only.
* @returns list of endpoints
*/
export const _getRegions = (): RegionInfo[] => {
let _regionInfo: RegionInfo[] = []
const endpoints = getEndpoints()
.map(toTransactor)
.map((it) => ({ region: it.region.trim(), name: '' }))
if (process.env.REGION_INFO !== undefined) {
_regionInfo = process.env.REGION_INFO.split(';')
.map((it) => it.split('|'))
.map((it) => ({ region: it[0].trim(), name: it[1].trim() }))
// We need to add all endpoints if they are not in info.
for (const endpoint of endpoints) {
if (_regionInfo.find((it) => it.region === endpoint.region) === undefined) {
_regionInfo.push(endpoint)
}
}
} else {
_regionInfo = endpoints
}
return _regionInfo
}
export interface EndpointInfo {
internalUrl: string
externalUrl: string
region: string
}
export function getEndpointInfo (): Map<string, EndpointInfo[]> {
return groupByArray(getEndpoints().map(toTransactor), (it) => it.region)
}
export const selectKind = (kind: EndpointKind, it: EndpointInfo): string => {
return kind === EndpointKind.Internal ? it.internalUrl : it.externalUrl
}
export const getEndpoint = (workspace: WorkspaceUuid, region: string | undefined, kind: EndpointKind): string => {
const hash = hashWorkspace(workspace)
const _endpointInfo = getEndpointInfo()
let transactors = _endpointInfo.get(region ?? '') ?? []
if (transactors.length === 0) {
console.warn('No transactors for the target region, will use default region', { group: region })
transactors = _endpointInfo.get('') ?? []
}
if (transactors.length === 0) {
throw new Error('Please provide transactor endpoint url')
}
return selectKind(kind, transactors[Math.abs(hash % transactors.length)])
}
export const getWorkspaceEndpoint = (
info: Map<string, EndpointInfo[]>,
workspace: WorkspaceUuid,
region: string | undefined
): EndpointInfo => {
const hash = hashWorkspace(workspace)
const byRegion = info.get(region ?? '') ?? []
return byRegion[Math.abs(hash % byRegion.length)]
}
export function getAllTransactors (kind: EndpointKind): string[] {
const transactorsUrl = getMetadata(accountPlugin.metadata.Transactors)
if (transactorsUrl === undefined) {
throw new Error('Please provide transactor endpoint url')
}
const endpoints = transactorsUrl
.split(',')
.map((it) => it.trim())
.filter((it) => it.length > 0)
if (endpoints.length === 0) {
throw new Error('Please provide transactor endpoint url')
}
const toTransactor = (line: string): { internalUrl: string, group: string, externalUrl: string } => {
const [internalUrl, externalUrl, group] = line.split(';')
return { internalUrl, group: group ?? '', externalUrl: externalUrl ?? internalUrl }
}
return endpoints.map(toTransactor).map((it) => (kind === EndpointKind.External ? it.externalUrl : it.internalUrl))
}
export function hashWithSalt (password: string, salt: Buffer): Buffer {
// remove "as any" when types in node will be fixed
return pbkdf2Sync(password, salt as any, 1000, 32, 'sha256')
}
export function verifyPassword (password: string, hash?: Buffer | null, salt?: Buffer | null): boolean {
if (hash == null || salt == null) {
return false
}
// remove "as any" when types in node will be fixed
return Buffer.compare(hash as any, hashWithSalt(password, salt) as any) === 0
}
export function cleanEmail (email: string): string {
return email.toLowerCase().trim()
}
export function normalizeValue (value: string): string {
return value.toLowerCase().trim()
}
export function isEmail (email: string): boolean {
// RFC 5322 compliant email regex
const EMAIL_REGEX =
/^[a-zA-Z0-9](?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-](?:\.?[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-])*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/ // eslint-disable-line no-control-regex
return EMAIL_REGEX.test(email)
}
export function isShallowEqual (obj1: Record<string, any>, obj2: Record<string, any>): boolean {
const keys1 = Object.keys(obj1)
const keys2 = Object.keys(obj2)
return keys1.length === keys2.length && keys1.every((k) => obj1[k] === obj2[k])
}
export async function setPassword (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
personUuid: AccountUuid,
password: string
): Promise<void> {
if (password == null || password === '') {
return
}
const salt = randomBytes(32)
await db.setPassword(personUuid, hashWithSalt(password, salt), salt)
}
export async function generateUniqueOtp (db: AccountDB): Promise<string> {
let exists = true
let code = ''
do {
code = otpGenerator.generate(6, {
upperCaseAlphabets: false,
lowerCaseAlphabets: false,
specialChars: false
})
exists = (await db.otp.findOne({ code })) != null
} while (exists)
return code
}
export async function sendOtp (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
socialId: SocialId
): Promise<OtpInfo> {
const ts = Date.now()
const otpData = (await db.otp.find({ socialId: socialId._id }, { createdOn: 'descending' }, 1))[0]
const retryDelay = getMetadata(accountPlugin.metadata.OtpRetryDelaySec) ?? 30
if (otpData !== undefined && otpData.expiresOn > ts && otpData.createdOn + retryDelay * 1000 > ts) {
return { sent: true, retryOn: otpData.createdOn + retryDelay * 1000 }
}
let sendMethod: (ctx: MeasureContext, branding: Branding | null, code: string, target: string) => Promise<void>
switch (socialId.type) {
case SocialIdType.EMAIL: {
sendMethod = sendOtpEmail
break
}
default:
throw new Error('Unsupported OTP social id type')
}
const retryDelayMs = (getMetadata(accountPlugin.metadata.OtpRetryDelaySec) ?? 30) * 1000
const ttlMs = (getMetadata(accountPlugin.metadata.OtpTimeToLiveSec) ?? 60) * 1000
const code = await generateUniqueOtp(db)
await sendMethod(ctx, branding, code, socialId.value)
await db.otp.insertOne({ socialId: socialId._id, code, expiresOn: ts + ttlMs, createdOn: ts })
return { sent: true, retryOn: ts + retryDelayMs }
}
export async function sendOtpEmail (
ctx: MeasureContext,
branding: Branding | null,
otp: string,
email: string
): Promise<void> {
const mailURL = getMetadata(accountPlugin.metadata.MAIL_URL)
if (mailURL === undefined || mailURL === '') {
ctx.error('Please provide email service url to enable email otp')
return
}
const mailAuth = getMetadata(accountPlugin.metadata.MAIL_AUTH_TOKEN)
const lang = branding?.language
const app = branding?.title ?? getMetadata(accountPlugin.metadata.ProductName)
const text = await translate(accountPlugin.string.OtpText, { code: otp, app }, lang)
const html = await translate(accountPlugin.string.OtpHTML, { code: otp, app }, lang)
const subject = await translate(accountPlugin.string.OtpSubject, { code: otp, app }, lang)
const to = email
const response = await fetch(concatLink(mailURL, '/send'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(mailAuth != null ? { Authorization: `Bearer ${mailAuth}` } : {})
},
body: JSON.stringify({
text,
html,
subject,
to
})
})
if (!response.ok) {
ctx.error(`Failed to send otp email: ${response.statusText}`, { to })
}
}
export async function isOtpValid (db: AccountDB, socialId: PersonId, code: string): Promise<boolean> {
const otpData = await db.otp.findOne({ socialId, code })
return (otpData?.expiresOn ?? 0) > Date.now()
}
/**
* Creates an account and a Huly social id for the specified person.
* Returns the _id of the newly created Huly social id.
*/
export async function createAccount (
db: AccountDB,
personUuid: PersonUuid,
confirmed = false,
automatic = false,
createdOn = Date.now()
): Promise<PersonId> {
// Create Huly social id and account
const socialId = await db.socialId.insertOne({
type: SocialIdType.HULY,
value: personUuid,
personUuid,
...(confirmed ? { verifiedOn: Date.now() } : {})
})
await db.account.insertOne({ uuid: personUuid as AccountUuid, automatic })
await db.accountEvent.insertOne({
accountUuid: personUuid as AccountUuid,
eventType: AccountEventType.ACCOUNT_CREATED,
time: createdOn
})
return socialId
}
export async function signUpByEmail (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
email: string,
password: string | null,
firstName: string,
lastName: string,
confirmed = false,
automatic = false
): Promise<{ account: AccountUuid, socialId: PersonId }> {
const normalizedEmail = cleanEmail(email)
const emailSocialId = await getEmailSocialId(db, normalizedEmail)
let account: AccountUuid
let socialId: PersonId
if (emailSocialId !== null) {
const existingAccount = await db.account.findOne({ uuid: emailSocialId.personUuid as AccountUuid })
if (existingAccount !== null) {
ctx.error('An account with the provided email already exists', { email })
throw new PlatformError(new Status(Severity.ERROR, platform.status.AccountAlreadyExists, {}))
}
account = emailSocialId.personUuid as AccountUuid
socialId = emailSocialId._id
// Person exists, but may have different name, need to update with what's been provided
await db.person.update({ uuid: account }, { firstName, lastName })
} else {
// There's no person we can link to this email, so we need to create a new one
account = await db.person.insertOne({ firstName, lastName })
socialId = await db.socialId.insertOne({
type: SocialIdType.EMAIL,
value: normalizedEmail,
personUuid: account,
...(confirmed ? { verifiedOn: Date.now() } : {})
})
}
await createAccount(db, account, confirmed, automatic)
if (password != null) {
await setPassword(ctx, db, branding, account, password)
}
return { account, socialId }
}
export async function signUpByGrant (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
accountUuid: AccountUuid,
grant: PermissionsGrant,
info?: LoginInfoRequestData
): Promise<{ account: AccountUuid, socialId: PersonId }> {
const firstName = grant.firstName ?? info?.firstName
const lastName = grant.lastName ?? info?.lastName
if (firstName == null || firstName === '') {
ctx.error('First name is required for grant sign up', { grant, info })
throw new PlatformError(new Status(Severity.ERROR, platform.status.BadRequest, {}))
}
const existingAccount = await db.account.findOne({ uuid: accountUuid })
if (existingAccount != null) {
ctx.error('An account with the provided uuid already exists', { accountUuid })
throw new PlatformError(new Status(Severity.ERROR, platform.status.AccountAlreadyExists, {}))
}
const existingPerson = await db.person.findOne({ uuid: accountUuid })
if (existingPerson == null) {
await db.person.insertOne({ uuid: accountUuid, firstName, lastName: lastName ?? '' })
}
// If there's no account there should be no Huly social id associated with the person if it existed
// also, there should be no confirmed social ids associated
// so we can safely proceed to account creation
const socialId = await createAccount(db, accountUuid, true, true)
return { account: accountUuid, socialId }
}
export async function selectWorkspace (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
token: string | undefined,
params: {
workspaceUrl: string
kind: 'external' | 'internal' | 'byregion'
externalRegions?: string[]
},
meta?: Meta
): Promise<WorkspaceLoginInfo> {
const { workspaceUrl, kind, externalRegions = [] } = params
let workspace: Workspace | null = null
if (workspaceUrl !== '') {
workspace = await getWorkspaceByUrl(db, workspaceUrl)
}
let accountUuid: AccountUuid
let extra: Record<string, any> | undefined
let grant: PermissionsGrant | undefined
let sub: AccountUuid | undefined
let exp: number | undefined
let nbf: number | undefined
try {
const decodedToken = decodeTokenVerbose(ctx, token ?? '')
accountUuid = decodedToken.account
if (workspace == null) {
workspace = await getWorkspaceById(db, decodedToken.workspace)
}
extra = decodedToken.extra
grant = decodedToken.grant
sub = decodedToken.sub
exp = decodedToken.exp
nbf = decodedToken.nbf
} catch (e) {
if (workspace?.allowReadOnlyGuest === true) {
accountUuid = readOnlyGuestAccountUuid
} else {
throw e
}
}
if (workspace == null) {
ctx.error('Workspace not found in selectWorkspace', { workspaceUrl, kind, accountUuid, extra })
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUrl }))
}
const getKind = (region: string | undefined): EndpointKind => {
switch (kind) {
case 'external':
return EndpointKind.External
case 'internal':
return EndpointKind.Internal
case 'byregion':
return externalRegions.includes(region ?? '') ? EndpointKind.External : EndpointKind.Internal
default:
return meta?.clientNetworkPosition === 'internal' ? EndpointKind.Internal : EndpointKind.External
}
}
if (isGuest(accountUuid, extra)) {
const workspace = await getWorkspaceByUrl(db, workspaceUrl)
if (workspace == null) {
ctx.error('Workspace not found in selectWorkspace', { workspaceUrl, kind, accountUuid, extra })
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUrl }))
}
// Guest mode select workspace
return {
account: accountUuid,
endpoint: getEndpoint(workspace.uuid, workspace.region, getKind(workspace.region)),
token,
workspace: workspace.uuid,
workspaceUrl: workspace.url,
workspaceDataId: workspace.dataId,
role: AccountRole.DocGuest
}
}
if (accountUuid === systemAccountUuid) {
return {
account: accountUuid,
token: generateToken(accountUuid, workspace.uuid, extra, undefined, {
grant,
sub,
exp,
nbf
}),
endpoint: getEndpoint(workspace.uuid, workspace.region, getKind(workspace.region)),
workspace: workspace.uuid,
workspaceUrl: workspace.url,
role: AccountRole.Admin
}
}
let role = await db.getWorkspaceRole(accountUuid, workspace.uuid)
if (role == null && extra?.admin === 'true') {
role = AccountRole.Admin
}
let account = await db.account.findOne({ uuid: accountUuid })
if ((role == null || account == null) && workspace.allowReadOnlyGuest) {
accountUuid = readOnlyGuestAccountUuid
role = await db.getWorkspaceRole(accountUuid, workspace.uuid)
account = await db.account.findOne({ uuid: accountUuid })
}
if (role == null) {
ctx.error('Not a member of the workspace being selected', { workspaceUrl, accountUuid })
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
if (accountUuid !== systemAccountUuid && account == null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.AccountNotFound, {}))
}
if (accountUuid !== systemAccountUuid && meta !== undefined) {
void setTimezone(ctx, db, accountUuid, account, meta)
}
if (role === AccountRole.ReadOnlyGuest) {
if (extra == null) {
extra = {}
}
extra.readonly = 'true'
}
const wsStatus = await db.workspaceStatus.findOne({ workspaceUuid: workspace.uuid })
if (wsStatus != null) {
if (wsStatus.isDisabled && isActiveMode(wsStatus.mode)) {
ctx.error('Selecting a disabled workspace', { workspaceUrl, accountUuid })
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUrl }))
}
}
const person = await db.person.findOne({ uuid: accountUuid })
if (person == null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.InternalServerError, {}))
}
return {
account: accountUuid,
token: generateToken(accountUuid, workspace.uuid, extra, undefined, {
grant,
sub,
exp,
nbf
}),
endpoint: getEndpoint(workspace.uuid, workspace.region, getKind(workspace.region)),
workspace: workspace.uuid,
workspaceUrl: workspace.url,
workspaceDataId: workspace.dataId,
allowGuestSignUp: workspace.allowReadOnlyGuest && workspace.allowGuestSignUp,
role
}
}
export async function updateAllowReadOnlyGuests (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
token: string,
params: {
readOnlyGuestsAllowed: boolean
}
): Promise<{ guestPerson: Person, guestSocialIds: SocialId[] } | undefined> {
const { readOnlyGuestsAllowed } = params
const { account, workspace } = decodeTokenVerbose(ctx, token)
if (workspace === null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUuid: workspace }))
}
const accRole = account === systemAccountUuid ? AccountRole.Owner : await db.getWorkspaceRole(account, workspace)
if (accRole == null || getRolePower(accRole) < getRolePower(AccountRole.Owner)) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
await db.updateAllowReadOnlyGuests(workspace, readOnlyGuestsAllowed)
if (!readOnlyGuestsAllowed) {
await db.unassignWorkspace(readOnlyGuestAccountUuid, workspace)
return undefined
}
let guestPerson = await db.person.findOne({ uuid: readOnlyGuestAccountUuid as PersonUuid })
if (guestPerson == null) {
await db.person.insertOne({
uuid: readOnlyGuestAccountUuid as PersonUuid,
firstName: 'Anonymous',
lastName: 'Guest'
})
await createAccount(db, readOnlyGuestAccountUuid as PersonUuid, true)
guestPerson = await db.person.findOne({ uuid: readOnlyGuestAccountUuid as PersonUuid })
}
const roleInWorkspace = await db.getWorkspaceRole(readOnlyGuestAccountUuid, workspace)
if (roleInWorkspace == null) {
await db.assignWorkspace(readOnlyGuestAccountUuid, workspace, AccountRole.ReadOnlyGuest)
}
const guestAccount = await db.account.findOne({ uuid: readOnlyGuestAccountUuid })
if (guestPerson === null || guestAccount == null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.InternalServerError, {}))
}
const guestSocialIds = await db.socialId.find({
personUuid: readOnlyGuestAccountUuid as PersonUuid,
verifiedOn: { $gt: 0 }
})
return { guestPerson, guestSocialIds: guestSocialIds.filter((si) => si.isDeleted !== true) }
}
export async function updateAllowGuestSignUp (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
token: string,
params: {
guestSignUpAllowed: boolean
}
): Promise<void> {
const { guestSignUpAllowed } = params
const { account, workspace } = decodeTokenVerbose(ctx, token)
if (workspace === null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUuid: workspace }))
}
const accRole = account === systemAccountUuid ? AccountRole.Owner : await db.getWorkspaceRole(account, workspace)
if (accRole == null || getRolePower(accRole) < getRolePower(AccountRole.Owner)) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
await db.updateAllowGuestSignUp(workspace, guestSignUpAllowed)
}
export async function updateWorkspaceRole (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
token: string,
params: {
targetAccount: AccountUuid
targetRole: AccountRole
}
): Promise<void> {
const { targetAccount, targetRole } = params
if (targetAccount === readOnlyGuestAccountUuid) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
const { account, workspace } = decodeTokenVerbose(ctx, token)
if (workspace === null) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.WorkspaceNotFound, { workspaceUuid: workspace }))
}
const accRole = account === systemAccountUuid ? AccountRole.Owner : await db.getWorkspaceRole(account, workspace)
if (
accRole == null ||
getRolePower(accRole) < getRolePower(AccountRole.Maintainer) ||
getRolePower(accRole) < getRolePower(targetRole)
) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
const currentRole = await db.getWorkspaceRole(targetAccount, workspace)
if (currentRole == null || getRolePower(accRole) < getRolePower(currentRole)) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
if (currentRole === targetRole) return
if (currentRole === AccountRole.Owner) {
// Check if there are other owners
const owners = (await db.getWorkspaceMembers(workspace)).filter((m) => m.role === AccountRole.Owner)
if (owners.length === 1) {
throw new PlatformError(new Status(Severity.ERROR, platform.status.Forbidden, {}))
}
}
await db.updateWorkspaceRole(targetAccount, workspace, targetRole)
}
/**
* Convert workspace name to a URL-friendly string following these rules:
*
* 1. Converts all characters to lowercase
* 2. Only keeps alphanumeric characters (a-z, 0-9) and hyphens (-)
* 3. Cannot start with a number or hyphen
* 4. Cannot end with a hyphen
* 5. Removes all other special characters
*/
export function generateWorkspaceUrl (name: string): string {
const lowercaseName = name.toLowerCase()
let result = ''
let isFirst = true
for (const char of lowercaseName) {
const isValidChar = /[a-z0-9-]/.test(char)
const isNumber = /[0-9]/.test(char)
const isHyphen = char === '-'
if (isValidChar && (!isFirst || (!isNumber && !isHyphen))) {
result += char
isFirst = false
}
}
// Trim hyphens from the end
return result.replace(/-+$/, '')
}
// TODO: rework later to map exact codes for specific DBs
const DB_ERROR_CODES = {
UNIQUE_VIOLATION: [
'23505', // Postgres, CockroachDB
11000 // Mongo
]
}
interface CreateWorkspaceRecordResult {
workspaceUuid: WorkspaceUuid
workspaceUrl: string
}
export async function createWorkspaceRecord (
ctx: MeasureContext,
db: AccountDB,
branding: Branding | null,
workspaceName: string,
account: PersonUuid,
region: string = '',
initMode: WorkspaceMode = 'pending-creation',
dataId?: WorkspaceDataId
): Promise<CreateWorkspaceRecordResult> {
const brandingKey = branding?.key ?? 'huly'
const regionInfo = getRegions().find((it) => it.region === region)
if (regionInfo === undefined) {
ctx.error('Region not found', { region, regions: getRegions() })
throw new PlatformError(
new Status(Severity.ERROR, platform.status.InternalServerError, {
region
})
)
}
// The workspace url must be unique.
// This function is not concurrency safe, moreover multiple account services may be
// creating a workspace with the same base url at the same time so it's not possible
// to make it safe in the first place.
// But the uniqueness is guaranteed by the database rules and it will reject duplicate workspace urls.
// So we just need to handle the expected error and retry until we get a unique url.
let iteration = 0
let baseWorkspaceUrl = generateWorkspaceUrl(workspaceName)
let workspaceUrl = baseWorkspaceUrl
if (baseWorkspaceUrl === '') {
baseWorkspaceUrl = 'ws'
workspaceUrl = `ws-${generateId('-')}`
}
while (true) {
try {
const workspaceUuid = await db.createWorkspace(
{
name: workspaceName,
url: workspaceUrl,
dataId,
branding: brandingKey,
createdBy: account,
billingAccount: account,
allowReadOnlyGuest: false,
allowGuestSignUp: false,
region
},
{
mode: initMode,
versionMajor: 0,
versionMinor: 0,
versionPatch: 0,
isDisabled: true
}
)
return {
workspaceUuid,
workspaceUrl
}
} catch (err: any) {
if (!DB_ERROR_CODES.UNIQUE_VIOLATION.includes(err.code)) {
throw err
}
}
workspaceUrl = `${baseWorkspaceUrl}-${generateId('-')}`
iteration++
// Safety check to prevent infinite loop. Should never happen if the code is alright.
if (iteration > 1000) {
ctx.error('Workspace record generation failed. Could not create a workspace record in 1000 attempts.', {