Skip to content

Commit

Permalink
deply on cloudflare (conwnet#597)
Browse files Browse the repository at this point in the history
* chore: cloudflare pages deploy

* chore: cloudflare page functions

* feat: use openvsx
  • Loading branch information
conwnet authored Dec 3, 2024
1 parent bccfe76 commit 932c504
Show file tree
Hide file tree
Showing 8 changed files with 167 additions and 10 deletions.
68 changes: 68 additions & 0 deletions functions/api/github-auth-callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* @file github auth callback
* @author netcon
*/

const createResponseHtml = (text: string, script: string) => `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connect to GitHub</title>
</head>
<body>
<h1>${text}</h1>
<script>${script}</script>
</body>
</html>
`;

// return the data to the opener window by postMessage API,
// and close current window if successfully connected
const createAuthorizeResultHtml = (data: Record<any, any>, origins: string) => {
const errorText = 'Failed! You can close this window and retry.';
const successText = 'Connected! You can now close this window.';
const resultStr = `{ type: 'authorizing', payload: ${JSON.stringify(data)} }`;
const script = `
'${origins}'.split(',').forEach(function(allowedOrigin) {
window.opener.postMessage(${resultStr}, allowedOrigin);
});
${data.error ? '' : 'setTimeout(() => window.close(), 50);'}`;
return createResponseHtml(data.error ? errorText : successText, script);
};

const MISSING_CODE_ERROR = {
error: 'request_invalid',
error_description: 'Missing code',
};
const UNKNOWN_ERROR = {
error: 'internal_error',
error_description: 'Unknown error',
};

export const onRequest: PagesFunction<{
GITHUB_OAUTH_ID: string;
GITHUB_OAUTH_SECRET: string;
GITHUB1S_ALLOWED_ORIGINS: string;
}> = async ({ request, env }) => {
const code = new URL(request.url).searchParams.get('code');

const createResponse = (status, data) => {
const body = createAuthorizeResultHtml(data, env.GITHUB1S_ALLOWED_ORIGINS);
return new Response(body, { status });
};

if (!code) {
return createResponse(401, MISSING_CODE_ERROR);
}

try {
// https://docs.github.com/en/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
body: JSON.stringify({ client_id: env.GITHUB_OAUTH_ID, client_secret: env.GITHUB_OAUTH_SECRET, code }),
});
return response.json().then((result) => createResponse(response.status, result));
} catch (e) {
return createResponse(500, UNKNOWN_ERROR);
}
};
76 changes: 76 additions & 0 deletions functions/api/gitlab-oauth-callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @file gitlab auth callback
* @author netcon
*/

const AUTH_REDIRECT_URI = 'https://auth.gitlab1s.com/api/gitlab-auth-callback';

const createResponseHtml = (text: string, script: string) => `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connect to GitLab</title>
</head>
<body>
<h1>${text}</h1>
<script>${script}</script>
</body>
</html>
`;

// return the data to the opener window by postMessage API,
// and close current window if successfully connected
const createAuthorizeResultHtml = (data: Record<any, any>, origins: string) => {
const errorText = 'Failed! You can close this window and retry.';
const successText = 'Connected! You can now close this window.';
const resultStr = `{ type: 'authorizing', payload: ${JSON.stringify(data)} }`;
const script = `
'${origins}'.split(',').forEach(function(allowedOrigin) {
window.opener.postMessage(${resultStr}, allowedOrigin);
});
${data.error ? '' : 'setTimeout(() => window.close(), 50);'}`;
return createResponseHtml(data.error ? errorText : successText, script);
};

const MISSING_CODE_ERROR = {
error: 'request_invalid',
error_description: 'Missing code',
};
const UNKNOWN_ERROR = {
error: 'internal_error',
error_description: 'Unknown error',
};

