-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathprotocol.ts
1541 lines (1346 loc) · 46.8 KB
/
protocol.ts
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 (c) 2020 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License.AGPL.txt in the project root for license information.
*/
import { WorkspaceInstance, PortVisibility, PortProtocol, WorkspaceInstanceMetrics } from "./workspace-instance";
import { RoleOrPermission } from "./permission";
import { Project } from "./teams-projects-protocol";
import { createHash } from "crypto";
import { WorkspaceRegion } from "./workspace-cluster";
export interface UserInfo {
name?: string;
}
export interface User {
/** The user id */
id: string;
/** The ID of the Organization this user is owned by. If undefined, the user is owned by the installation */
organizationId?: string;
/** The timestamp when the user entry was created */
creationDate: string;
avatarUrl?: string;
name?: string;
/** Optional for backwards compatibility */
fullName?: string;
identities: Identity[];
/**
* Whether the user has been blocked to use our service, because of TOS violation for example.
* Optional for backwards compatibility.
*/
blocked?: boolean;
/** A map of random settings that alter the behaviour of Gitpod on a per-user basis */
featureFlags?: UserFeatureSettings;
/** The permissions and/or roles the user has */
rolesOrPermissions?: RoleOrPermission[];
/** Whether the user is logical deleted. This flag is respected by all queries in UserDB */
markedDeleted?: boolean;
additionalData?: AdditionalUserData;
// Identifies an explicit team or user ID to which all the user's workspace usage should be attributed to (e.g. for billing purposes)
usageAttributionId?: string;
// The last time this user got verified somehow. The user is not verified if this is empty.
lastVerificationTime?: string;
// The phone number used for the last phone verification.
verificationPhoneNumber?: string;
// The FGA relationships version of this user
fgaRelationshipsVersion?: number;
}
export namespace User {
export function is(data: any): data is User {
return data && data.hasOwnProperty("id") && data.hasOwnProperty("identities");
}
export function getIdentity(user: User, authProviderId: string): Identity | undefined {
return user.identities.find((id) => id.authProviderId === authProviderId);
}
export function isOrganizationOwned(user: User) {
return !!user.organizationId;
}
}
export interface WorkspaceTimeoutSetting {
// user globol workspace timeout
workspaceTimeout: string;
// control whether to enable the closed timeout of a workspace, i.e. close web ide, disconnect ssh connection
disabledClosedTimeout: boolean;
}
export interface AdditionalUserData extends Partial<WorkspaceTimeoutSetting> {
/** @deprecated unused */
platforms?: UserPlatform[];
emailNotificationSettings?: EmailNotificationSettings;
featurePreview?: boolean;
ideSettings?: IDESettings;
// key is the name of the news, string the iso date when it was seen
whatsNewSeen?: { [key: string]: string };
// key is the name of the OAuth client i.e. local app, string the iso date when it was approved
// TODO(rl): provide a management UX to allow rescinding of approval
oauthClientsApproved?: { [key: string]: string };
// to remember GH Orgs the user installed/updated the GH App for
/** @deprecated unused */
knownGitHubOrgs?: string[];
// Git clone URL pointing to the user's dotfile repo
dotfileRepo?: string;
// preferred workspace classes
workspaceClasses?: WorkspaceClasses;
// additional user profile data
profile?: ProfileDetails;
/** @deprecated */
shouldSeeMigrationMessage?: boolean;
// remembered workspace auto start options
workspaceAutostartOptions?: WorkspaceAutostartOption[];
}
export interface WorkspaceAutostartOption {
cloneURL: string;
organizationId: string;
workspaceClass?: string;
ideSettings?: IDESettings;
region?: WorkspaceRegion;
}
export namespace AdditionalUserData {
export function set(user: User, partialData: Partial<AdditionalUserData>): User {
if (!user.additionalData) {
user.additionalData = {
...partialData,
};
} else {
user.additionalData = {
...user.additionalData,
...partialData,
};
}
return user;
}
}
// The format in which we store User Profiles in
export interface ProfileDetails {
// when was the last time the user updated their profile information or has been nudged to do so.
lastUpdatedDetailsNudge?: string;
// when was the last time the user has accepted our privacy policy
acceptedPrivacyPolicyDate?: string;
// the user's company name
companyName?: string;
// the user's email
emailAddress?: string;
// type of role user has in their job
jobRole?: string;
// freeform entry for job role user works in (when jobRole is "other")
jobRoleOther?: string;
// Reasons user is exploring Gitpod when they signed up
explorationReasons?: string[];
// what user hopes to accomplish when they signed up
signupGoals?: string[];
// freeform entry for signup goals (when signupGoals is "other")
signupGoalsOther?: string;
// Set after a user completes the onboarding flow
onboardedTimestamp?: string;
// Onboarding question about a user's company size
companySize?: string;
// key-value pairs of dialogs in the UI which should only appear once. The value usually is a timestamp of the last dismissal
coachmarksDismissals?: { [key: string]: string };
}
export interface EmailNotificationSettings {
allowsChangelogMail?: boolean;
allowsDevXMail?: boolean;
allowsOnboardingMail?: boolean;
}
export type IDESettings = {
settingVersion?: string;
defaultIde?: string;
useLatestVersion?: boolean;
preferToolbox?: boolean;
// DEPRECATED: Use defaultIde after `settingVersion: 2.0`, no more specialify desktop or browser.
useDesktopIde?: boolean;
// DEPRECATED: Same with useDesktopIde.
defaultDesktopIde?: string;
};
export interface WorkspaceClasses {
regular?: string;
/**
* @deprecated see Project.settings.prebuilds.workspaceClass
*/
prebuild?: string;
}
export interface UserPlatform {
uid: string;
userAgent: string;
browser: string;
os: string;
lastUsed: string;
firstUsed: string;
/**
* Since when does the user have the browser extension installe don this device.
*/
browserExtensionInstalledSince?: string;
/**
* Since when does the user not have the browser extension installed anymore (but previously had).
*/
browserExtensionUninstalledSince?: string;
}
export interface UserFeatureSettings {
/**
* Permanent feature flags are added to each and every workspace instance
* this user starts.
*/
permanentWSFeatureFlags?: NamedWorkspaceFeatureFlag[];
}
export type BillingTier = "paid" | "free";
/**
* The values of this type MUST MATCH enum values in WorkspaceFeatureFlag from ws-manager/client/core_pb.d.ts
* If they don't we'll break things during workspace startup.
*/
export const WorkspaceFeatureFlags = {
full_workspace_backup: undefined,
workspace_class_limiting: undefined,
workspace_connection_limiting: undefined,
workspace_psi: undefined,
ssh_ca: undefined,
};
export type NamedWorkspaceFeatureFlag = keyof typeof WorkspaceFeatureFlags;
export namespace NamedWorkspaceFeatureFlag {
export const WORKSPACE_PERSISTED_FEATTURE_FLAGS: NamedWorkspaceFeatureFlag[] = ["full_workspace_backup"];
export function isWorkspacePersisted(ff: NamedWorkspaceFeatureFlag): boolean {
return WORKSPACE_PERSISTED_FEATTURE_FLAGS.includes(ff);
}
}
export type EnvVar = UserEnvVar | ProjectEnvVarWithValue | OrgEnvVarWithValue | EnvVarWithValue;
export interface EnvVarWithValue {
name: string;
value: string;
}
export interface ProjectEnvVarWithValue extends EnvVarWithValue {
id?: string;
/** If a project-scoped env var is "censored", it is only visible in Prebuilds */
censored: boolean;
}
export interface ProjectEnvVar extends Omit<ProjectEnvVarWithValue, "value"> {
id: string;
projectId: string;
}
export interface OrgEnvVarWithValue extends EnvVarWithValue {
id?: string;
}
export interface OrgEnvVar extends Omit<OrgEnvVarWithValue, "value"> {
id: string;
orgId: string;
}
export interface UserEnvVarValue extends EnvVarWithValue {
id?: string;
repositoryPattern: string; // DEPRECATED: Use ProjectEnvVar instead of repositoryPattern - https://github.com/gitpod-com/gitpod/issues/5322
}
export interface UserEnvVar extends UserEnvVarValue {
id: string;
userId: string;
deleted?: boolean;
}
export namespace EnvVar {
export const GITPOD_IMAGE_AUTH_ENV_VAR_NAME = "GITPOD_IMAGE_AUTH";
/**
* - GITPOD_IMAGE_AUTH is documented https://www.gitpod.io/docs/configure/workspaces/workspace-image#use-a-private-docker-image
*/
export const WhiteListFromReserved = [GITPOD_IMAGE_AUTH_ENV_VAR_NAME];
export function is(data: any): data is EnvVar {
return data.hasOwnProperty("name") && data.hasOwnProperty("value");
}
/**
* Extracts the "host:credentials" pairs from the GITPOD_IMAGE_AUTH environment variable.
* @param envVars
* @returns A map of host to credentials
*/
export function getGitpodImageAuth(envVars: EnvVarWithValue[]): Map<string, string> {
const res = new Map<string, string>();
const imageAuth = envVars.find((e) => e.name === EnvVar.GITPOD_IMAGE_AUTH_ENV_VAR_NAME);
if (!imageAuth) {
return res;
}
(imageAuth.value || "")
.split(",")
.map((e) => e.trim().split(":"))
.filter((e) => e.length == 2)
.forEach((e) => res.set(e[0], e[1]));
return res;
}
}
export namespace UserEnvVar {
export const DELIMITER = "/";
export const WILDCARD_ASTERISK = "*";
// This wildcard is only allowed on the last segment, and matches arbitrary segments to the right
export const WILDCARD_DOUBLE_ASTERISK = "**";
const WILDCARD_SHARP = "#"; // TODO(gpl) Where does this come from? Bc we have/had patterns as part of URLs somewhere, maybe...?
const MIN_PATTERN_SEGMENTS = 2;
function isWildcard(c: string): boolean {
return c === WILDCARD_ASTERISK || c === WILDCARD_SHARP;
}
export function is(data: any): data is UserEnvVar {
return (
EnvVar.is(data) &&
data.hasOwnProperty("id") &&
data.hasOwnProperty("userId") &&
data.hasOwnProperty("repositoryPattern")
);
}
/**
* @param variable
* @returns Either a string containing an error message or undefined.
*/
export function validate(variable: UserEnvVarValue): string | undefined {
const name = variable.name;
const pattern = variable.repositoryPattern;
if (!EnvVar.WhiteListFromReserved.includes(name) && name.startsWith("GITPOD_")) {
return "Name with prefix 'GITPOD_' is reserved.";
}
if (name.trim() === "") {
return "Name must not be empty.";
}
if (name.length > 255) {
return "Name too long. Maximum name length is 255 characters.";
}
if (!/^[a-zA-Z_]+[a-zA-Z0-9_]*$/.test(name)) {
return "Name must match /^[a-zA-Z_]+[a-zA-Z0-9_]*$/.";
}
if (variable.value.trim() === "") {
return "Value must not be empty.";
}
if (variable.value.length > 32767) {
return "Value too long. Maximum value length is 32767 characters.";
}
if (pattern.trim() === "") {
return "Scope must not be empty.";
}
const split = splitRepositoryPattern(pattern);
if (split.length < MIN_PATTERN_SEGMENTS) {
return "A scope must use the form 'organization/repo'.";
}
for (const name of split) {
if (name !== "*") {
if (!/^[a-zA-Z0-9_\-.\*]+$/.test(name)) {
return "Invalid scope segment. Only ASCII characters, numbers, -, _, . or * are allowed.";
}
}
}
return undefined;
}
export function normalizeRepoPattern(pattern: string) {
return pattern.toLocaleLowerCase();
}
function splitRepositoryPattern(pattern: string): string[] {
return pattern.split(DELIMITER);
}
function joinRepositoryPattern(...parts: string[]): string {
return parts.join(DELIMITER);
}
/**
* Matches the given EnvVar pattern against the fully qualified name of the repository:
* - GitHub: "repo/owner"
* - GitLab: "some/nested/repo" (up to MAX_PATTERN_SEGMENTS deep)
* @param pattern
* @param repoFqn
* @returns True if the pattern matches that fully qualified name
*/
export function matchEnvVarPattern(pattern: string, repoFqn: string): boolean {
const fqnSegments = splitRepositoryPattern(repoFqn);
const patternSegments = splitRepositoryPattern(pattern);
if (patternSegments.length < MIN_PATTERN_SEGMENTS) {
// Technically not a problem, but we should not allow this for safety reasons.
// And because we hisotrically never allowed this (GitHub would always require at least "*/*") we are just keeping old constraints.
// Note: Most importantly this guards against arbitrary wildcard matches
return false;
}
function isWildcardMatch(patternSegment: string, isLastSegment: boolean): boolean {
if (isWildcard(patternSegment)) {
return true;
}
return isLastSegment && patternSegment === WILDCARD_DOUBLE_ASTERISK;
}
let i = 0;
for (; i < patternSegments.length; i++) {
if (i >= fqnSegments.length) {
return false;
}
const fqnSegment = fqnSegments[i];
const patternSegment = patternSegments[i];
const isLastSegment = patternSegments.length === i + 1;
if (!isWildcardMatch(patternSegment, isLastSegment) && patternSegment !== fqnSegment.toLocaleLowerCase()) {
return false;
}
}
if (fqnSegments.length > i) {
// Special case: "**" as last segment matches arbitrary # of segments to the right
if (patternSegments[i - 1] === WILDCARD_DOUBLE_ASTERISK) {
return true;
}
return false;
}
return true;
}
// Matches the following patterns for "some/nested/repo", ordered by highest score:
// - exact: some/nested/repo ()
// - partial:
// - some/nested/*
// - some/*
// - generic:
// - */*/*
// - */*
// Does NOT match:
// - */repo (number of parts does not match)
// cmp. test cases in env-var-service.spec.ts
export function filter<T extends UserEnvVarValue>(vars: T[], owner: string, repo: string): T[] {
const matchedEnvVars = vars.filter((e) =>
matchEnvVarPattern(e.repositoryPattern, joinRepositoryPattern(owner, repo)),
);
const resmap = new Map<string, T[]>();
matchedEnvVars.forEach((e) => {
const l = resmap.get(e.name) || [];
l.push(e);
resmap.set(e.name, l);
});
// In cases of multiple matches per env var: find the best match
// Best match is the most specific pattern, where the left-most segment is most significant
function scoreMatchedEnvVar(e: T): number {
function valueSegment(segment: string): number {
switch (segment) {
case WILDCARD_ASTERISK:
return 2;
case WILDCARD_SHARP:
return 2;
case WILDCARD_DOUBLE_ASTERISK:
return 1;
default:
return 3;
}
}
const patternSegments = splitRepositoryPattern(e.repositoryPattern);
let result = 0;
for (const segment of patternSegments) {
// We can assume the pattern matches from context, so we just need to check whether it's a wildcard or not
const val = valueSegment(segment);
result = result * 10 + val;
}
return result;
}
const result = [];
for (const name of resmap.keys()) {
const candidates = resmap.get(name);
if (!candidates) {
// not sure how this can happen, but so be it
continue;
}
if (candidates.length == 1) {
result.push(candidates[0]);
continue;
}
let bestCandidate = candidates[0];
let bestScore = scoreMatchedEnvVar(bestCandidate);
for (const e of candidates.slice(1)) {
const score = scoreMatchedEnvVar(e);
if (score > bestScore) {
bestScore = score;
bestCandidate = e;
}
}
result.push(bestCandidate!);
}
return result;
}
}
export interface SSHPublicKeyValue {
name: string;
key: string;
}
export interface UserSSHPublicKey extends SSHPublicKeyValue {
id: string;
key: string;
userId: string;
fingerprint: string;
creationTime: string;
lastUsedTime?: string;
}
export type UserSSHPublicKeyValue = Omit<UserSSHPublicKey, "userId">;
export namespace SSHPublicKeyValue {
export function validate(value: SSHPublicKeyValue): string | undefined {
if (value.name.length === 0) {
return "Title must not be empty.";
}
if (value.name.length > 255) {
return "Title too long. Maximum value length is 255 characters.";
}
if (value.key.length === 0) {
return "Key must not be empty.";
}
try {
getData(value);
} catch (e) {
return "Key is invalid. You must supply a key in OpenSSH public key format.";
}
return;
}
export function getData(value: SSHPublicKeyValue) {
// Begins with 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'ssh-ed25519', '[email protected]', or '[email protected]'.
const regex =
/^(?<type>ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|ssh-ed25519|sk-ecdsa-sha2-nistp256@openssh\.com|sk-ssh-ed25519@openssh\.com) (?<key>.*?)( (?<email>.*?))?$/;
const resultGroup = regex.exec(value.key.trim());
if (!resultGroup) {
throw new Error("Key is invalid.");
}
return {
type: resultGroup.groups?.["type"] as string,
key: resultGroup.groups?.["key"] as string,
email: resultGroup.groups?.["email"] || undefined,
};
}
export function getFingerprint(value: SSHPublicKeyValue) {
const data = getData(value);
const buf = Buffer.from(data.key, "base64");
// gitlab style
// const hash = createHash("md5").update(buf).digest("hex");
// github style
const hash = createHash("sha256").update(buf).digest("base64");
return hash;
}
export const MAXIMUM_KEY_LENGTH = 5;
}
export interface GitpodToken {
/** Hash value (SHA256) of the token (primary key). */
tokenHash: string;
/** Human readable name of the token */
name?: string;
/** Token kind */
type: GitpodTokenType;
/** The user the token belongs to. */
userId: string;
/** Scopes (e.g. limition to read-only) */
scopes: string[];
/** Created timestamp */
created: string;
}
export enum GitpodTokenType {
API_AUTH_TOKEN = 0,
MACHINE_AUTH_TOKEN = 1,
}
export interface OneTimeSecret {
id: string;
value: string;
expirationTime: string;
deleted: boolean;
}
export interface WorkspaceInstanceUser {
name?: string;
avatarUrl?: string;
instanceId: string;
userId: string;
lastSeen: string;
}
export interface Identity {
authProviderId: string;
authId: string;
authName: string;
primaryEmail?: string;
/** This is a flag that triggers the HARD DELETION of this entity */
deleted?: boolean;
// The last time this entry was touched during a signin. It's only set for SSO identities.
lastSigninTime?: string;
// @deprecated as no longer in use since '19
readonly?: boolean;
}
export type IdentityLookup = Pick<Identity, "authProviderId" | "authId">;
export namespace Identity {
export function is(data: any): data is Identity {
return (
data.hasOwnProperty("authProviderId") && data.hasOwnProperty("authId") && data.hasOwnProperty("authName")
);
}
export function equals(id1: IdentityLookup, id2: IdentityLookup) {
return id1.authProviderId === id2.authProviderId && id1.authId === id2.authId;
}
}
export interface Token {
value: string;
scopes: string[];
updateDate?: string;
expiryDate?: string;
reservedUntilDate?: string;
idToken?: string;
refreshToken?: string;
username?: string;
}
export interface TokenEntry {
uid: string;
authProviderId: string;
authId: string;
token: Token;
expiryDate?: string;
reservedUntilDate?: string;
refreshable?: boolean;
}
export interface EmailDomainFilterEntry {
domain: string;
negative: boolean;
}
export type AppInstallationPlatform = "github";
export type AppInstallationState = "claimed.user" | "claimed.platform" | "installed" | "uninstalled";
export interface AppInstallation {
platform: AppInstallationPlatform;
installationID: string;
ownerUserID?: string;
platformUserID?: string;
state: AppInstallationState;
creationTime: string;
lastUpdateTime: string;
}
export interface PendingGithubEvent {
id: string;
githubUserId: string;
creationDate: Date;
type: string;
event: string;
deleted: boolean;
}
export interface Snapshot {
id: string;
creationTime: string;
availableTime?: string;
originalWorkspaceId: string;
bucketId: string;
state: SnapshotState;
message?: string;
}
export type SnapshotState = "pending" | "available" | "error";
export interface Workspace {
id: string;
creationTime: string;
organizationId: string;
contextURL: string;
description: string;
ownerId: string;
projectId?: string;
context: WorkspaceContext;
config: WorkspaceConfig;
/**
* The source where to get the workspace base image from. This source is resolved
* during workspace creation. Once a base image has been built the information in here
* is superseded by baseImageNameResolved.
*/
imageSource?: WorkspaceImageSource;
/**
* The resolved, fix name of the workspace image. We only use this
* to access the logs during an image build.
*/
imageNameResolved?: string;
/**
* The resolved/built fixed named of the base image. This field is only set if the workspace
* already has its base image built.
*/
baseImageNameResolved?: string;
shareable?: boolean;
pinned?: boolean;
// workspace is hard-deleted on the database and about to be collected by periodic deleter
readonly deleted?: boolean;
/**
* Mark as deleted (user-facing). The actual deletion of the workspace content is executed
* with a (configurable) delay
*/
softDeleted?: WorkspaceSoftDeletion;
/**
* Marks the time when the workspace was marked as softDeleted. The actual deletion of the
* workspace content happens after a configurable period
*/
softDeletedTime?: string;
/**
* Marks the time when the workspace content has been deleted.
*/
contentDeletedTime?: string;
/**
* The time when the workspace is eligible for soft deletion. This is the time when the workspace
* is marked as softDeleted earliest.
*/
deletionEligibilityTime?: string;
type: WorkspaceType;
basedOnPrebuildId?: string;
basedOnSnapshotId?: string;
}
export type WorkspaceSoftDeletion = "user" | "gc";
export type WorkspaceType = "regular" | "prebuild" | "imagebuild";
export namespace Workspace {
export function getPullRequestNumber(ws: Workspace): number | undefined {
if (PullRequestContext.is(ws.context)) {
return ws.context.nr;
}
return undefined;
}
export function getIssueNumber(ws: Workspace): number | undefined {
if (IssueContext.is(ws.context)) {
return ws.context.nr;
}
return undefined;
}
export function getBranchName(ws: Workspace): string | undefined {
if (CommitContext.is(ws.context)) {
return ws.context.ref;
}
return undefined;
}
export function getCommit(ws: Workspace): string | undefined {
if (CommitContext.is(ws.context)) {
return ws.context.revision && ws.context.revision.substr(0, 8);
}
return undefined;
}
const NAME_PREFIX = "named:";
export function fromWorkspaceName(name?: Workspace["description"]): string | undefined {
if (name?.startsWith(NAME_PREFIX)) {
return name.slice(NAME_PREFIX.length);
}
return undefined;
}
export function toWorkspaceName(name?: Workspace["description"]): string {
if (!name || name?.trim().length === 0) {
return "no-name";
}
return `${NAME_PREFIX}${name}`;
}
}
export interface GuessGitTokenScopesParams {
host: string;
repoUrl: string;
gitCommand: string;
}
export interface GuessedGitTokenScopes {
message?: string;
scopes?: string[];
}
export interface VSCodeConfig {
extensions?: string[];
}
export interface JetBrainsConfig {
intellij?: JetBrainsProductConfig;
goland?: JetBrainsProductConfig;
pycharm?: JetBrainsProductConfig;
phpstorm?: JetBrainsProductConfig;
rubymine?: JetBrainsProductConfig;
webstorm?: JetBrainsProductConfig;
rider?: JetBrainsProductConfig;
clion?: JetBrainsProductConfig;
rustrover?: JetBrainsProductConfig;
}
export interface JetBrainsProductConfig {
prebuilds?: JetBrainsPrebuilds;
vmoptions?: string;
}
export interface JetBrainsPrebuilds {
version?: "stable" | "latest" | "both";
}
export interface RepositoryCloneInformation {
url: string;
checkoutLocation?: string;
}
export interface CoreDumpConfig {
enabled?: boolean;
softLimit?: number;
hardLimit?: number;
}
export interface WorkspaceConfig {
mainConfiguration?: string;
additionalRepositories?: RepositoryCloneInformation[];
image?: ImageConfig;
ports?: PortConfig[];
tasks?: TaskConfig[];
checkoutLocation?: string;
workspaceLocation?: string;
gitConfig?: { [config: string]: string };
github?: GithubAppConfig;
vscode?: VSCodeConfig;
jetbrains?: JetBrainsConfig;
coreDump?: CoreDumpConfig;
ideCredentials?: string;
env?: { [env: string]: any };
/** deprecated. Enabled by default **/
experimentalNetwork?: boolean;
/**
* Where the config object originates from.
*
* repo - from the repository
* derived - computed based on analyzing the repository
* additional-content - config comes from additional content, usually provided through the project's configuration
* default - our static catch-all default config
*/
_origin?: "repo" | "derived" | "additional-content" | "default";
/**
* Set of automatically infered feature flags. That's not something the user can set, but
* that is set by gitpod at workspace creation time.
*/
_featureFlags?: NamedWorkspaceFeatureFlag[];
}
export interface GithubAppConfig {
prebuilds?: GithubAppPrebuildConfig;
}
export interface GithubAppPrebuildConfig {
master?: boolean;
branches?: boolean;
pullRequests?: boolean;
pullRequestsFromForks?: boolean;
addCheck?: boolean | "prevent-merge-on-error";
addBadge?: boolean;
addLabel?: boolean | string;
addComment?: boolean;
}
export namespace GithubAppPrebuildConfig {
export function is(obj: boolean | GithubAppPrebuildConfig): obj is GithubAppPrebuildConfig {
return !(typeof obj === "boolean");
}
}
export type WorkspaceImageSource = WorkspaceImageSourceDocker | WorkspaceImageSourceReference;
export interface WorkspaceImageSourceDocker {
dockerFilePath: string;
dockerFileHash: string;
dockerFileSource?: Commit;
}
export namespace WorkspaceImageSourceDocker {
export function is(obj: object): obj is WorkspaceImageSourceDocker {
return "dockerFileHash" in obj && "dockerFilePath" in obj;
}
}
export interface WorkspaceImageSourceReference {
/** The resolved, fix base image reference */
baseImageResolved: string;
}
export namespace WorkspaceImageSourceReference {
export function is(obj: object): obj is WorkspaceImageSourceReference {
return "baseImageResolved" in obj;
}
}
export type PrebuiltWorkspaceState =
// the prebuild is queued and may start at anytime
| "queued"
// the workspace prebuild is currently running (i.e. there's a workspace pod deployed)
| "building"
// the prebuild was aborted
| "aborted"
// the prebuild timed out
| "timeout"
// the prebuild has finished (even if a headless task failed) and a snapshot is available
| "available"
// the prebuild (headless workspace) failed due to some system error
| "failed";
export interface PrebuiltWorkspace {
id: string;
cloneURL: string;
branch?: string;
projectId?: string;
commit: string;
buildWorkspaceId: string;
creationTime: string;
state: PrebuiltWorkspaceState;
statusVersion: number;
error?: string;
snapshot?: string;
}
export type PrebuiltWorkspaceWithWorkspace = PrebuiltWorkspace & { workspace: Workspace };
export namespace PrebuiltWorkspace {
export function isDone(pws: PrebuiltWorkspace) {
return (
pws.state === "available" || pws.state === "timeout" || pws.state === "aborted" || pws.state === "failed"
);
}
export function isAvailable(pws: PrebuiltWorkspace) {
return pws.state === "available" && !!pws.snapshot;
}
export function buildDidSucceed(pws: PrebuiltWorkspace) {
return pws.state === "available" && !pws.error;
}
}
export interface PrebuiltWorkspaceUpdatable {
id: string;
prebuiltWorkspaceId: string;
owner: string;
repo: string;
isResolved: boolean;
installationId: string;
/**
* the commitSHA of the commit that triggered the prebuild
*/
commitSHA?: string;
issue?: string;
contextUrl?: string;
}
export type PortOnOpen = "open-browser" | "open-preview" | "notify" | "ignore";
export interface PortConfig {
port: number;
onOpen?: PortOnOpen;
visibility?: PortVisibility;
protocol?: PortProtocol;
description?: string;
name?: string;
}
export namespace PortConfig {
export function is(config: any): config is PortConfig {
return config && "port" in config && typeof config.port === "number";
}