Path: blob/main/components/gitpod-protocol/src/util/parse-workspace-id.ts
2500 views
/**1* Copyright (c) 2020 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56const REGEX_WORKSPACE_ID = /[0-9a-z]{2,16}-[0-9a-z]{2,16}-[0-9a-z]{8,11}/;7const REGEX_WORKSPACE_ID_EXACT = new RegExp(`^${REGEX_WORKSPACE_ID.source}$`);8// We need to parse the workspace id precisely here to get the case '<some-str>-<port>-<wsid>.ws.' right9const REGEX_WORKSPACE_ID_FROM_HOSTNAME = new RegExp(`(${REGEX_WORKSPACE_ID.source})\.ws`);1011const REGEX_WORKSPACE_ID_LEGACY = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;12const REGEX_WORKSPACE_ID_LEGACY_EXACT = new RegExp(`^${REGEX_WORKSPACE_ID_LEGACY.source}$`);13const REGEX_WORKSPACE_ID_LEGACY_FROM_HOSTNAME = new RegExp(`(${REGEX_WORKSPACE_ID_LEGACY.source})\.ws`);1415/**16* Hostname may be of the form:17* - moccasin-ferret-155799b3.ws-eu01.gitpod.io18* - 1234-moccasin-ferret-155799b3.ws-eu01.gitpod.io19* - webview-1234-moccasin-ferret-155799b3.ws-eu01.gitpod.io (or any other string replacing webview)20* @param hostname The hostname the request is headed to21*/22export const parseWorkspaceIdFromHostname = function (hostname: string) {23const match = REGEX_WORKSPACE_ID_FROM_HOSTNAME.exec(hostname);24if (match && match.length >= 2) {25return match[1];26} else {27const legacyMatch = REGEX_WORKSPACE_ID_LEGACY_FROM_HOSTNAME.exec(hostname);28if (legacyMatch && legacyMatch.length >= 2) {29return legacyMatch[1];30}31return undefined;32}33};3435/** Equals UUIDv4 (and REGEX_WORKSPACE_ID_LEGACY!) */36const REGEX_INSTANCE_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;37const REGEX_INSTANCE_ID_EXACT = new RegExp(`^${REGEX_INSTANCE_ID.source}$`);3839/**40* @param maybeId41* @returns42*/43export const matchesInstanceIdOrLegacyWorkspaceIdExactly = function (maybeId: string): boolean {44return REGEX_INSTANCE_ID_EXACT.test(maybeId) || REGEX_WORKSPACE_ID_LEGACY_EXACT.test(maybeId);45};4647/**48* @param maybeWorkspaceId49* @returns50*/51export const matchesNewWorkspaceIdExactly = function (maybeWorkspaceId: string): boolean {52return REGEX_WORKSPACE_ID_EXACT.test(maybeWorkspaceId);53};5455/**56* Matches both new and legacy workspace ids57*/58export const isWorkspaceId = function (maybeWorkspaceId?: string): boolean {59if (!maybeWorkspaceId) {60return false;61}6263return matchesNewWorkspaceIdExactly(maybeWorkspaceId) || REGEX_WORKSPACE_ID_LEGACY_EXACT.test(maybeWorkspaceId);64};656667