diff --git a/packages/misskey-js/etc/misskey-js.api.md b/packages/misskey-js/etc/misskey-js.api.md index 70955a2a73..423b3be916 100644 --- a/packages/misskey-js/etc/misskey-js.api.md +++ b/packages/misskey-js/etc/misskey-js.api.md @@ -28,7 +28,8 @@ declare namespace acct { parseUrl, parseAcctOrUrl, toString_2 as toString, - Acct + Acct, + UrlIsNotAcctLikeError } } export { acct } @@ -3640,6 +3641,11 @@ type TestResponse = operations['test']['responses']['200']['content']['applicati // @public (undocumented) function toString_2(acct: Acct): string; +// @public (undocumented) +class UrlIsNotAcctLikeError extends Error { + constructor(); +} + // @public (undocumented) type User = components['schemas']['User']; diff --git a/packages/misskey-js/src/acct.ts b/packages/misskey-js/src/acct.ts index e30599b650..e8c4524ec4 100644 --- a/packages/misskey-js/src/acct.ts +++ b/packages/misskey-js/src/acct.ts @@ -27,15 +27,25 @@ export function parse(acct: string): Acct { return { username: split[0], host: split[1] || null }; } +export class UrlIsNotAcctLikeError extends Error { + constructor() { + super('This url is not acct like.'); + } +} + export function parseUrl(str: string): Acct { const url = new URL(str); + + if (url.hash.length > 0) throw new UrlIsNotAcctLikeError(); + if (url.search.length > 0) throw new UrlIsNotAcctLikeError(); + const splited = url.pathname.split('/'); let path = splited.pop(); if (path === '') path = splited.pop(); // If the last segment is empty due to a trailing '/', use the previous segment - if (!path) throw new Error('This url is not acct like.'); - if (!path.startsWith('@')) throw new Error('This url is not acct like.'); - if (path.length <= 1) throw new Error('This url is not acct like.'); + if (!path) throw new UrlIsNotAcctLikeError(); + if (!path.startsWith('@')) throw new UrlIsNotAcctLikeError(); + if (path.length <= 1) throw new UrlIsNotAcctLikeError(); const split = path.split('@', 3); // ['', 'username', 'other.example.com'] diff --git a/packages/misskey-js/test/acct.ts b/packages/misskey-js/test/acct.ts index 510b106ad2..4200e593de 100644 --- a/packages/misskey-js/test/acct.ts +++ b/packages/misskey-js/test/acct.ts @@ -59,6 +59,14 @@ function testParseUrl(fn: (acct: string) => acct.Acct) { it('throws url have @username path but ended with sub directory', () => { expect(() => fn('https://example.com/@alice/subdir')).toThrowError(); }); + + it('throws url with search params', () => { + expect(() => fn('https://example.com/@alice?foo=bar')).toThrowError(); + }); + + it('throws url with hash', () => { + expect(() => fn('https://example.com/@alice#fragment')).toThrowError(); + }); } describe('acct.parse', () => {