From 3368fe855249f45bdf1e4c1e509d325d44e80fbe Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 13 Apr 2018 06:06:18 +0900 Subject: wip --- src/server/api/bot/interfaces/line.ts | 103 +++++++++++++++++----------------- 1 file changed, 51 insertions(+), 52 deletions(-) (limited to 'src/server/api/bot/interfaces') diff --git a/src/server/api/bot/interfaces/line.ts b/src/server/api/bot/interfaces/line.ts index be3bfe33d3..454630161a 100644 --- a/src/server/api/bot/interfaces/line.ts +++ b/src/server/api/bot/interfaces/line.ts @@ -1,5 +1,5 @@ import * as EventEmitter from 'events'; -import * as express from 'express'; +import * as Router from 'koa-router'; import * as request from 'request'; import * as crypto from 'crypto'; import User from '../../../../models/user'; @@ -158,82 +158,81 @@ class LineBot extends BotCore { } } -module.exports = async (app: express.Application) => { - if (config.line_bot == null) return; +const handler = new EventEmitter(); - const handler = new EventEmitter(); +handler.on('event', async (ev) => { - handler.on('event', async (ev) => { + const sourceId = ev.source.userId; + const sessionId = `line-bot-sessions:${sourceId}`; - const sourceId = ev.source.userId; - const sessionId = `line-bot-sessions:${sourceId}`; + const session = await redis.get(sessionId); + let bot: LineBot; - const session = await redis.get(sessionId); - let bot: LineBot; - - if (session == null) { - const user = await User.findOne({ - host: null, - 'line': { - userId: sourceId - } - }); + if (session == null) { + const user = await User.findOne({ + host: null, + 'line': { + userId: sourceId + } + }); - bot = new LineBot(user); + bot = new LineBot(user); - bot.on('signin', user => { - User.update(user._id, { - $set: { - 'line': { - userId: sourceId - } + bot.on('signin', user => { + User.update(user._id, { + $set: { + 'line': { + userId: sourceId } - }); + } }); + }); - bot.on('signout', user => { - User.update(user._id, { - $set: { - 'line': { - userId: null - } + bot.on('signout', user => { + User.update(user._id, { + $set: { + 'line': { + userId: null } - }); + } }); - - redis.set(sessionId, JSON.stringify(bot.export())); - } else { - bot = LineBot.import(JSON.parse(session)); - } - - bot.on('updated', () => { - redis.set(sessionId, JSON.stringify(bot.export())); }); - if (session != null) bot.refreshUser(); + redis.set(sessionId, JSON.stringify(bot.export())); + } else { + bot = LineBot.import(JSON.parse(session)); + } - bot.react(ev); + bot.on('updated', () => { + redis.set(sessionId, JSON.stringify(bot.export())); }); - app.post('/hooks/line', (req, res, next) => { - // req.headers['x-line-signature'] は常に string ですが、型定義の都合上 - // string | string[] になっているので string を明示しています - const sig1 = req.headers['x-line-signature'] as string; + if (session != null) bot.refreshUser(); + + bot.react(ev); +}); + +// Init router +const router = new Router(); + +if (config.line_bot) { + router.post('/hooks/line', ctx => { + const sig1 = ctx.headers['x-line-signature']; const hash = crypto.createHmac('SHA256', config.line_bot.channel_secret) - .update((req as any).rawBody); + .update(ctx.request.rawBody); const sig2 = hash.digest('base64'); // シグネチャ比較 if (sig1 === sig2) { - req.body.events.forEach(ev => { + ctx.body.events.forEach(ev => { handler.emit('event', ev); }); - - res.sendStatus(200); } else { - res.sendStatus(400); + ctx.status = 400; } }); -}; +} + +module.exports = router; -- cgit v1.2.3-freya From 22d2f2051c4cbe3da5b9ece674f36a6555f8c953 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 13 Apr 2018 09:44:00 +0900 Subject: wip --- src/client/app/common/mios.ts | 5 +++-- src/server/api/api-handler.ts | 16 +++++++++++++--- src/server/api/bot/interfaces/line.ts | 2 +- src/server/api/call.ts | 4 +--- src/server/api/index.ts | 4 +++- src/server/api/private/signin.ts | 6 +++--- src/server/api/private/signup.ts | 6 +++--- src/server/api/service/github.ts | 8 ++++++-- src/server/file/index.ts | 7 ++++++- src/server/file/pour.ts | 8 +------- 10 files changed, 40 insertions(+), 26 deletions(-) (limited to 'src/server/api/bot/interfaces') diff --git a/src/client/app/common/mios.ts b/src/client/app/common/mios.ts index a09af799be..ccc73eebc3 100644 --- a/src/client/app/common/mios.ts +++ b/src/client/app/common/mios.ts @@ -444,9 +444,10 @@ export default class MiOS extends EventEmitter { // Append a credential if (this.isSignedIn) (data as any).i = this.i.token; - const viaStream = localStorage.getItem('apiViaStream') ? localStorage.getItem('apiViaStream') == 'true' : true; - return new Promise((resolve, reject) => { + const viaStream = this.stream.hasConnection && + (localStorage.getItem('apiViaStream') ? localStorage.getItem('apiViaStream') == 'true' : true); + if (viaStream) { const stream = this.stream.borrow(); const id = Math.random().toString(); diff --git a/src/server/api/api-handler.ts b/src/server/api/api-handler.ts index 2c50234317..947794a20e 100644 --- a/src/server/api/api-handler.ts +++ b/src/server/api/api-handler.ts @@ -25,11 +25,21 @@ export default async (endpoint: Endpoint, ctx: Koa.Context) => { // Authentication try { - [user, app] = await authenticate(ctx.body['i']); + [user, app] = await authenticate(ctx.request.body['i']); } catch (e) { - return reply(403, 'AUTHENTICATION_FAILED'); + reply(403, 'AUTHENTICATION_FAILED'); + return; } + let res; + // API invoking - call(endpoint, user, app, ctx.body, ctx.req).then(reply).catch(e => reply(400, e)); + try { + res = await call(endpoint, user, app, ctx.request.body, ctx.req); + } catch (e) { + reply(400, e); + return; + } + + reply(res); }; diff --git a/src/server/api/bot/interfaces/line.ts b/src/server/api/bot/interfaces/line.ts index 454630161a..733315391d 100644 --- a/src/server/api/bot/interfaces/line.ts +++ b/src/server/api/bot/interfaces/line.ts @@ -226,7 +226,7 @@ if (config.line_bot) { // シグネチャ比較 if (sig1 === sig2) { - ctx.body.events.forEach(ev => { + ctx.request.body.events.forEach(ev => { handler.emit('event', ev); }); } else { diff --git a/src/server/api/call.ts b/src/server/api/call.ts index c25f55ed3f..cc40294657 100644 --- a/src/server/api/call.ts +++ b/src/server/api/call.ts @@ -6,11 +6,9 @@ import limitter from './limitter'; import { IUser } from '../../models/user'; import { IApp } from '../../models/app'; -export default (endpoint: string | Endpoint, user: IUser, app: IApp, data: any, req?: http.IncomingMessage) => new Promise(async (ok, rej) => { +export default (endpoint: string | Endpoint, user: IUser, app: IApp, data: any, req?: http.IncomingMessage) => new Promise(async (ok, rej) => { const isSecure = user != null && app == null; - //console.log(endpoint, user, app, data); - const ep = typeof endpoint == 'string' ? endpoints.find(e => e.name == endpoint) : endpoint; if (ep.secure && !isSecure) { diff --git a/src/server/api/index.ts b/src/server/api/index.ts index c383e1cf8d..2ea5fccb5b 100644 --- a/src/server/api/index.ts +++ b/src/server/api/index.ts @@ -13,7 +13,9 @@ const handler = require('./api-handler').default; // Init app const app = new Koa(); -app.use(bodyParser); +app.use(bodyParser({ + detectJSON: () => true +})); // Init multer instance const upload = multer({ diff --git a/src/server/api/private/signin.ts b/src/server/api/private/signin.ts index 55326deeaf..1737007206 100644 --- a/src/server/api/private/signin.ts +++ b/src/server/api/private/signin.ts @@ -11,9 +11,9 @@ export default async (ctx: Koa.Context) => { ctx.set('Access-Control-Allow-Origin', config.url); ctx.set('Access-Control-Allow-Credentials', 'true'); - const username = ctx.body['username']; - const password = ctx.body['password']; - const token = ctx.body['token']; + const username = ctx.request.body['username']; + const password = ctx.request.body['password']; + const token = ctx.request.body['token']; if (typeof username != 'string') { ctx.status = 400; diff --git a/src/server/api/private/signup.ts b/src/server/api/private/signup.ts index a4554be4ae..15257b869f 100644 --- a/src/server/api/private/signup.ts +++ b/src/server/api/private/signup.ts @@ -37,7 +37,7 @@ export default async (ctx: Koa.Context) => { // Verify recaptcha // ただしテスト時はこの機構は障害となるため無効にする if (process.env.NODE_ENV !== 'test') { - const success = await recaptcha(ctx.body['g-recaptcha-response']); + const success = await recaptcha(ctx.request.body['g-recaptcha-response']); if (!success) { ctx.throw(400, 'recaptcha-failed'); @@ -45,8 +45,8 @@ export default async (ctx: Koa.Context) => { } } - const username = ctx.body['username']; - const password = ctx.body['password']; + const username = ctx.request.body['username']; + const password = ctx.request.body['password']; // Validate username if (!validateUsername(username)) { diff --git a/src/server/api/service/github.ts b/src/server/api/service/github.ts index ee226cc5cc..cd9760a36d 100644 --- a/src/server/api/service/github.ts +++ b/src/server/api/service/github.ts @@ -35,10 +35,14 @@ if (config.github_bot != null) { const secret = config.github_bot.hook_secret; router.post('/hooks/github', ctx => { + const body = JSON.stringify(ctx.request.body); + const hash = crypto.createHmac('sha1', secret).update(body).digest('hex'); const sig1 = new Buffer(ctx.headers['x-hub-signature']); - const sig2 = new Buffer(`sha1=${crypto.createHmac('sha1', secret).update(JSON.stringify(ctx.body)).digest('hex')}`); + const sig2 = new Buffer(`sha1=${hash}`); + + // シグネチャ比較 if (sig1.equals(sig2)) { - handler.emit(ctx.headers['x-github-event'], ctx.body); + handler.emit(ctx.headers['x-github-event'], ctx.request.body); ctx.status = 204; } else { ctx.status = 400; diff --git a/src/server/file/index.ts b/src/server/file/index.ts index d58939f1be..d305286d12 100644 --- a/src/server/file/index.ts +++ b/src/server/file/index.ts @@ -13,6 +13,11 @@ import sendDriveFile from './send-drive-file'; const app = new Koa(); app.use(cors()); +app.use(async (ctx, next) => { + ctx.set('Cache-Control', 'max-age=31536000, immutable'); + await next(); +}); + // Init router const router = new Router(); @@ -27,7 +32,7 @@ router.get('/app-default.jpg', ctx => { }); router.get('/:id', sendDriveFile); -router.get('/:id/:name', sendDriveFile); +router.get('/:id/*', sendDriveFile); // Register router app.use(router.routes()); diff --git a/src/server/file/pour.ts b/src/server/file/pour.ts index b38b969c2d..0fd0ad0e60 100644 --- a/src/server/file/pour.ts +++ b/src/server/file/pour.ts @@ -83,12 +83,6 @@ export default function(readable: stream.Readable, type: string, ctx: Koa.Contex ctx.set('Content-Disposition', 'attachment'); } - ctx.set('Cache-Control', 'max-age=31536000, immutable'); ctx.set('Content-Type', data.contentType); - - data.stream.pipe(ctx.res); - - data.stream.on('end', () => { - ctx.res.end(); - }); + ctx.body = data.stream; } -- cgit v1.2.3-freya