summaryrefslogtreecommitdiff
path: root/packages/backend/src/server/oauth/OAuth2ProviderService.ts
blob: 45d24686de557d60028a186353038b0a7eea4de3 (plain)
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
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { bindThis } from '@/decorators.js';
import type { Config } from '@/config.js';
import { DI } from '@/di-symbols.js';
import { MastodonClientService } from '@/server/api/mastodon/MastodonClientService.js';
import { getErrorData } from '@/server/api/mastodon/MastodonLogger.js';
import { ServerUtilityService } from '@/server/ServerUtilityService.js';
import type { FastifyInstance } from 'fastify';

const kinds = [
	'read:account',
	'write:account',
	'read:blocks',
	'write:blocks',
	'read:drive',
	'write:drive',
	'read:favorites',
	'write:favorites',
	'read:following',
	'write:following',
	'read:messaging',
	'write:messaging',
	'read:mutes',
	'write:mutes',
	'write:notes',
	'read:notifications',
	'write:notifications',
	'read:reactions',
	'write:reactions',
	'write:votes',
	'read:pages',
	'write:pages',
	'write:page-likes',
	'read:page-likes',
	'read:user-groups',
	'write:user-groups',
	'read:channels',
	'write:channels',
	'read:gallery',
	'write:gallery',
	'read:gallery-likes',
	'write:gallery-likes',
];

@Injectable()
export class OAuth2ProviderService {
	constructor(
		@Inject(DI.config)
		private config: Config,

		private readonly mastodonClientService: MastodonClientService,
		private readonly serverUtilityService: ServerUtilityService,
	) { }

	// https://datatracker.ietf.org/doc/html/rfc8414.html
	// https://indieauth.spec.indieweb.org/#indieauth-server-metadata
	public generateRFC8414() {
		return {
			issuer: this.config.webUrl,
			authorization_endpoint: new URL('/oauth/authorize', this.config.webUrl),
			token_endpoint: new URL('/oauth/token', this.config.webUrl),
			scopes_supported: kinds,
			response_types_supported: ['code'],
			grant_types_supported: ['authorization_code'],
			service_documentation: 'https://misskey-hub.net',
			code_challenge_methods_supported: ['S256'],
			authorization_response_iss_parameter_supported: true,
		};
	}

	@bindThis
	public async createServer(fastify: FastifyInstance): Promise<void> {
		// https://datatracker.ietf.org/doc/html/rfc8414.html
		// https://indieauth.spec.indieweb.org/#indieauth-server-metadata
		/* fastify.get('/.well-known/oauth-authorization-server', async (_request, reply) => {
			reply.send({
				issuer: this.config.webUrl,
				authorization_endpoint: new URL('/oauth/authorize', this.config.webUrl),
				token_endpoint: new URL('/oauth/token', this.config.webUrl),
				scopes_supported: kinds,
				response_types_supported: ['code'],
				grant_types_supported: ['authorization_code'],
				service_documentation: 'https://misskey-hub.net',
				code_challenge_methods_supported: ['S256'],
				authorization_response_iss_parameter_supported: true,
			});
		}); */

		this.serverUtilityService.addMultipartFormDataContentType(fastify);
		this.serverUtilityService.addFormUrlEncodedContentType(fastify);
		this.serverUtilityService.addCORS(fastify);
		this.serverUtilityService.addFlattenedQueryType(fastify);

		for (const url of ['/authorize', '/authorize/']) {
			fastify.get<{ Querystring: Record<string, string | string[] | undefined> }>(url, async (request, reply) => {
				if (typeof(request.query.client_id) !== 'string') return reply.code(400).send({ error: 'BAD_REQUEST', error_description: 'Missing required query "client_id"' });

				const redirectUri = new URL(Buffer.from(request.query.client_id, 'base64').toString());
				redirectUri.searchParams.set('mastodon', 'true');
				if (request.query.state) redirectUri.searchParams.set('state', String(request.query.state));
				if (request.query.redirect_uri) redirectUri.searchParams.set('redirect_uri', String(request.query.redirect_uri));

				return reply.redirect(redirectUri.toString());
			});
		}

		fastify.post<{ Body?: Record<string, string | string[] | undefined>, Querystring: Record<string, string | string[] | undefined> }>('/token', async (request, reply) => {
			const body = request.body ?? request.query;

			if (body.grant_type === 'client_credentials') {
				const ret = {
					access_token: uuid(),
					token_type: 'Bearer',
					scope: 'read',
					created_at: Math.floor(new Date().getTime() / 1000),
				};
				return reply.send(ret);
			}

			try {
				if (!body.client_secret) return reply.code(400).send({ error: 'BAD_REQUEST', error_description: 'Missing required query "client_secret"' });

				const clientId = body.client_id ? String(body.clientId) : null;
				const secret = String(body.client_secret);
				const code = body.code ? String(body.code) : '';

				// TODO fetch the access token directly, then remove all oauth code from megalodon
				const client = this.mastodonClientService.getClient(request);
				const atData = await client.fetchAccessToken(clientId, secret, code);

				const ret = {
					access_token: atData.accessToken,
					token_type: 'Bearer',
					scope: atData.scope || body.scope || 'read write follow push',
					created_at: atData.createdAt || Math.floor(new Date().getTime() / 1000),
				};
				return reply.send(ret);
			} catch (e: unknown) {
				const data = getErrorData(e);
				return reply.code(401).send(data);
			}
		});
	}
}