From 608b8bb74142c52e78f53afc1bbc340b85dfa2d4 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 27 Mar 2020 20:24:32 +0900 Subject: wip --- src/server/api/openapi/description.ts | 47 +---------------------------------- 1 file changed, 1 insertion(+), 46 deletions(-) (limited to 'src/server/api') diff --git a/src/server/api/openapi/description.ts b/src/server/api/openapi/description.ts index a4b79d9502..4fff53ac90 100644 --- a/src/server/api/openapi/description.ts +++ b/src/server/api/openapi/description.ts @@ -42,52 +42,7 @@ export function getDescription(lang = 'ja-JP'): string { .join('\n'); const descriptions = { - 'ja-JP': `**Misskey is a decentralized microblogging platform.** - -# Usage -**APIはすべてPOSTでリクエスト/レスポンスともにJSON形式です。** -一部のAPIはリクエストに認証情報(APIキー)が必要です。リクエストの際に\`i\`というパラメータでAPIキーを添付してください。 - -## 自分のアカウントのAPIキーを取得する -「設定 > API」で、自分のAPIキーを取得できます。 - -> アカウントを不正利用される可能性があるため、このトークンは第三者に教えないでください(アプリなどにも入力しないでください)。 - -## アプリケーションとしてAPIキーを取得する -直接ユーザーのAPIキーをアプリケーションが扱うのはセキュリティ上のリスクがあるので、 -アプリケーションからAPIを利用する際には、アプリケーションとアプリケーションを利用するユーザーが結び付けられた専用のAPIキーを発行します。 - -### 1.アプリケーションを登録する -まず、あなたのアプリケーションやWebサービス(以後、あなたのアプリと呼びます)をMisskeyに登録します。 -[デベロッパーセンター](/dev)にアクセスし、「アプリ > アプリ作成」からアプリを作成してください。 - -登録が済むとあなたのアプリのシークレットキーが入手できます。このシークレットキーは後で使用します。 - -> アプリに成りすまされる可能性があるため、極力このシークレットキーは公開しないようにしてください。

- -### 2.ユーザーに認証させる -アプリを使ってもらうには、ユーザーにアカウントへのアクセスの許可をもらう必要があります。 - -認証セッションを開始するには、[${config.apiUrl}/auth/session/generate](#operation/auth/session/generate) へパラメータに\`appSecret\`としてシークレットキーを含めたリクエストを送信します。 -レスポンスとして認証セッションのトークンや認証フォームのURLが取得できるので、認証フォームのURLをブラウザで表示し、ユーザーにフォームを提示してください。 - -あなたのアプリがコールバックURLを設定している場合、 -ユーザーがあなたのアプリの連携を許可すると設定しているコールバックURLに\`token\`という名前でセッションのトークンが含まれたクエリを付けてリダイレクトします。 - -あなたのアプリがコールバックURLを設定していない場合、ユーザーがあなたのアプリの連携を許可したことを(何らかの方法で(たとえばボタンを押させるなど))確認出来るようにしてください。 - -### 3.アクセストークンを取得する -ユーザーが連携を許可したら、[${config.apiUrl}/auth/session/userkey](#operation/auth/session/userkey) へリクエストを送信します。 - -上手くいけば、認証したユーザーのアクセストークンがレスポンスとして取得できます。おめでとうございます! - -アクセストークンが取得できたら、*「ユーザーのアクセストークン+あなたのアプリのシークレットキーをsha256したもの」*をAPIキーとして、APIにリクエストできます。 - -APIキーの生成方法を擬似コードで表すと次のようになります: -\`\`\` js -const i = sha256(userToken + secretKey); -\`\`\` - + 'ja-JP': ` # Permissions |Permisson (kind)|Description|Endpoints| |:--|:--|:--| -- cgit v1.2.3-freya From 6be127e18bdbea6031698baeb8632f917a8346eb Mon Sep 17 00:00:00 2001 From: syuilo Date: Sat, 28 Mar 2020 11:24:37 +0900 Subject: Implement MiAuth --- locales/ja-JP.yml | 4 ++ migration/1585361548360-miauth.ts | 36 ++++++++++ src/client/pages/auth.vue | 8 +-- src/client/pages/doc.vue | 4 ++ src/client/pages/miauth.vue | 99 ++++++++++++++++++++++++++ src/client/router.ts | 1 + src/docs/api.ja-JP.md | 32 ++++----- src/models/entities/access-token.ts | 54 +++++++++++++- src/server/api/authenticate.ts | 24 +++++-- src/server/api/call.ts | 7 +- src/server/api/define.ts | 9 ++- src/server/api/endpoints/app/show.ts | 4 +- src/server/api/endpoints/drive/files/create.ts | 2 +- src/server/api/endpoints/i.ts | 4 +- src/server/api/endpoints/i/update.ts | 4 +- src/server/api/endpoints/miauth/gen-token.ts | 54 ++++++++++++++ src/server/api/endpoints/notes/create.ts | 3 +- src/server/api/index.ts | 24 ++++++- src/server/api/stream/index.ts | 5 +- 19 files changed, 330 insertions(+), 48 deletions(-) create mode 100644 migration/1585361548360-miauth.ts create mode 100644 src/client/pages/miauth.vue create mode 100644 src/server/api/endpoints/miauth/gen-token.ts (limited to 'src/server/api') diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index 40772f9b1f..4650f03a29 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -568,7 +568,11 @@ _permissions: _auth: shareAccess: "「{name}」がアカウントにアクセスすることを許可しますか?" + shareAccessAsk: "アカウントへのアクセスを許可しますか?" permissionAsk: "このアプリは次の権限を要求しています" + pleaseGoBack: "アプリケーションに戻ってやっていってください" + callback: "アプリケーションに戻っています" + denied: "アクセスを拒否しました" _antennaSources: all: "全てのノート" diff --git a/migration/1585361548360-miauth.ts b/migration/1585361548360-miauth.ts new file mode 100644 index 0000000000..22d6c207ff --- /dev/null +++ b/migration/1585361548360-miauth.ts @@ -0,0 +1,36 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +export class miauth1585361548360 implements MigrationInterface { + name = 'miauth1585361548360' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "access_token" ADD "lastUsedAt" TIMESTAMP WITH TIME ZONE DEFAULT null`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "session" character varying(128) DEFAULT null`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "name" character varying(128) DEFAULT null`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "description" character varying(512) DEFAULT null`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "iconUrl" character varying(512) DEFAULT null`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "permission" character varying(64) array NOT NULL DEFAULT '{}'::varchar[]`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD "fetched" boolean NOT NULL DEFAULT false`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP CONSTRAINT "FK_a3ff16c90cc87a82a0b5959e560"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ALTER COLUMN "appId" DROP NOT NULL`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ALTER COLUMN "appId" SET DEFAULT null`, undefined); + await queryRunner.query(`CREATE INDEX "IDX_bf3a053c07d9fb5d87317c56ee" ON "access_token" ("session") `, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD CONSTRAINT "FK_a3ff16c90cc87a82a0b5959e560" FOREIGN KEY ("appId") REFERENCES "app"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, undefined); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "access_token" DROP CONSTRAINT "FK_a3ff16c90cc87a82a0b5959e560"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_bf3a053c07d9fb5d87317c56ee"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ALTER COLUMN "appId" DROP DEFAULT`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ALTER COLUMN "appId" SET NOT NULL`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" ADD CONSTRAINT "FK_a3ff16c90cc87a82a0b5959e560" FOREIGN KEY ("appId") REFERENCES "app"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "fetched"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "permission"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "iconUrl"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "description"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "name"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "session"`, undefined); + await queryRunner.query(`ALTER TABLE "access_token" DROP COLUMN "lastUsedAt"`, undefined); + } + +} diff --git a/src/client/pages/auth.vue b/src/client/pages/auth.vue index 9f5b45f001..e025924fe0 100755 --- a/src/client/pages/auth.vue +++ b/src/client/pages/auth.vue @@ -12,20 +12,18 @@ @accepted="accepted" />
-

{{ $t('denied') }}

-

{{ $t('denied-paragraph') }}

+

{{ $t('_auth.denied') }}

{{ session.app.isAuthorized ? this.$t('already-authorized') : this.$t('allowed') }}

-

{{ $t('callback-url') }}

-

{{ $t('please-go-back') }}

+

{{ $t('_auth.callback') }}

+

{{ $t('_auth.pleaseGoBack') }}

{{ $t('error') }}

diff --git a/src/client/pages/doc.vue b/src/client/pages/doc.vue index 5cdb5999ba..8d1ba4bd73 100644 --- a/src/client/pages/doc.vue +++ b/src/client/pages/doc.vue @@ -118,6 +118,10 @@ export default Vue.extend({ margin-bottom: 0; } + ::v-deep a { + color: var(--link); + } + ::v-deep h2 { font-size: 1.25em; padding: 0 0 0.5em 0; diff --git a/src/client/pages/miauth.vue b/src/client/pages/miauth.vue new file mode 100644 index 0000000000..7d7e363d39 --- /dev/null +++ b/src/client/pages/miauth.vue @@ -0,0 +1,99 @@ + + + + + diff --git a/src/client/router.ts b/src/client/router.ts index 83445fea7e..70d497d36f 100644 --- a/src/client/router.ts +++ b/src/client/router.ts @@ -58,6 +58,7 @@ export const router = new VueRouter({ { path: '/notes/:note', name: 'note', component: page('note') }, { path: '/tags/:tag', component: page('tag') }, { path: '/auth/:token', component: page('auth') }, + { path: '/miauth/:session', component: page('miauth') }, { path: '/authorize-follow', component: page('follow') }, { path: '/share', component: page('share') }, { path: '*', component: page('not-found') } diff --git a/src/docs/api.ja-JP.md b/src/docs/api.ja-JP.md index 5d370a29cd..f47aeb81cf 100644 --- a/src/docs/api.ja-JP.md +++ b/src/docs/api.ja-JP.md @@ -3,25 +3,25 @@ MisskeyAPIを使ってMisskeyクライアント、Misskey連携Webサービス、Bot等(以下「アプリケーション」と呼びます)を開発できます。 ストリーミングAPIもあるので、リアルタイム性のあるアプリケーションを作ることも可能です。 -APIを使い始めるには、まずAPIキーを取得する必要があります。 -このドキュメントでは、APIキーを取得する手順を説明した後、基本的なAPIの使い方を説明します。 +APIを使い始めるには、まずアクセストークンを取得する必要があります。 +このドキュメントでは、アクセストークンを取得する手順を説明した後、基本的なAPIの使い方を説明します。 -## APIキーの取得 -基本的に、APIはリクエストにはAPIキーが必要となります。 -あなたの作ろうとしているアプリケーションが、あなた専用のものなのか、それとも不特定多数の人に使ってもらうものなのかによって、APIキーの取得手順は異なります。 +## アクセストークンの取得 +基本的に、APIはリクエストにはアクセストークンが必要となります。 +あなたの作ろうとしているアプリケーションが、あなた専用のものなのか、それとも不特定多数の人に使ってもらうものなのかによって、アクセストークンの取得手順は異なります。 -* あなた専用の場合: [「自分のアカウントのAPIキーを取得する」](#自分のアカウントのAPIキーを取得する)に進む -* 皆に使ってもらう場合: [「アプリケーションとしてAPIキーを取得する」](#アプリケーションとしてAPIキーを取得する)に進む +* あなた専用の場合: [「自分のアカウントのアクセストークンを取得する」](#自分のアカウントのアクセストークンを取得する)に進む +* 皆に使ってもらう場合: [「アプリケーションとしてアクセストークンを取得する」](#アプリケーションとしてアクセストークンを取得する)に進む -### 自分のアカウントのAPIキーを取得する -「設定 > API」で、自分のAPIキーを取得できます。 +### 自分のアカウントのアクセストークンを取得する +「設定 > API」で、自分のアクセストークンを取得できます。 -> この方法で入手したAPIキーは強力なので、第三者に教えないでください(アプリなどにも入力しないでください)。 +> この方法で入手したアクセストークンは強力なので、第三者に教えないでください(アプリなどにも入力しないでください)。 [「APIの使い方」へ進む](#APIの使い方) -### アプリケーションとしてAPIキーを取得する -アプリケーションを使ってもらうには、ユーザーのAPIキーを以下の手順で取得する必要があります。 +### アプリケーションとしてアクセストークンを取得する +アプリケーションを使ってもらうには、ユーザーのアクセストークンを以下の手順で取得する必要があります。 #### Step 1 @@ -38,23 +38,23 @@ UUIDを生成する。以後これをセッションIDと呼びます。 * `callback` ... 認証が終わった後にリダイレクトするURL * > 例: `https://missdeck.example.com/callback` * リダイレクト時には、`session`というクエリパラメータでセッションIDが付きます -* `permissions` ... アプリケーションが要求する権限 +* `permission` ... アプリケーションが要求する権限 * > 例: `write:notes,write:following,read:drive` * 要求する権限を`,`で区切って列挙します * どのような権限があるかは[APIリファレンス](/api-doc)で確認できます #### Step 3 -ユーザーが連携を許可した後、`{_URL_}/miauth/{session}/check`にPOSTリクエストすると、レスポンスとしてAPIキーを含むJSONが返ります。 +ユーザーが連携を許可した後、`{_URL_}/miauth/{session}/check`にPOSTリクエストすると、レスポンスとしてアクセストークンを含むJSONが返ります。 レスポンスに含まれるプロパティ: -* `token` ... ユーザーのAPIキー +* `token` ... ユーザーのアクセストークン * `user` ... ユーザーの情報 [「APIの使い方」へ進む](#APIの使い方) ## APIの使い方 **APIはすべてPOSTで、リクエスト/レスポンスともにJSON形式です。RESTではありません。** -APIキーは、`i`というパラメータ名でリクエストに含めます。 +アクセストークンは、`i`というパラメータ名でリクエストに含めます。 * [APIリファレンス](/api-doc) * [ストリーミングAPI](./stream) diff --git a/src/models/entities/access-token.ts b/src/models/entities/access-token.ts index 137bf1444d..5f41b3c1fc 100644 --- a/src/models/entities/access-token.ts +++ b/src/models/entities/access-token.ts @@ -13,12 +13,26 @@ export class AccessToken { }) public createdAt: Date; + @Column('timestamp with time zone', { + nullable: true, + default: null, + }) + public lastUsedAt: Date | null; + @Index() @Column('varchar', { length: 128 }) public token: string; + @Index() + @Column('varchar', { + length: 128, + nullable: true, + default: null + }) + public session: string | null; + @Index() @Column('varchar', { length: 128 @@ -35,12 +49,48 @@ export class AccessToken { @JoinColumn() public user: User | null; - @Column(id()) - public appId: App['id']; + @Column({ + ...id(), + nullable: true, + default: null + }) + public appId: App['id'] | null; @ManyToOne(type => App, { onDelete: 'CASCADE' }) @JoinColumn() public app: App | null; + + @Column('varchar', { + length: 128, + nullable: true, + default: null + }) + public name: string | null; + + @Column('varchar', { + length: 512, + nullable: true, + default: null + }) + public description: string | null; + + @Column('varchar', { + length: 512, + nullable: true, + default: null + }) + public iconUrl: string | null; + + @Column('varchar', { + length: 64, array: true, + default: '{}' + }) + public permission: string[]; + + @Column('boolean', { + default: false + }) + public fetched: boolean; } diff --git a/src/server/api/authenticate.ts b/src/server/api/authenticate.ts index 519ed77388..32ad3b4019 100644 --- a/src/server/api/authenticate.ts +++ b/src/server/api/authenticate.ts @@ -1,7 +1,11 @@ import isNativeToken from './common/is-native-token'; import { User } from '../../models/entities/user'; -import { App } from '../../models/entities/app'; import { Users, AccessTokens, Apps } from '../../models'; +import { ensure } from '../../prelude/ensure'; + +type App = { + permission: string[]; +}; export default async (token: string): Promise<[User | null | undefined, App | null | undefined]> => { if (token == null) { @@ -27,14 +31,26 @@ export default async (token: string): Promise<[User | null | undefined, App | nu throw new Error('invalid signature'); } - const app = await Apps - .findOne(accessToken.appId); + AccessTokens.update(accessToken.id, { + lastUsedAt: new Date(), + }); const user = await Users .findOne({ id: accessToken.userId // findOne(accessToken.userId) のように書かないのは後方互換性のため }); - return [user, app]; + if (accessToken.appId) { + const app = await Apps + .findOne(accessToken.appId).then(ensure); + + return [user, { + permission: app.permission + }]; + } else { + return [user, { + permission: accessToken.permission + }]; + } } }; diff --git a/src/server/api/call.ts b/src/server/api/call.ts index 37bcf7ce16..c75006ef31 100644 --- a/src/server/api/call.ts +++ b/src/server/api/call.ts @@ -4,7 +4,10 @@ import { User } from '../../models/entities/user'; import endpoints from './endpoints'; import { ApiError } from './error'; import { apiLogger } from './logger'; -import { App } from '../../models/entities/app'; + +type App = { + permission: string[]; +}; const accessDenied = { message: 'Access denied.', @@ -73,7 +76,7 @@ export default async (endpoint: string, user: User | null | undefined, app: App // API invoking const before = performance.now(); - return await ep.exec(data, user, app, file).catch((e: Error) => { + return await ep.exec(data, user, isSecure, file).catch((e: Error) => { if (e instanceof ApiError) { throw e; } else { diff --git a/src/server/api/define.ts b/src/server/api/define.ts index 1fd4543bd0..3c9e6863b7 100644 --- a/src/server/api/define.ts +++ b/src/server/api/define.ts @@ -2,7 +2,6 @@ import * as fs from 'fs'; import { ILocalUser } from '../../models/entities/user'; import { IEndpointMeta } from './endpoints'; import { ApiError } from './error'; -import { App } from '../../models/entities/app'; import { SchemaType } from '../../misc/schema'; // TODO: defaultが設定されている場合はその型も考慮する @@ -15,12 +14,12 @@ type Params = { export type Response = Record | void; type executor = - (params: Params, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, app: App, file?: any, cleanup?: Function) => + (params: Params, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any, cleanup?: Function) => Promise>>; export default function (meta: T, cb: executor) - : (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, app: App, file?: any) => Promise { - return (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, app: App, file?: any) => { + : (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any) => Promise { + return (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any) => { function cleanup() { fs.unlink(file.path, () => {}); } @@ -37,7 +36,7 @@ export default function (meta: T, cb: executor) return Promise.reject(pserr); } - return cb(ps, user, app, file, cleanup); + return cb(ps, user, isSecure, file, cleanup); }; } diff --git a/src/server/api/endpoints/app/show.ts b/src/server/api/endpoints/app/show.ts index 2c8cdbe396..c1bbb2c53e 100644 --- a/src/server/api/endpoints/app/show.ts +++ b/src/server/api/endpoints/app/show.ts @@ -28,9 +28,7 @@ export const meta = { } }; -export default define(meta, async (ps, user, app) => { - const isSecure = user != null && app == null; - +export default define(meta, async (ps, user, isSecure) => { // Lookup app const ap = await Apps.findOne(ps.appId); diff --git a/src/server/api/endpoints/drive/files/create.ts b/src/server/api/endpoints/drive/files/create.ts index 3c5c982534..5043fbb8e7 100644 --- a/src/server/api/endpoints/drive/files/create.ts +++ b/src/server/api/endpoints/drive/files/create.ts @@ -78,7 +78,7 @@ export const meta = { } }; -export default define(meta, async (ps, user, app, file, cleanup) => { +export default define(meta, async (ps, user, isSecure, file, cleanup) => { // Get 'name' parameter let name = ps.name || file.originalname; if (name !== undefined && name !== null) { diff --git a/src/server/api/endpoints/i.ts b/src/server/api/endpoints/i.ts index d22de40c69..3909d54663 100644 --- a/src/server/api/endpoints/i.ts +++ b/src/server/api/endpoints/i.ts @@ -19,9 +19,7 @@ export const meta = { }, }; -export default define(meta, async (ps, user, app) => { - const isSecure = user != null && app == null; - +export default define(meta, async (ps, user, isSecure) => { return await Users.pack(user, user, { detail: true, includeHasUnreadNotes: true, diff --git a/src/server/api/endpoints/i/update.ts b/src/server/api/endpoints/i/update.ts index 5c4a9576e1..0a3ba824ae 100644 --- a/src/server/api/endpoints/i/update.ts +++ b/src/server/api/endpoints/i/update.ts @@ -178,9 +178,7 @@ export const meta = { } }; -export default define(meta, async (ps, user, app) => { - const isSecure = user != null && app == null; - +export default define(meta, async (ps, user, isSecure) => { const updates = {} as Partial; const profileUpdates = {} as Partial; diff --git a/src/server/api/endpoints/miauth/gen-token.ts b/src/server/api/endpoints/miauth/gen-token.ts new file mode 100644 index 0000000000..599ecf477e --- /dev/null +++ b/src/server/api/endpoints/miauth/gen-token.ts @@ -0,0 +1,54 @@ +import rndstr from 'rndstr'; +import $ from 'cafy'; +import define from '../../define'; +import { AccessTokens } from '../../../../models'; +import { genId } from '../../../../misc/gen-id'; + +export const meta = { + tags: ['auth'], + + requireCredential: true as const, + + secure: true, + + params: { + session: { + validator: $.str + }, + + name: { + validator: $.nullable.optional.str + }, + + description: { + validator: $.nullable.optional.str, + }, + + iconUrl: { + validator: $.nullable.optional.str, + }, + + permission: { + validator: $.arr($.str).unique(), + }, + }, +}; + +export default define(meta, async (ps, user) => { + // Generate access token + const accessToken = rndstr('a-zA-Z0-9', 32); + + // Insert access token doc + await AccessTokens.save({ + id: genId(), + createdAt: new Date(), + session: ps.session, + userId: user.id, + token: accessToken, + hash: accessToken, + name: ps.name, + description: ps.description, + iconUrl: ps.iconUrl, + permission: ps.permission, + }); +}); diff --git a/src/server/api/endpoints/notes/create.ts b/src/server/api/endpoints/notes/create.ts index e983ad6fd6..cccf138add 100644 --- a/src/server/api/endpoints/notes/create.ts +++ b/src/server/api/endpoints/notes/create.ts @@ -209,7 +209,7 @@ export const meta = { } }; -export default define(meta, async (ps, user, app) => { +export default define(meta, async (ps, user) => { let visibleUsers: User[] = []; if (ps.visibleUserIds) { visibleUsers = (await Promise.all(ps.visibleUserIds.map(id => Users.findOne(id)))) @@ -281,7 +281,6 @@ export default define(meta, async (ps, user, app) => { reply, renote, cw: ps.cw, - app, viaMobile: ps.viaMobile, localOnly: ps.localOnly, visibility: ps.visibility, diff --git a/src/server/api/index.ts b/src/server/api/index.ts index 258e632bd8..49209ede43 100644 --- a/src/server/api/index.ts +++ b/src/server/api/index.ts @@ -15,7 +15,7 @@ import signin from './private/signin'; import discord from './service/discord'; import github from './service/github'; import twitter from './service/twitter'; -import { Instances } from '../../models'; +import { Instances, AccessTokens, Users } from '../../models'; // Init app const app = new Koa(); @@ -73,6 +73,28 @@ router.get('/v1/instance/peers', async ctx => { ctx.body = instances.map(instance => instance.host); }); +router.post('/miauth/:session/check', async ctx => { + const token = await AccessTokens.findOne({ + session: ctx.params.session + }); + + if (token && !token.fetched) { + AccessTokens.update(token.id, { + fetched: true + }); + + ctx.body = { + ok: true, + token: token.token, + user: await Users.pack(token.userId, null, { detail: true }) + }; + } else { + ctx.body = { + ok: false, + }; + } +}); + // Return 404 for unknown API router.all('*', async ctx => { ctx.status = 404; diff --git a/src/server/api/stream/index.ts b/src/server/api/stream/index.ts index 463ae0a601..4b233b9a8b 100644 --- a/src/server/api/stream/index.ts +++ b/src/server/api/stream/index.ts @@ -7,10 +7,13 @@ import Channel from './channel'; import channels from './channels'; import { EventEmitter } from 'events'; import { User } from '../../../models/entities/user'; -import { App } from '../../../models/entities/app'; import { Users, Followings, Mutings } from '../../../models'; import { ApiError } from '../error'; +type App = { + permission: string[]; +}; + /** * Main stream connection */ -- cgit v1.2.3-freya From 9ea1ed855931039142affd9635670c0c065dce75 Mon Sep 17 00:00:00 2001 From: syuilo Date: Sat, 28 Mar 2020 16:52:52 +0900 Subject: Add i/apps private API --- src/server/api/endpoints/i/apps.ts | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/server/api/endpoints/i/apps.ts (limited to 'src/server/api') diff --git a/src/server/api/endpoints/i/apps.ts b/src/server/api/endpoints/i/apps.ts new file mode 100644 index 0000000000..38299cd0dc --- /dev/null +++ b/src/server/api/endpoints/i/apps.ts @@ -0,0 +1,41 @@ +import $ from 'cafy'; +import define from '../../define'; +import { AccessTokens } from '../../../../models'; + +export const meta = { + requireCredential: true as const, + + secure: true, + + params: { + sort: { + validator: $.optional.str.or([ + '+createdAt', + '-createdAt', + '+lastUsedAt', + '-lastUsedAt', + ]), + }, + } +}; + +export default define(meta, async (ps, user) => { + const query = AccessTokens.createQueryBuilder('token'); + + switch (ps.sort) { + case '+createdAt': query.orderBy('token.createdAt', 'DESC'); break; + case '-createdAt': query.orderBy('token.createdAt', 'ASC'); break; + case '+lastUsedAt': query.andWhere('token.lastUsedAt IS NOT NULL').orderBy('token.lastUsedAt', 'DESC'); break; + case '-lastUsedAt': query.andWhere('token.lastUsedAt IS NOT NULL').orderBy('token.lastUsedAt', 'ASC'); break; + default: query.orderBy('token.id', 'ASC'); break; + } + + const tokens = await query.getMany(); + + return await Promise.all(tokens.map(token => ({ + id: token.id, + name: token.name, + createdAt: token.createdAt, + lastUsedAt: token.lastUsedAt, + }))); +}); -- cgit v1.2.3-freya From 614a1d74ddf388dcb82f69722c96696ad530602d Mon Sep 17 00:00:00 2001 From: syuilo Date: Sat, 28 Mar 2020 18:07:41 +0900 Subject: Resolve #6192 --- migration/1585385921215-custom-notification.ts | 48 ++++++++++++++++++++ src/client/components/notification.vue | 35 ++++++++------ src/models/entities/notification.ts | 58 ++++++++++++++++++++++-- src/models/repositories/notification.ts | 10 +++- src/server/api/authenticate.ts | 14 ++---- src/server/api/call.ts | 13 ++---- src/server/api/define.ts | 9 ++-- src/server/api/endpoints/app/show.ts | 4 +- src/server/api/endpoints/drive/files/create.ts | 2 +- src/server/api/endpoints/i.ts | 4 +- src/server/api/endpoints/i/update.ts | 4 +- src/server/api/endpoints/notes/polls/vote.ts | 6 ++- src/server/api/endpoints/notifications/create.ts | 37 +++++++++++++++ src/server/api/endpoints/users/groups/invite.ts | 3 +- src/server/api/stream/index.ts | 13 ++---- src/services/create-notification.ts | 34 +++----------- src/services/following/create.ts | 8 +++- src/services/following/requests/create.ts | 3 +- src/services/note/create.ts | 3 +- src/services/note/polls/vote.ts | 6 ++- src/services/note/reaction/create.ts | 6 ++- 21 files changed, 229 insertions(+), 91 deletions(-) create mode 100644 migration/1585385921215-custom-notification.ts create mode 100644 src/server/api/endpoints/notifications/create.ts (limited to 'src/server/api') diff --git a/migration/1585385921215-custom-notification.ts b/migration/1585385921215-custom-notification.ts new file mode 100644 index 0000000000..24c29d53e5 --- /dev/null +++ b/migration/1585385921215-custom-notification.ts @@ -0,0 +1,48 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +export class customNotification1585385921215 implements MigrationInterface { + name = 'customNotification1585385921215' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "notification" ADD "customBody" character varying(2048)`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD "customHeader" character varying(256)`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD "customIcon" character varying(1024)`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD "appAccessTokenId" character varying(32)`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP CONSTRAINT "FK_3b4e96eec8d36a8bbb9d02aa710"`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ALTER COLUMN "notifierId" DROP NOT NULL`, undefined); + await queryRunner.query(`COMMENT ON COLUMN "notification"."notifierId" IS 'The ID of sender user of the Notification.'`, undefined); + await queryRunner.query(`ALTER TYPE "public"."notification_type_enum" RENAME TO "notification_type_enum_old"`, undefined); + await queryRunner.query(`CREATE TYPE "notification_type_enum" AS ENUM('follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited', 'app')`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ALTER COLUMN "type" TYPE "notification_type_enum" USING "type"::"text"::"notification_type_enum"`, undefined); + await queryRunner.query(`DROP TYPE "notification_type_enum_old"`, undefined); + await queryRunner.query(`COMMENT ON COLUMN "notification"."type" IS 'The type of the Notification.'`, undefined); + await queryRunner.query(`CREATE INDEX "IDX_3b4e96eec8d36a8bbb9d02aa71" ON "notification" ("notifierId") `, undefined); + await queryRunner.query(`CREATE INDEX "IDX_33f33cc8ef29d805a97ff4628b" ON "notification" ("type") `, undefined); + await queryRunner.query(`CREATE INDEX "IDX_080ab397c379af09b9d2169e5b" ON "notification" ("isRead") `, undefined); + await queryRunner.query(`CREATE INDEX "IDX_e22bf6bda77b6adc1fd9e75c8c" ON "notification" ("appAccessTokenId") `, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD CONSTRAINT "FK_3b4e96eec8d36a8bbb9d02aa710" FOREIGN KEY ("notifierId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD CONSTRAINT "FK_e22bf6bda77b6adc1fd9e75c8c9" FOREIGN KEY ("appAccessTokenId") REFERENCES "access_token"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, undefined); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "notification" DROP CONSTRAINT "FK_e22bf6bda77b6adc1fd9e75c8c9"`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP CONSTRAINT "FK_3b4e96eec8d36a8bbb9d02aa710"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_e22bf6bda77b6adc1fd9e75c8c"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_080ab397c379af09b9d2169e5b"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_33f33cc8ef29d805a97ff4628b"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_3b4e96eec8d36a8bbb9d02aa71"`, undefined); + await queryRunner.query(`COMMENT ON COLUMN "notification"."type" IS ''`, undefined); + await queryRunner.query(`CREATE TYPE "notification_type_enum_old" AS ENUM('follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited')`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ALTER COLUMN "type" TYPE "notification_type_enum_old" USING "type"::"text"::"notification_type_enum_old"`, undefined); + await queryRunner.query(`DROP TYPE "notification_type_enum"`, undefined); + await queryRunner.query(`ALTER TYPE "notification_type_enum_old" RENAME TO "notification_type_enum"`, undefined); + await queryRunner.query(`COMMENT ON COLUMN "notification"."notifierId" IS ''`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ALTER COLUMN "notifierId" SET NOT NULL`, undefined); + await queryRunner.query(`ALTER TABLE "notification" ADD CONSTRAINT "FK_3b4e96eec8d36a8bbb9d02aa710" FOREIGN KEY ("notifierId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "appAccessTokenId"`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "customIcon"`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "customHeader"`, undefined); + await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "customBody"`, undefined); + } + +} diff --git a/src/client/components/notification.vue b/src/client/components/notification.vue index d768c0b074..f415887e76 100644 --- a/src/client/components/notification.vue +++ b/src/client/components/notification.vue @@ -1,22 +1,24 @@ @@ -142,14 +147,14 @@ export default Vue.extend({ height: 42px; margin-right: 8px; - > .avatar { + > .icon { display: block; width: 100%; height: 100%; border-radius: 6px; } - > .icon { + > .sub-icon { position: absolute; z-index: 1; bottom: -2px; @@ -163,6 +168,10 @@ export default Vue.extend({ font-size: 12px; pointer-events: none; + &:empty { + display: none; + } + > * { color: #fff; width: 100%; diff --git a/src/models/entities/notification.ts b/src/models/entities/notification.ts index cd3fe9b01e..565645a5d6 100644 --- a/src/models/entities/notification.ts +++ b/src/models/entities/notification.ts @@ -4,6 +4,7 @@ import { id } from '../id'; import { Note } from './note'; import { FollowRequest } from './follow-request'; import { UserGroupInvitation } from './user-group-invitation'; +import { AccessToken } from './access-token'; @Entity() export class Notification { @@ -35,11 +36,13 @@ export class Notification { /** * 通知の送信者(initiator) */ + @Index() @Column({ ...id(), + nullable: true, comment: 'The ID of sender user of the Notification.' }) - public notifierId: User['id']; + public notifierId: User['id'] | null; @ManyToOne(type => User, { onDelete: 'CASCADE' @@ -59,16 +62,19 @@ export class Notification { * receiveFollowRequest - フォローリクエストされた * followRequestAccepted - 自分の送ったフォローリクエストが承認された * groupInvited - グループに招待された + * app - アプリ通知 */ + @Index() @Column('enum', { - enum: ['follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited'], + enum: ['follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited', 'app'], comment: 'The type of the Notification.' }) - public type: 'follow' | 'mention' | 'reply' | 'renote' | 'quote' | 'reaction' | 'pollVote' | 'receiveFollowRequest' | 'followRequestAccepted' | 'groupInvited'; + public type: 'follow' | 'mention' | 'reply' | 'renote' | 'quote' | 'reaction' | 'pollVote' | 'receiveFollowRequest' | 'followRequestAccepted' | 'groupInvited' | 'app'; /** * 通知が読まれたかどうか */ + @Index() @Column('boolean', { default: false, comment: 'Whether the Notification is read.' @@ -114,10 +120,52 @@ export class Notification { @Column('varchar', { length: 128, nullable: true }) - public reaction: string; + public reaction: string | null; @Column('integer', { nullable: true }) - public choice: number; + public choice: number | null; + + /** + * アプリ通知のbody + */ + @Column('varchar', { + length: 2048, nullable: true + }) + public customBody: string | null; + + /** + * アプリ通知のheader + * (省略時はアプリ名で表示されることを期待) + */ + @Column('varchar', { + length: 256, nullable: true + }) + public customHeader: string | null; + + /** + * アプリ通知のicon(URL) + * (省略時はアプリアイコンで表示されることを期待) + */ + @Column('varchar', { + length: 1024, nullable: true + }) + public customIcon: string | null; + + /** + * アプリ通知のアプリ(のトークン) + */ + @Index() + @Column({ + ...id(), + nullable: true + }) + public appAccessTokenId: AccessToken['id'] | null; + + @ManyToOne(type => AccessToken, { + onDelete: 'CASCADE' + }) + @JoinColumn() + public appAccessToken: AccessToken | null; } diff --git a/src/models/repositories/notification.ts b/src/models/repositories/notification.ts index f020714f80..a8978cc01b 100644 --- a/src/models/repositories/notification.ts +++ b/src/models/repositories/notification.ts @@ -1,5 +1,5 @@ import { EntityRepository, Repository } from 'typeorm'; -import { Users, Notes, UserGroupInvitations } from '..'; +import { Users, Notes, UserGroupInvitations, AccessTokens } from '..'; import { Notification } from '../entities/notification'; import { ensure } from '../../prelude/ensure'; import { awaitAll } from '../../prelude/await-all'; @@ -13,13 +13,14 @@ export class NotificationRepository extends Repository { src: Notification['id'] | Notification, ): Promise { const notification = typeof src === 'object' ? src : await this.findOne(src).then(ensure); + const token = notification.appAccessTokenId ? await AccessTokens.findOne(notification.appAccessTokenId).then(ensure) : null; return await awaitAll({ id: notification.id, createdAt: notification.createdAt.toISOString(), type: notification.type, userId: notification.notifierId, - user: Users.pack(notification.notifier || notification.notifierId), + user: notification.notifierId ? Users.pack(notification.notifier || notification.notifierId) : null, ...(notification.type === 'mention' ? { note: Notes.pack(notification.note || notification.noteId!, notification.notifieeId), } : {}), @@ -43,6 +44,11 @@ export class NotificationRepository extends Repository { ...(notification.type === 'groupInvited' ? { invitation: UserGroupInvitations.pack(notification.userGroupInvitationId!), } : {}), + ...(notification.type === 'app' ? { + body: notification.customBody, + header: notification.customHeader || token!.name, + icon: notification.customIcon || token!.iconUrl, + } : {}), }); } diff --git a/src/server/api/authenticate.ts b/src/server/api/authenticate.ts index 32ad3b4019..c3e277e8de 100644 --- a/src/server/api/authenticate.ts +++ b/src/server/api/authenticate.ts @@ -2,12 +2,9 @@ import isNativeToken from './common/is-native-token'; import { User } from '../../models/entities/user'; import { Users, AccessTokens, Apps } from '../../models'; import { ensure } from '../../prelude/ensure'; +import { AccessToken } from '../../models/entities/access-token'; -type App = { - permission: string[]; -}; - -export default async (token: string): Promise<[User | null | undefined, App | null | undefined]> => { +export default async (token: string): Promise<[User | null | undefined, AccessToken | null | undefined]> => { if (token == null) { return [null, null]; } @@ -45,12 +42,11 @@ export default async (token: string): Promise<[User | null | undefined, App | nu .findOne(accessToken.appId).then(ensure); return [user, { + id: accessToken.id, permission: app.permission - }]; + } as AccessToken]; } else { - return [user, { - permission: accessToken.permission - }]; + return [user, accessToken]; } } }; diff --git a/src/server/api/call.ts b/src/server/api/call.ts index c75006ef31..7911eb9b49 100644 --- a/src/server/api/call.ts +++ b/src/server/api/call.ts @@ -4,10 +4,7 @@ import { User } from '../../models/entities/user'; import endpoints from './endpoints'; import { ApiError } from './error'; import { apiLogger } from './logger'; - -type App = { - permission: string[]; -}; +import { AccessToken } from '../../models/entities/access-token'; const accessDenied = { message: 'Access denied.', @@ -15,8 +12,8 @@ const accessDenied = { id: '56f35758-7dd5-468b-8439-5d6fb8ec9b8e' }; -export default async (endpoint: string, user: User | null | undefined, app: App | null | undefined, data: any, file?: any) => { - const isSecure = user != null && app == null; +export default async (endpoint: string, user: User | null | undefined, token: AccessToken | null | undefined, data: any, file?: any) => { + const isSecure = user != null && token == null; const ep = endpoints.find(e => e.name === endpoint); @@ -54,7 +51,7 @@ export default async (endpoint: string, user: User | null | undefined, app: App throw new ApiError(accessDenied, { reason: 'You are not a moderator.' }); } - if (app && ep.meta.kind && !app.permission.some(p => p === ep.meta.kind)) { + if (token && ep.meta.kind && !token.permission.some(p => p === ep.meta.kind)) { throw new ApiError({ message: 'Your app does not have the necessary permissions to use this endpoint.', code: 'PERMISSION_DENIED', @@ -76,7 +73,7 @@ export default async (endpoint: string, user: User | null | undefined, app: App // API invoking const before = performance.now(); - return await ep.exec(data, user, isSecure, file).catch((e: Error) => { + return await ep.exec(data, user, token, file).catch((e: Error) => { if (e instanceof ApiError) { throw e; } else { diff --git a/src/server/api/define.ts b/src/server/api/define.ts index 3c9e6863b7..2ee0ba4868 100644 --- a/src/server/api/define.ts +++ b/src/server/api/define.ts @@ -3,6 +3,7 @@ import { ILocalUser } from '../../models/entities/user'; import { IEndpointMeta } from './endpoints'; import { ApiError } from './error'; import { SchemaType } from '../../misc/schema'; +import { AccessToken } from '../../models/entities/access-token'; // TODO: defaultが設定されている場合はその型も考慮する type Params = { @@ -14,12 +15,12 @@ type Params = { export type Response = Record | void; type executor = - (params: Params, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any, cleanup?: Function) => + (params: Params, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, token: AccessToken, file?: any, cleanup?: Function) => Promise>>; export default function (meta: T, cb: executor) - : (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any) => Promise { - return (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, isSecure: boolean, file?: any) => { + : (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, token: AccessToken, file?: any) => Promise { + return (params: any, user: T['requireCredential'] extends true ? ILocalUser : ILocalUser | null, token: AccessToken, file?: any) => { function cleanup() { fs.unlink(file.path, () => {}); } @@ -36,7 +37,7 @@ export default function (meta: T, cb: executor) return Promise.reject(pserr); } - return cb(ps, user, isSecure, file, cleanup); + return cb(ps, user, token, file, cleanup); }; } diff --git a/src/server/api/endpoints/app/show.ts b/src/server/api/endpoints/app/show.ts index c1bbb2c53e..e3f3a1eaa4 100644 --- a/src/server/api/endpoints/app/show.ts +++ b/src/server/api/endpoints/app/show.ts @@ -28,7 +28,9 @@ export const meta = { } }; -export default define(meta, async (ps, user, isSecure) => { +export default define(meta, async (ps, user, token) => { + const isSecure = token == null; + // Lookup app const ap = await Apps.findOne(ps.appId); diff --git a/src/server/api/endpoints/drive/files/create.ts b/src/server/api/endpoints/drive/files/create.ts index 5043fbb8e7..c0bb6bcc6e 100644 --- a/src/server/api/endpoints/drive/files/create.ts +++ b/src/server/api/endpoints/drive/files/create.ts @@ -78,7 +78,7 @@ export const meta = { } }; -export default define(meta, async (ps, user, isSecure, file, cleanup) => { +export default define(meta, async (ps, user, _, file, cleanup) => { // Get 'name' parameter let name = ps.name || file.originalname; if (name !== undefined && name !== null) { diff --git a/src/server/api/endpoints/i.ts b/src/server/api/endpoints/i.ts index 3909d54663..02d59682b8 100644 --- a/src/server/api/endpoints/i.ts +++ b/src/server/api/endpoints/i.ts @@ -19,7 +19,9 @@ export const meta = { }, }; -export default define(meta, async (ps, user, isSecure) => { +export default define(meta, async (ps, user, token) => { + const isSecure = token == null; + return await Users.pack(user, user, { detail: true, includeHasUnreadNotes: true, diff --git a/src/server/api/endpoints/i/update.ts b/src/server/api/endpoints/i/update.ts index 0a3ba824ae..c90f050251 100644 --- a/src/server/api/endpoints/i/update.ts +++ b/src/server/api/endpoints/i/update.ts @@ -178,7 +178,9 @@ export const meta = { } }; -export default define(meta, async (ps, user, isSecure) => { +export default define(meta, async (ps, user, token) => { + const isSecure = token == null; + const updates = {} as Partial; const profileUpdates = {} as Partial; diff --git a/src/server/api/endpoints/notes/polls/vote.ts b/src/server/api/endpoints/notes/polls/vote.ts index 3c5492f8ee..45210b5a6e 100644 --- a/src/server/api/endpoints/notes/polls/vote.ts +++ b/src/server/api/endpoints/notes/polls/vote.ts @@ -132,7 +132,8 @@ export default define(meta, async (ps, user) => { }); // Notify - createNotification(note.userId, user.id, 'pollVote', { + createNotification(note.userId, 'pollVote', { + notifierId: user.id, noteId: note.id, choice: ps.choice }); @@ -143,7 +144,8 @@ export default define(meta, async (ps, user) => { userId: Not(user.id), }).then(watchers => { for (const watcher of watchers) { - createNotification(watcher.userId, user.id, 'pollVote', { + createNotification(watcher.userId, 'pollVote', { + notifierId: user.id, noteId: note.id, choice: ps.choice }); diff --git a/src/server/api/endpoints/notifications/create.ts b/src/server/api/endpoints/notifications/create.ts new file mode 100644 index 0000000000..fed422b645 --- /dev/null +++ b/src/server/api/endpoints/notifications/create.ts @@ -0,0 +1,37 @@ +import $ from 'cafy'; +import define from '../../define'; +import { createNotification } from '../../../../services/create-notification'; + +export const meta = { + tags: ['notifications'], + + requireCredential: true as const, + + kind: 'write:notifications', + + params: { + body: { + validator: $.str + }, + + header: { + validator: $.optional.nullable.str + }, + + icon: { + validator: $.optional.nullable.str + }, + }, + + errors: { + } +}; + +export default define(meta, async (ps, user, token) => { + createNotification(user.id, 'app', { + appAccessTokenId: token.id, + customBody: ps.body, + customHeader: ps.header, + customIcon: ps.icon, + }); +}); diff --git a/src/server/api/endpoints/users/groups/invite.ts b/src/server/api/endpoints/users/groups/invite.ts index da0fd1c2ca..a0f5091b07 100644 --- a/src/server/api/endpoints/users/groups/invite.ts +++ b/src/server/api/endpoints/users/groups/invite.ts @@ -104,7 +104,8 @@ export default define(meta, async (ps, me) => { } as UserGroupInvitation); // 通知を作成 - createNotification(user.id, me.id, 'groupInvited', { + createNotification(user.id, 'groupInvited', { + notifierId: me.id, userGroupInvitationId: invitation.id }); }); diff --git a/src/server/api/stream/index.ts b/src/server/api/stream/index.ts index 4b233b9a8b..05594ac722 100644 --- a/src/server/api/stream/index.ts +++ b/src/server/api/stream/index.ts @@ -9,10 +9,7 @@ import { EventEmitter } from 'events'; import { User } from '../../../models/entities/user'; import { Users, Followings, Mutings } from '../../../models'; import { ApiError } from '../error'; - -type App = { - permission: string[]; -}; +import { AccessToken } from '../../../models/entities/access-token'; /** * Main stream connection @@ -21,7 +18,7 @@ export default class Connection { public user?: User; public following: User['id'][] = []; public muting: User['id'][] = []; - public app: App; + public token: AccessToken; private wsConnection: websocket.connection; public subscriber: EventEmitter; private channels: Channel[] = []; @@ -33,12 +30,12 @@ export default class Connection { wsConnection: websocket.connection, subscriber: EventEmitter, user: User | null | undefined, - app: App | null | undefined + token: AccessToken | null | undefined ) { this.wsConnection = wsConnection; this.subscriber = subscriber; if (user) this.user = user; - if (app) this.app = app; + if (token) this.token = token; this.wsConnection.on('message', this.onWsConnectionMessage); @@ -86,7 +83,7 @@ export default class Connection { const endpoint = payload.endpoint || payload.ep; // alias // 呼び出し - call(endpoint, user, this.app, payload.data).then(res => { + call(endpoint, user, this.token, payload.data).then(res => { this.sendMessageToWs(`api:${payload.id}`, { res }); }).catch((e: ApiError) => { this.sendMessageToWs(`api:${payload.id}`, { diff --git a/src/services/create-notification.ts b/src/services/create-notification.ts index c5c6e7144b..7fc8bfaf53 100644 --- a/src/services/create-notification.ts +++ b/src/services/create-notification.ts @@ -3,46 +3,26 @@ import pushSw from './push-notification'; import { Notifications, Mutings } from '../models'; import { genId } from '../misc/gen-id'; import { User } from '../models/entities/user'; -import { Note } from '../models/entities/note'; import { Notification } from '../models/entities/notification'; -import { FollowRequest } from '../models/entities/follow-request'; -import { UserGroupInvitation } from '../models/entities/user-group-invitation'; export async function createNotification( notifieeId: User['id'], - notifierId: User['id'], type: Notification['type'], - content?: { - noteId?: Note['id']; - reaction?: string; - choice?: number; - followRequestId?: FollowRequest['id']; - userGroupInvitationId?: UserGroupInvitation['id']; - } + data: Partial ) { - if (notifieeId === notifierId) { + if (data.notifierId && (notifieeId === data.notifierId)) { return null; } - const data = { + // Create notification + const notification = await Notifications.save({ id: genId(), createdAt: new Date(), notifieeId: notifieeId, - notifierId: notifierId, type: type, isRead: false, - } as Partial; - - if (content) { - if (content.noteId) data.noteId = content.noteId; - if (content.reaction) data.reaction = content.reaction; - if (content.choice) data.choice = content.choice; - if (content.followRequestId) data.followRequestId = content.followRequestId; - if (content.userGroupInvitationId) data.userGroupInvitationId = content.userGroupInvitationId; - } - - // Create notification - const notification = await Notifications.save(data); + ...data + } as Partial); const packed = await Notifications.pack(notification); @@ -58,7 +38,7 @@ export async function createNotification( const mutings = await Mutings.find({ muterId: notifieeId }); - if (mutings.map(m => m.muteeId).includes(notifierId)) { + if (data.notifierId && mutings.map(m => m.muteeId).includes(data.notifierId)) { return; } //#endregion diff --git a/src/services/following/create.ts b/src/services/following/create.ts index ce352ffbc1..c5f130f49f 100644 --- a/src/services/following/create.ts +++ b/src/services/following/create.ts @@ -57,7 +57,9 @@ export async function insertFollowingDoc(followee: User, follower: User) { }); // 通知を作成 - createNotification(follower.id, followee.id, 'followRequestAccepted'); + createNotification(follower.id, 'followRequestAccepted', { + notifierId: followee.id, + }); } if (alreadyFollowed) return; @@ -95,7 +97,9 @@ export async function insertFollowingDoc(followee: User, follower: User) { Users.pack(follower, followee).then(packed => publishMainStream(followee.id, 'followed', packed)), // 通知を作成 - createNotification(followee.id, follower.id, 'follow'); + createNotification(followee.id, 'follow', { + notifierId: follower.id + }); } } diff --git a/src/services/following/requests/create.ts b/src/services/following/requests/create.ts index 1c6bac0fbe..deaeedb9a8 100644 --- a/src/services/following/requests/create.ts +++ b/src/services/following/requests/create.ts @@ -50,7 +50,8 @@ export default async function(follower: User, followee: User, requestId?: string }).then(packed => publishMainStream(followee.id, 'meUpdated', packed)); // 通知を作成 - createNotification(followee.id, follower.id, 'receiveFollowRequest', { + createNotification(followee.id, 'receiveFollowRequest', { + notifierId: follower.id, followRequestId: followRequest.id }); } diff --git a/src/services/note/create.ts b/src/services/note/create.ts index 50586e8bc7..60a5a5e69d 100644 --- a/src/services/note/create.ts +++ b/src/services/note/create.ts @@ -78,7 +78,8 @@ class NotificationManager { // 通知される側のユーザーが通知する側のユーザーをミュートしていない限りは通知する if (!mentioneesMutedUserIds.includes(this.notifier.id)) { - createNotification(x.target, this.notifier.id, x.reason, { + createNotification(x.target, x.reason, { + notifierId: this.notifier.id, noteId: this.note.id }); } diff --git a/src/services/note/polls/vote.ts b/src/services/note/polls/vote.ts index aee52ba10d..7350c813af 100644 --- a/src/services/note/polls/vote.ts +++ b/src/services/note/polls/vote.ts @@ -48,7 +48,8 @@ export default async function(user: User, note: Note, choice: number) { }); // Notify - createNotification(note.userId, user.id, 'pollVote', { + createNotification(note.userId, 'pollVote', { + notifierId: user.id, noteId: note.id, choice: choice }); @@ -60,7 +61,8 @@ export default async function(user: User, note: Note, choice: number) { }) .then(watchers => { for (const watcher of watchers) { - createNotification(watcher.userId, user.id, 'pollVote', { + createNotification(watcher.userId, 'pollVote', { + notifierId: user.id, noteId: note.id, choice: choice }); diff --git a/src/services/note/reaction/create.ts b/src/services/note/reaction/create.ts index 166c4e1f81..72750affe0 100644 --- a/src/services/note/reaction/create.ts +++ b/src/services/note/reaction/create.ts @@ -66,7 +66,8 @@ export default async (user: User, note: Note, reaction?: string) => { // リアクションされたユーザーがローカルユーザーなら通知を作成 if (note.userHost === null) { - createNotification(note.userId, user.id, 'reaction', { + createNotification(note.userId, 'reaction', { + notifierId: user.id, noteId: note.id, reaction: reaction }); @@ -78,7 +79,8 @@ export default async (user: User, note: Note, reaction?: string) => { userId: Not(user.id) }).then(watchers => { for (const watcher of watchers) { - createNotification(watcher.userId, user.id, 'reaction', { + createNotification(watcher.userId, 'reaction', { + notifierId: user.id, noteId: note.id, reaction: reaction }); -- cgit v1.2.3-freya From dcd43a17ba1f1680abe3adf1499932797d703de7 Mon Sep 17 00:00:00 2001 From: syuilo Date: Sat, 28 Mar 2020 19:33:11 +0900 Subject: インストールしたアプリ見れるようにしたり削除できるようにしたり MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- locales/ja-JP.yml | 4 ++ src/client/components/notes.vue | 14 +---- src/client/pages/apps.vue | 98 ++++++++++++++++++++++++++++++ src/client/pages/follow-requests.vue | 14 +---- src/client/pages/messaging/index.vue | 14 +---- src/client/pages/my-settings/index.vue | 4 +- src/client/router.ts | 1 + src/client/style.scss | 20 ++++++ src/server/api/endpoints/i/revoke-token.ts | 24 ++++++++ 9 files changed, 153 insertions(+), 40 deletions(-) create mode 100644 src/client/pages/apps.vue create mode 100644 src/server/api/endpoints/i/revoke-token.ts (limited to 'src/server/api') diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index 4650f03a29..a77991cccd 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -468,6 +468,10 @@ unableToProcess: "操作を完了できません" recentUsed: "最近使用" install: "インストール" uninstall: "アンインストール" +installedApps: "インストールされたアプリ" +nothing: "ありません" +installedDate: "インストール日時" +lastUsedDate: "最終使用日時" _theme: explore: "テーマを探す" diff --git a/src/client/components/notes.vue b/src/client/components/notes.vue index 65dda17575..0cf4dee2dd 100644 --- a/src/client/components/notes.vue +++ b/src/client/components/notes.vue @@ -1,6 +1,6 @@