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
|
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import querystring from 'querystring';
import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
/* import { kinds } from '@/misc/api-permissions.js';
import type { Config } from '@/config.js';
import { DI } from '@/di-symbols.js'; */
import multer from 'fastify-multer';
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 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,
) { }
// https://datatracker.ietf.org/doc/html/rfc8414.html
// https://indieauth.spec.indieweb.org/#indieauth-server-metadata
public generateRFC8414() {
return {
issuer: this.config.url,
authorization_endpoint: new URL('/oauth/authorize', this.config.url),
token_endpoint: new URL('/oauth/token', this.config.url),
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.url,
authorization_endpoint: new URL('/oauth/authorize', this.config.url),
token_endpoint: new URL('/oauth/token', this.config.url),
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,
});
}); */
const upload = multer({
storage: multer.diskStorage({}),
limits: {
fileSize: this.config.maxFileSize || 262144000,
files: 1,
},
});
fastify.addHook('onRequest', (request, reply, done) => {
reply.header('Access-Control-Allow-Origin', '*');
done();
});
fastify.addContentTypeParser('application/x-www-form-urlencoded', (request, payload, done) => {
let body = '';
payload.on('data', (data) => {
body += data;
});
payload.on('end', () => {
try {
const parsed = querystring.parse(body);
done(null, parsed);
} catch (e: unknown) {
done(e instanceof Error ? e : new Error(String(e)));
}
});
payload.on('error', done);
});
fastify.register(multer.contentParser);
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));
reply.redirect(redirectUri.toString());
});
}
fastify.post<{ Body?: Record<string, string | string[] | undefined>, Querystring: Record<string, string | string[] | undefined> }>('/token', { preHandler: upload.none() }, 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),
};
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
const client = this.mastodonClientService.getClient(request);
const atData = await client.fetchAccessToken(clientId, secret, code);
const ret = {
access_token: atData.accessToken,
token_type: 'Bearer',
scope: body.scope || 'read write follow push',
created_at: Math.floor(new Date().getTime() / 1000),
};
reply.send(ret);
} catch (e: unknown) {
const data = getErrorData(e);
reply.code(401).send(data);
}
});
}
}
|