Skip to content

Commit 4b7006d

Browse files
committed
Fix the build error
1 parent 0a2d642 commit 4b7006d

File tree

5 files changed

+83
-28
lines changed

5 files changed

+83
-28
lines changed

lambda/openid-configuration/index.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,19 @@ APIGatewayProxyEventV2,
1212
APIGatewayProxyResultV2 | void
1313
> = async (event, _context, callback) => {
1414
const host = event.headers.Host!;
15+
const stage = event.requestContext && event.requestContext.stage;
16+
const issuer = `https://${host}/${stage}`;
1517
const body = JSON.stringify({
16-
issuer: `https://${host}`,
17-
authorization_endpoint: `https://${host}/authorize`,
18-
token_endpoint: `https://${host}/token`,
18+
issuer,
19+
authorization_endpoint: `${issuer}//authorize`,
20+
token_endpoint: `${issuer}//token`,
1921
token_endpoint_auth_methods_supported: [
2022
'client_secret_basic',
2123
'private_key_jwt',
2224
],
2325
token_endpoint_auth_signing_alg_values_supported: ['RS256'],
24-
userinfo_endpoint: `https://${host}/userinfo`,
25-
jwks_uri: `https://${host}/.well-known/jwks.json`,
26+
userinfo_endpoint: `${issuer}//userinfo`,
27+
jwks_uri: `${issuer}//.well-known/jwks.json`,
2628
scopes_supported: ['openid', 'read:user', 'user:email'],
2729
response_types_supported: [
2830
'code',

lambda/token/index.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import {
55
} from 'aws-lambda';
66
import fetch from 'cross-fetch';
77
import { left, right, isRight } from 'fp-ts/Either';
8+
import { Logger } from '@aws-lambda-powertools/logger';
89

9-
const eventToRequest = (source: string) => {
10-
const bodyString = Buffer.from(source, 'base64').toString('ascii');
10+
const logger = new Logger();
11+
12+
const eventToRequest = (bodyString: string) => {
1113
const body = new URLSearchParams(bodyString);
1214
const paramNames = [
1315
'grant_type',
@@ -19,16 +21,16 @@ const eventToRequest = (source: string) => {
1921

2022
const invalidParams = paramNames.filter((name) => !body.has(name));
2123
if (invalidParams.length > 0) {
22-
return right(() => `token request body ${invalidParams}`);
24+
return right(() => `token request body [${invalidParams}] in [${paramNames}]. body: ${JSON.stringify(body)}`);
2325
}
2426

2527
return left(() => ({
26-
grant_type: body.get('grant_type')!,
28+
// grant_type: body.get('grant_type')!,
2729
redirect_uri: body.get('redirect_uri')!,
2830
client_id: body.get('client_id')!,
2931
client_secret: body.get('client_secret')!,
3032
code: body.get('code')!,
31-
state: body.get('state') ?? undefined,
33+
...(body.has('state') ? { state: body.get('state') } : {}),
3234
}));
3335
};
3436

@@ -37,30 +39,32 @@ APIGatewayProxyEventV2,
3739
APIGatewayProxyResultV2 | void
3840
> = async (event, _context, callback) => {
3941
if (!event.body) {
42+
logger.warn('body is undefined');
4043
callback(null, {
4144
statusCode: 400,
4245
});
4346
return;
4447
}
4548
const result = eventToRequest(event.body);
4649
if (isRight(result)) {
50+
const message = result.right();
51+
logger.warn(`cannot convert event to request. reson: ${message}, request: ${JSON.stringify(event)}`);
4752
callback(null, {
4853
statusCode: 400,
4954
body: result.right(),
5055
});
5156
return;
5257
}
53-
const body = JSON.stringify(result.left());
5458
const response = await fetch('https://github.com/login/oauth/access_token', {
5559
method: 'POST',
5660
headers: {
57-
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
61+
'Content-Type': 'application/json',
5862
Accept: 'application/json',
5963
},
60-
body,
64+
body: JSON.stringify(result.left()),
6165
});
6266
callback(null, {
63-
statusCode: 200,
67+
statusCode: response.status,
6468
body: JSON.stringify(await response.json()),
6569
});
6670
};

lambda/userinfo/index.ts

Lines changed: 57 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import fetch from 'cross-fetch';
77
import {
88
left, right, isRight, Either,
99
} from 'fp-ts/Either';
10+
import { Logger } from '@aws-lambda-powertools/logger';
11+
12+
const logger = new Logger();
1013

1114
interface Email {
1215
email: string;
@@ -15,7 +18,15 @@ interface Email {
1518
visibility?: 'private' | 'public';
1619
}
1720

18-
const getUserId = async (token: string): Promise<Either<number, string>> => {
21+
const getUser = async (token: string): Promise<Either<{
22+
id: number;
23+
name: string,
24+
login: string,
25+
html_url: string,
26+
avatar_url: string,
27+
blog: string,
28+
updated_at: string
29+
}, string>> => {
1930
const response = await fetch('https://api.github.com/user', {
2031
method: 'GET',
2132
headers: {
@@ -28,11 +39,26 @@ const getUserId = async (token: string): Promise<Either<number, string>> => {
2839
`Cannot get user ID. status: ${response.statusText}. ${response.text()}`,
2940
);
3041
}
31-
const { id } = (await response.json()) as {
42+
43+
const user = (await response.json()) as {
3244
id: number;
45+
name: string,
46+
login: string,
47+
html_url: string,
48+
avatar_url: string,
49+
blog: string,
50+
updated_at: string
3351
};
3452

35-
return left(id);
53+
return left({
54+
id: user.id,
55+
name: user.name,
56+
login: user.login,
57+
html_url: user.html_url,
58+
avatar_url: user.avatar_url,
59+
blog: user.blog,
60+
updated_at: user.updated_at,
61+
});
3662
};
3763

3864
const getValidEmail = async (token: string): Promise<Either<Email, string>> => {
@@ -55,10 +81,12 @@ const getValidEmail = async (token: string): Promise<Either<Email, string>> => {
5581
visibility?: 'private' | 'public';
5682
}[];
5783

84+
logger.info(JSON.stringify(emails));
85+
5886
const email = emails.find(
5987
(it) => it.primary
6088
&& it.verified
61-
&& it.email.trim().endsWith('noreply.github.com'),
89+
&& !it.email.trim().endsWith('noreply.github.com'),
6290
);
6391
return email ? left(email) : right('/user/emails returned no valid emails');
6492
};
@@ -70,6 +98,7 @@ APIGatewayProxyResultV2 | void
7098
const { headers } = event;
7199
const authHeader = headers.authorization || headers.Authorization;
72100
if (!authHeader) {
101+
logger.warn('/userinfo request contained no accessToken');
73102
callback(null, {
74103
statusCode: 400,
75104
body: '/userinfo request contained no accessToken',
@@ -78,6 +107,7 @@ APIGatewayProxyResultV2 | void
78107
}
79108
const authHeaderPrefix = authHeader.slice(0, 'bearer '.length);
80109
if (authHeaderPrefix.toLowerCase() !== 'bearer ') {
110+
logger.warn('authorization header does not contain bearer token');
81111
callback(null, {
82112
statusCode: 400,
83113
body: 'authorization header does not contain bearer token',
@@ -86,39 +116,52 @@ APIGatewayProxyResultV2 | void
86116
}
87117
const token = authHeader.slice('bearer '.length).trim();
88118
if (!token) {
119+
logger.warn('authorization header does not contain bearer token');
89120
callback(null, {
90121
statusCode: 400,
91122
body: 'authorization header does not contain bearer token',
92123
});
93124
}
94125

95-
const [idResult, emailResult] = await Promise.all([
96-
getUserId(token),
126+
const [userResult, emailResult] = await Promise.all([
127+
getUser(token),
97128
getValidEmail(token),
98129
]);
99-
if (isRight(idResult)) {
130+
if (isRight(userResult)) {
131+
logger.warn(userResult.right);
100132
callback(null, {
101133
statusCode: 400,
102-
body: `/userinfo ${idResult.right}`,
134+
body: `/userinfo ${userResult.right}`,
103135
});
104136
return;
105137
}
106138
if (isRight(emailResult)) {
139+
logger.warn(emailResult.right);
107140
callback(null, {
108141
statusCode: 400,
109142
body: `/userinfo ${emailResult.right}`,
110143
});
111144
return;
112145
}
113146

114-
const id = idResult.left;
147+
const user = userResult.left;
115148
const email = emailResult.left;
149+
const body = JSON.stringify({
150+
sub: user.id.toString(),
151+
name: user.name,
152+
preferred_username: user.login,
153+
profile: user.html_url,
154+
picture: user.avatar_url,
155+
website: user.blog,
156+
updated_at: new Date(Date.parse(user.updated_at)).getTime() / 1000,
157+
email: email.email,
158+
email_verified: email.verified,
159+
});
160+
161+
logger.info(body);
162+
116163
callback(null, {
117164
statusCode: 200,
118-
body: JSON.stringify({
119-
sub: id.toString(),
120-
email: email.email,
121-
email_verified: email.verified,
122-
}),
165+
body,
123166
});
124167
};

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"lint": "eslint --ext .ts lambda"
1212
},
1313
"devDependencies": {
14+
"@middy/core": "*",
1415
"@swc/core": "*",
1516
"@swc/helpers": "*",
1617
"@types/aws-lambda": "*",

yarn.lock

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@
101101
"@jridgewell/resolve-uri" "^3.0.3"
102102
"@jridgewell/sourcemap-codec" "^1.4.10"
103103

104+
"@middy/core@*":
105+
version "3.3.0"
106+
resolved "https://registry.yarnpkg.com/@middy/core/-/core-3.3.0.tgz#0342a3e130e72da0843f75ebcd6cdb37042f14c4"
107+
integrity sha512-27gn/e3lgBx5bI5yDkIdr/CWFAGmBK7M1mSQpnciak762YKyj/pABXpzj/l6SjFPxKXr9uMhUgr2qr/6s8/zow==
108+
104109
"@nodelib/fs.scandir@2.1.5":
105110
version "2.1.5"
106111
resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5"

0 commit comments

Comments
 (0)