diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx index 0eda2219b8..b990e4359e 100644 --- a/app/scenes/Login/OAuthAuthorize.tsx +++ b/app/scenes/Login/OAuthAuthorize.tsx @@ -5,6 +5,7 @@ import Flex from "@shared/components/Flex"; import { s } from "@shared/styles"; import { parseDomain } from "@shared/utils/domains"; import { isLoopbackUri } from "@shared/utils/urls"; +import { OAuthClientValidation } from "@shared/validations"; import type OAuthClient from "~/models/oauth/OAuthClient"; import ButtonLarge from "~/components/ButtonLarge"; import ChangeLanguage from "~/components/ChangeLanguage"; @@ -76,15 +77,12 @@ function inputScopes(scope?: string): string[] { * @param clientId the OAuth client_id parameter. * @returns the hostname, or undefined if the client does not use a metadata document. */ -function metadataDocumentHost(clientId?: string) { - if (!clientId?.startsWith("https://")) { - return undefined; - } - try { - return new URL(clientId).hostname; - } catch { - return undefined; - } +function metadataDocumentHost(clientId: string) { + return clientId.startsWith( + OAuthClientValidation.metadataDocumentClientIdPrefix + ) + ? parseDomain(clientId).host + : undefined; } /** @@ -199,7 +197,8 @@ function Authorize() { } const { name, developerName, developerUrl } = response.data; - const clientHost = metadataDocumentHost(clientId); + const clientHost = metadataDocumentHost(response.data.clientId); + const isLoopback = isLoopbackUri(redirectUri); return ( @@ -265,13 +264,13 @@ function Authorize() { )} - {isLoopbackUri(redirectUri) && clientHost ? ( + {isLoopback && clientHost ? ( }} /> - ) : isLoopbackUri(redirectUri) ? ( + ) : isLoopback ? ( You will be redirected to a local application after authorizing. diff --git a/server/migrations/20261010120000-add-client-metadata-documents-to-oauth-clients.js b/server/migrations/20261010120000-add-client-metadata-documents-to-oauth-clients.js index 0c1c6b69de..43f1cdb009 100644 --- a/server/migrations/20261010120000-add-client-metadata-documents-to-oauth-clients.js +++ b/server/migrations/20261010120000-add-client-metadata-documents-to-oauth-clients.js @@ -26,10 +26,11 @@ module.exports = { { transaction } ); - // Only clients identified by a metadata document URL may exist without a team. + // A client has no team exactly when it is identified by a metadata + // document URL. await queryInterface.sequelize.query( `ALTER TABLE "oauth_clients" ADD CONSTRAINT "oauth_clients_team_id_or_metadata_document" - CHECK ("teamId" IS NOT NULL OR "clientId" LIKE 'https://%');`, + CHECK (("teamId" IS NULL) = ("clientId" LIKE 'https://%'));`, { transaction } ); }); diff --git a/server/migrations/20261010120001-add-oauth-client-id-indexes.js b/server/migrations/20261010120001-add-oauth-client-id-indexes.js new file mode 100644 index 0000000000..8296b4ea37 --- /dev/null +++ b/server/migrations/20261010120001-add-oauth-client-id-indexes.js @@ -0,0 +1,23 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface) { + // Covers cascade deletes and the cleanup checks for live grants. + await queryInterface.sequelize.query( + 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "oauth_authentications_oauth_client_id" ON "oauth_authentications" ("oauthClientId");' + ); + await queryInterface.sequelize.query( + 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "oauth_authorization_codes_oauth_client_id" ON "oauth_authorization_codes" ("oauthClientId");' + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + 'DROP INDEX CONCURRENTLY IF EXISTS "oauth_authorization_codes_oauth_client_id";' + ); + await queryInterface.sequelize.query( + 'DROP INDEX CONCURRENTLY IF EXISTS "oauth_authentications_oauth_client_id";' + ); + }, +}; diff --git a/server/models/oauth/OAuthClient.test.ts b/server/models/oauth/OAuthClient.test.ts index 579e46ed7f..32b726dadb 100644 --- a/server/models/oauth/OAuthClient.test.ts +++ b/server/models/oauth/OAuthClient.test.ts @@ -3,6 +3,7 @@ import { OAuthClient } from "@server/models"; import { buildMetadataDocumentOAuthClient, buildOAuthClient, + buildTeam, } from "@server/test/factories"; describe("OAuthClient", () => { @@ -47,5 +48,17 @@ describe("OAuthClient", () => { ) ).rejects.toThrow(); }); + + it("should not allow a metadata document client to have a team", async () => { + const team = await buildTeam(); + const client = await buildMetadataDocumentOAuthClient(); + + await expect( + OAuthClient.update( + { teamId: team.id }, + { where: { id: client.id }, hooks: false } + ) + ).rejects.toThrow(); + }); }); }); diff --git a/server/models/oauth/OAuthClient.ts b/server/models/oauth/OAuthClient.ts index 091e16879d..1218631941 100644 --- a/server/models/oauth/OAuthClient.ts +++ b/server/models/oauth/OAuthClient.ts @@ -183,6 +183,16 @@ class OAuthClient extends ParanoidModel< return !this.createdById && !this.isCIMD; } + /** + * Determine if this client exists only to serve MCP. This is true for + * clients from dynamic client registration and from metadata documents. + * + * @returns true if this client was not created by a user, false otherwise. + */ + public get isMCPClient() { + return !this.createdById; + } + /** * Determine if this client is identified by a client ID metadata document * (CIMD). These clients use the https URL of the document as their @@ -224,7 +234,9 @@ class OAuthClient extends ParanoidModel< * @returns true if the identifier is a metadata document URL. */ public static isMetadataDocumentClientId(clientId: string | undefined) { - return !!clientId?.startsWith("https://"); + return !!clientId?.startsWith( + OAuthClientValidation.metadataDocumentClientIdPrefix + ); } /** diff --git a/server/policies/oauthClient.ts b/server/policies/oauthClient.ts index d487cf2d24..4ac67560f9 100644 --- a/server/policies/oauthClient.ts +++ b/server/policies/oauthClient.ts @@ -18,10 +18,8 @@ allow(User, "read", OAuthClient, (actor, oauthClient) => !!oauthClient?.published, !!oauthClient?.isCIMD ), - // Dynamically registered and metadata document clients exist only to - // serve MCP, so they become unreachable when the team turns it off. - (!oauthClient?.isDCR && !oauthClient?.isCIMD) || - !!actor.team?.getPreference(TeamPreference.MCP) + // MCP clients become unreachable when the team turns MCP off. + !oauthClient?.isMCPClient || !!actor.team?.getPreference(TeamPreference.MCP) ) ); @@ -29,7 +27,6 @@ allow(User, ["update", "delete"], OAuthClient, (actor, oauthClient) => and( isTeamAdmin(actor, oauthClient), isTeamMutable(actor), - !oauthClient?.isDCR, - !oauthClient?.isCIMD + !oauthClient?.isMCPClient ) ); diff --git a/server/queues/tasks/CleanupDynamicOAuthClientsTask.ts b/server/queues/tasks/CleanupDynamicOAuthClientsTask.ts index 786a07f1c9..ca5ef76b88 100644 --- a/server/queues/tasks/CleanupDynamicOAuthClientsTask.ts +++ b/server/queues/tasks/CleanupDynamicOAuthClientsTask.ts @@ -1,5 +1,6 @@ import { subDays, subHours } from "date-fns"; import { Op, Sequelize } from "sequelize"; +import { OAuthClientValidation } from "@shared/validations"; import Logger from "@server/logging/Logger"; import { OAuthClient } from "@server/models"; import { TaskPriority } from "./base/BaseTask"; @@ -22,6 +23,8 @@ export default class CleanupDynamicOAuthClientsTask extends CronTask { // Deleting a client cascades to its codes, so keep clients that are // between consent and token exchange. + const metadataDocumentPattern = `${OAuthClientValidation.metadataDocumentClientIdPrefix}%`; + const noPendingCodes = Sequelize.literal( `NOT EXISTS (SELECT 1 FROM oauth_authorization_codes oac WHERE oac."oauthClientId" = "oauth_clients"."id" AND oac."expiresAt" > NOW())` ); @@ -29,7 +32,7 @@ export default class CleanupDynamicOAuthClientsTask extends CronTask { const count = await OAuthClient.unscoped().destroy({ where: { createdById: null, - clientId: { [Op.notLike]: "https://%" }, + clientId: { [Op.notLike]: metadataDocumentPattern }, [Op.and]: [noPendingCodes], [Op.or]: [ { @@ -49,9 +52,7 @@ export default class CleanupDynamicOAuthClientsTask extends CronTask { const metadataCount = await OAuthClient.unscoped().destroy({ where: { - createdById: null, - teamId: null, - clientId: { [Op.like]: "https://%" }, + clientId: { [Op.like]: metadataDocumentPattern }, createdAt: { [Op.lt]: neverUsedCutoff }, [Op.and]: [ noPendingCodes, diff --git a/server/routes/api/oauthClients/oauthClients.ts b/server/routes/api/oauthClients/oauthClients.ts index 042c9b2bee..bfb3a8f899 100644 --- a/server/routes/api/oauthClients/oauthClients.ts +++ b/server/routes/api/oauthClients/oauthClients.ts @@ -1,12 +1,8 @@ import Router from "@koa/router"; import { Op } from "sequelize"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; -import { TeamPreference, UserRole } from "@shared/types"; -import { - AuthorizationError, - NotFoundError, - ValidationError, -} from "@server/errors"; +import { UserRole } from "@shared/types"; +import { NotFoundError, ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import { transaction } from "@server/middlewares/transaction"; @@ -88,18 +84,8 @@ router.post( const { id, clientId, redirectUri } = ctx.input.body; const { user } = ctx.state.auth; - // Metadata documents only serve MCP, so do not fetch one for a workspace - // that has turned it off. - if ( - clientId && - OAuthClient.isMetadataDocumentClientId(clientId) && - !user.team.getPreference(TeamPreference.MCP) - ) { - throw AuthorizationError(); - } - const oauthClient = clientId - ? await ClientMetadataHelper.findOrFetchByClientId(clientId) + ? await ClientMetadataHelper.findOrFetchByClientId(clientId, user.team) : await OAuthClient.findByPk(id); if (!oauthClient) { throw NotFoundError(); diff --git a/server/routes/oauth/index.ts b/server/routes/oauth/index.ts index cd17b63f67..51a2360e5b 100644 --- a/server/routes/oauth/index.ts +++ b/server/routes/oauth/index.ts @@ -3,11 +3,7 @@ import Koa from "koa"; import bodyParser from "koa-body"; import Router from "@koa/router"; import env from "@server/env"; -import { - AuthorizationError, - ValidationError, - NotFoundError, -} from "@server/errors"; +import { ValidationError, NotFoundError } from "@server/errors"; import { apiContext } from "@server/middlewares/apiContext"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; @@ -58,18 +54,12 @@ router.post( throw ValidationError("Missing client_id"); } - // Metadata documents only serve MCP, so do not fetch one for a workspace - // that has turned it off. - if ( - OAuthClient.isMetadataDocumentClientId(clientId) && - !user.team.getPreference(TeamPreference.MCP) - ) { - throw AuthorizationError(); - } - // Metadata document clients are fetched again here when the cached copy // has expired, so that the redirect URI check uses fresh data. - const client = await ClientMetadataHelper.findOrFetchByClientId(clientId); + const client = await ClientMetadataHelper.findOrFetchByClientId( + clientId, + user.team + ); authorize(user, "read", client); // Metadata document clients are public and cannot prove a loopback diff --git a/server/test/factories.ts b/server/test/factories.ts index 599c5cdd0d..9a0eb688d9 100644 --- a/server/test/factories.ts +++ b/server/test/factories.ts @@ -5,6 +5,7 @@ import type { InferCreationAttributes } from "sequelize"; import type { DeepPartial } from "utility-types"; import { randomUUID } from "node:crypto"; import { randomString } from "@shared/random"; +import { Hour } from "@shared/utils/time"; import type { ProsemirrorData, ReactionSummary } from "@shared/types"; import { CollectionPermission, @@ -845,14 +846,14 @@ export async function buildPin(overrides: Partial = {}): Promise { } export async function buildOAuthClient(overrides: Partial = {}) { - if (!overrides.teamId) { + if (overrides.teamId === undefined) { const team = await buildTeam(); overrides.teamId = team.id; } if (!overrides.createdById && overrides.createdById !== null) { const user = await buildUser({ - teamId: overrides.teamId, + teamId: overrides.teamId ?? undefined, }); overrides.createdById = user.id; } @@ -883,25 +884,15 @@ export async function buildOAuthClient(overrides: Partial = {}) { export async function buildMetadataDocumentOAuthClient( overrides: Partial = {} ) { - return OAuthClient.create( - { - clientId: `https://${randomUUID()}.example.com/oauth/client.json`, - name: faker.company.name(), - redirectUris: ["https://example.com/oauth/callback"], - clientType: "public", - published: false, - teamId: null, - createdById: null, - metadataExpiresAt: new Date(Date.now() + 60 * 60 * 1000), - ...(overrides.createdAt && !overrides.updatedAt - ? { updatedAt: overrides.createdAt } - : {}), - ...overrides, - }, - { - silent: overrides.createdAt || overrides.updatedAt ? true : false, - } - ); + return buildOAuthClient({ + clientId: `https://${randomUUID()}.example.com/oauth/client.json`, + clientType: "public", + published: false, + teamId: null, + createdById: null, + metadataExpiresAt: new Date(Date.now() + Hour.ms), + ...overrides, + }); } export async function buildOAuthAuthorizationCode( diff --git a/server/utils/oauth/ClientMetadataHelper.test.ts b/server/utils/oauth/ClientMetadataHelper.test.ts index 9a11aec7a9..d68f0c9d18 100644 --- a/server/utils/oauth/ClientMetadataHelper.test.ts +++ b/server/utils/oauth/ClientMetadataHelper.test.ts @@ -1,6 +1,8 @@ import { randomUUID } from "node:crypto"; import { http, HttpResponse } from "msw"; import { Minute, Day } from "@shared/utils/time"; +import { TeamPreference } from "@shared/types"; +import type { Team } from "@server/models"; import { OAuthClient } from "@server/models"; import { buildMetadataDocumentOAuthClient, @@ -225,10 +227,30 @@ describe("ClientMetadataHelper", () => { }); describe("findOrFetchByClientId", () => { + let team: Team; + + beforeEach(async () => { + team = await buildTeam(); + }); + + it("should not fetch when the team has turned MCP off", async () => { + const clientId = buildClientId(); + const mock = mockDocument(clientId, buildDocument(clientId)); + const disabled = await buildTeam({ + preferences: { [TeamPreference.MCP]: false }, + }); + + await expect( + ClientMetadataHelper.findOrFetchByClientId(clientId, disabled) + ).rejects.toThrow(); + expect(mock.requests()).toEqual(0); + }); + it("should find a generated client without fetching", async () => { const client = await buildOAuthClient(); const found = await ClientMetadataHelper.findOrFetchByClientId( - client.clientId + client.clientId, + team ); expect(found?.id).toEqual(client.id); }); @@ -239,7 +261,10 @@ describe("ClientMetadataHelper", () => { headers: { "Cache-Control": "max-age=3600" }, }); - const client = await ClientMetadataHelper.findOrFetchByClientId(clientId); + const client = await ClientMetadataHelper.findOrFetchByClientId( + clientId, + team + ); expect(client).toBeTruthy(); expect(client?.clientId).toEqual(clientId); @@ -268,7 +293,8 @@ describe("ClientMetadataHelper", () => { ); const client = await ClientMetadataHelper.findOrFetchByClientId( - cached.clientId + cached.clientId, + team ); expect(client?.id).toEqual(cached.id); @@ -285,7 +311,8 @@ describe("ClientMetadataHelper", () => { ); const client = await ClientMetadataHelper.findOrFetchByClientId( - cached.clientId + cached.clientId, + team ); expect(mock.requests()).toEqual(1); @@ -301,7 +328,8 @@ describe("ClientMetadataHelper", () => { mockDocument(cached.clientId, "error", { status: 500 }); const client = await ClientMetadataHelper.findOrFetchByClientId( - cached.clientId + cached.clientId, + team ); expect(client).toBeNull(); @@ -315,9 +343,9 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, buildDocument(clientId)); const clients = await Promise.all([ - ClientMetadataHelper.findOrFetchByClientId(clientId), - ClientMetadataHelper.findOrFetchByClientId(clientId), - ClientMetadataHelper.findOrFetchByClientId(clientId), + ClientMetadataHelper.findOrFetchByClientId(clientId, team), + ClientMetadataHelper.findOrFetchByClientId(clientId, team), + ClientMetadataHelper.findOrFetchByClientId(clientId, team), ]); expect(clients.every(Boolean)).toBe(true); @@ -326,7 +354,8 @@ describe("ClientMetadataHelper", () => { it("should not fetch an invalid client_id URL", async () => { const client = await ClientMetadataHelper.findOrFetchByClientId( - "https://example.com/a/../client" + "https://example.com/a/../client", + team ); expect(client).toBeNull(); }); @@ -339,7 +368,7 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, buildDocument(clientId), { status }); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -359,7 +388,7 @@ describe("ClientMetadataHelper", () => { ); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); expect(mock.requests()).toEqual(0); }); @@ -374,7 +403,7 @@ describe("ClientMetadataHelper", () => { ); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -383,7 +412,7 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, "{ not json"); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -392,7 +421,7 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, buildDocument(buildClientId())); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -401,7 +430,7 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, buildDocument(clientId, { client_secret: "abc" })); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -415,7 +444,7 @@ describe("ClientMetadataHelper", () => { ); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); } ); @@ -425,7 +454,7 @@ describe("ClientMetadataHelper", () => { mockDocument(clientId, buildDocument(clientId, { redirect_uris: [] })); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -439,7 +468,7 @@ describe("ClientMetadataHelper", () => { ); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -450,7 +479,7 @@ describe("ClientMetadataHelper", () => { }); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); }); @@ -461,7 +490,7 @@ describe("ClientMetadataHelper", () => { }); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeTruthy(); }); @@ -470,7 +499,7 @@ describe("ClientMetadataHelper", () => { const mock = mockDocument(clientId, buildDocument(clientId)); expect( - await ClientMetadataHelper.findOrFetchByClientId(clientId) + await ClientMetadataHelper.findOrFetchByClientId(clientId, team) ).toBeNull(); expect(mock.requests()).toEqual(0); }); @@ -484,7 +513,10 @@ describe("ClientMetadataHelper", () => { }) ); - const client = await ClientMetadataHelper.findOrFetchByClientId(clientId); + const client = await ClientMetadataHelper.findOrFetchByClientId( + clientId, + team + ); expect(client?.redirectUris).toEqual(["http://127.0.0.1:33418/callback"]); }); }); diff --git a/server/utils/oauth/ClientMetadataHelper.ts b/server/utils/oauth/ClientMetadataHelper.ts index 59a4aba713..6f663c8608 100644 --- a/server/utils/oauth/ClientMetadataHelper.ts +++ b/server/utils/oauth/ClientMetadataHelper.ts @@ -1,9 +1,13 @@ +import { clamp } from "es-toolkit"; +import { UniqueConstraintError } from "sequelize"; import { z } from "zod"; -import { getBaseDomain } from "@shared/utils/domains"; +import { TeamPreference } from "@shared/types"; +import { parseDomain } from "@shared/utils/domains"; import { errToString } from "@shared/utils/error"; -import { Minute, Day } from "@shared/utils/time"; +import { Day, Minute, Second } from "@shared/utils/time"; import { OAuthClientValidation } from "@shared/validations"; import env from "@server/env"; +import { AuthorizationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import { OAuthClient, Share, Team } from "@server/models"; import fetch from "@server/utils/fetch"; @@ -67,23 +71,25 @@ export class ClientMetadataHelper { * client or the cached copy has expired. * * @param clientId The public client identifier. + * @param team The team of the user that requests the client. * @returns The OAuth client, or null if it is not found or not valid. + * @throws AuthorizationError if the client is a metadata document and the + * team has turned MCP off. */ public static async findOrFetchByClientId( - clientId: string + clientId: string, + team: Team ): Promise { if (!OAuthClient.isMetadataDocumentClientId(clientId)) { return OAuthClient.findByClientId(clientId); } - if (!ClientMetadataHelper.isValidClientIdUrl(clientId)) { - return null; - } - // Users can upload content to this installation, so a document hosted - // here could impersonate a client. - if ( - await ClientMetadataHelper.isInstallationHost(new URL(clientId).hostname) - ) { + // Metadata documents only serve MCP, so do not fetch one for a team that + // has turned it off. + if (!team.getPreference(TeamPreference.MCP)) { + throw AuthorizationError(); + } + if (!ClientMetadataHelper.isValidClientIdUrl(clientId)) { return null; } @@ -95,6 +101,14 @@ export class ClientMetadataHelper { return existing; } + // Users can upload content to this installation, so a document hosted + // here could impersonate a client. + if ( + await ClientMetadataHelper.isInstallationHost(new URL(clientId).hostname) + ) { + return null; + } + try { const { document, expiresAt } = await ClientMetadataHelper.fetchMetadataDocument(clientId); @@ -112,12 +126,20 @@ export class ClientMetadataHelper { return await existing.update(attributes); } - // Concurrent first requests for the same URL resolve to the same row. - const [client, created] = await OAuthClient.findOrCreate({ - where: { clientId }, - defaults: { ...attributes, clientId, teamId: null, createdById: null }, - }); - return created ? client : await client.update(attributes); + try { + return await OAuthClient.create({ + ...attributes, + clientId, + teamId: null, + createdById: null, + }); + } catch (err) { + // A concurrent request for the same URL created the row first. + if (err instanceof UniqueConstraintError) { + return await OAuthClient.findByClientId(clientId); + } + throw err; + } } catch (err) { // An existing client is kept so that issued tokens continue to work, // but it cannot be authorized again until a fetch succeeds. @@ -156,7 +178,7 @@ export class ClientMetadataHelper { return false; } - if (url.protocol !== "https:" || !clientId.startsWith("https://")) { + if (!OAuthClient.isMetadataDocumentClientId(clientId)) { return false; } if (url.username || url.password || clientId.includes("#")) { @@ -188,9 +210,8 @@ export class ClientMetadataHelper { * @returns true if the hostname belongs to this installation. */ public static async isInstallationHost(hostname: string): Promise { - const host = hostname.toLowerCase().replace(/\.+$/, ""); - const baseDomain = getBaseDomain(); - if (host === baseDomain || host.endsWith(`.${baseDomain}`)) { + const { host, custom } = parseDomain(hostname); + if (!custom) { return true; } @@ -284,14 +305,15 @@ export class ClientMetadataHelper { const expires = headers.get("expires"); if (maxAge) { - duration = parseInt(maxAge[1], 10) * 1000; + duration = parseInt(maxAge[1], 10) * Second.ms; } else if (expires) { const expiresAt = new Date(expires).getTime(); duration = Number.isNaN(expiresAt) ? 0 : expiresAt - now.getTime(); } - const clamped = Math.min( - Math.max(duration, ClientMetadataHelper.minCacheDuration), + const clamped = clamp( + duration, + ClientMetadataHelper.minCacheDuration, ClientMetadataHelper.maxCacheDuration ); return new Date(now.getTime() + clamped); diff --git a/shared/validations.ts b/shared/validations.ts index 160e9a6c57..29728c8226 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -124,6 +124,9 @@ export const OAuthClientValidation = { /** The maximum length of an OAuth client ID, which can be a metadata document URL */ maxClientIdLength: 1024, + /** The prefix of client IDs that are the URL of a client ID metadata document */ + metadataDocumentClientIdPrefix: "https://", + /** The maximum number of redirect URIs for an OAuth client */ maxRedirectUris: 20,