export const onRequest: PagesFunction<{
GITLAB_OAUTH_ID: string;
GITLAB_OAUTH_SECRET: string;
GITLAB1S_ALLOWED_ORIGINS: string;
}> = async ({ request, env }) => {
const code = new URL(request.url).searchParams.get('code');

const createResponse = (status, data) => {
const body = createAuthorizeResultHtml(data, env.GITLAB1S_ALLOWED_ORIGINS);
return new Response(body, { status });
};

if (!code) {
return createResponse(401, MISSING_CODE_ERROR);
}

try {
// https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-flow
const response = await fetch('https://gitlab.com/oauth/token', {
method: 'POST',
body: JSON.stringify({
code,
client_id: env.GITLAB_OAUTH_ID,
client_secret: env.GITLAB_OAUTH_SECRET,
redirect_uri: AUTH_REDIRECT_URI,
grant_type: 'authorization_code',
}),
});
return response.json().then((result) => createResponse(response.status, result));
} catch (e) {
return createResponse(500, UNKNOWN_ERROR);
}
};
9 changes: 9 additions & 0 deletions functions/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"include": ["**/*"],
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"lib": ["esnext"],
"types": ["@cloudflare/workers-types"]
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
},
"devDependencies": {
"@github1s/vscode-web": "0.22.0",
"@cloudflare/workers-types": "^4.20240722.0",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"clean-css": "^5.3.2",
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const resolvePlatformState = (): [Platform, string] => {
(window as any).vscodeWeb = {
commands: vscodeCommands,
allowEditorLabelOverride: true,
additionalBuiltinExtensions: ['ms-vscode.anycode'],
additionalBuiltinExtensions: [],
webviewEndpoint: staticAssetsPrefix + '/vscode/vs/workbench/contrib/webview/browser/pre',
productConfiguration: createProductConfiguration(platform),
initialColorTheme: { themeType: 'dark' as any },
Expand Down
14 changes: 5 additions & 9 deletions src/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@ export const createProductConfiguration = (platform: Platform) => ({
applicationName: platform + '1s',
reportIssueUrl: 'https://github.com/conwnet/github1s/issues/new',
extensionsGallery: {
serviceUrl: 'https://marketplace.visualstudio.com/_apis/public/gallery',
cacheUrl: 'https://vscode.blob.core.windows.net/gallery/index',
itemUrl: 'https://marketplace.visualstudio.com/items',
resourceUrlTemplate: window.location.origin + '/api/vscode-unpkg/{publisher}/{name}/{version}/{path}',
controlUrl: 'https://az764295.vo.msecnd.net/extensions/marketplace.json',
recommendationsUrl: 'https://az764295.vo.msecnd.net/extensions/workspaceRecommendations.json.gz',
nlsBaseUrl: '',
publisherUrl: '',
resourceUrlTemplate:
'https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}',
serviceUrl: 'https://open-vsx.org/vscode/gallery',
itemUrl: 'https://open-vsx.org/vscode/item',
},
linkProtectionTrustedDomains: [
'*.github.com',
Expand All @@ -27,8 +23,8 @@ export const createProductConfiguration = (platform: Platform) => ({
'*.microsoft.com',
'*.vercel.com',
'*.sourcegraph.com',
'*.gitpod.io',
'*.ossinsight.io',
'*.open-vsx.org',
],
extensionEnabledApiProposals: { 'ms-vscode.anycode': ['extensionsAny'] },
});
2 changes: 2 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,13 @@ module.exports = (env, argv) => {
!devVscode && {
from: 'node_modules/@github1s/vscode-web/dist/vscode',
to: `static-${STATIC_HASH}/vscode`,
globOptions: { ignore: ['**/*.js.map'] },
...skipMinified,
},
!devVscode && {
from: 'node_modules/@github1s/vscode-web/dist/extensions',
to: `static-${STATIC_HASH}/extensions`,
globOptions: { ignore: ['**/*.js.map'] },
...skipMinified,
},
!devVscode && {
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
# yarn lockfile v1


"@cloudflare/workers-types@^4.20240722.0":
version "4.20240722.0"
resolved "https://registry.yarnpkg.com/@cloudflare/workers-types/-/workers-types-4.20240722.0.tgz#f5b9579fe5ff14077ae425208af6dea74249d130"
integrity sha512-/N072r7w7jNCgciRtImOQnHODn8CNwl3NHGO2lmC5bCsgevTRNeNj6B2IjS+OgEfo0qFoBgLejISl6ot9QvGvA==

"@discoveryjs/json-ext@^0.5.0":
version "0.5.7"
resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70"
Expand Down

0 comments on commit 932c504

Please sign in to comment.