import {z} from 'zod' export type OAuth2ClientId = {id: string, entityType: 'TENANT' | 'CUSTOMER' | 'USER' | 'DASHBOARD' | 'ASSET' | 'DEVICE' | 'ALARM' | 'RULE_CHAIN' | 'RULE_NODE' | 'ENTITY_VIEW' | 'WIDGETS_BUNDLE' | 'WIDGET_TYPE' | 'TENANT_PROFILE' | 'DEVICE_PROFILE' | 'ASSET_PROFILE' | 'API_USAGE_STATE' | 'TB_RESOURCE' | 'OTA_PACKAGE' | 'EDGE' | 'RPC' | 'QUEUE' | 'NOTIFICATION_TARGET' | 'NOTIFICATION_TEMPLATE' | 'NOTIFICATION_REQUEST' | 'NOTIFICATION' | 'NOTIFICATION_RULE' | 'QUEUE_STATS' | 'OAUTH2_CLIENT' | 'DOMAIN' | 'MOBILE_APP' | 'MOBILE_APP_BUNDLE' | 'CALCULATED_FIELD' | 'JOB' | 'ADMIN_SETTINGS' | 'AI_MODEL' | 'API_KEY'}; export type JsonNode = unknown; export type TenantId = {id: string, entityType: 'TENANT'}; export type OAuth2BasicMapperConfig = {emailAttributeKey?: string | undefined, firstNameAttributeKey?: string | undefined, lastNameAttributeKey?: string | undefined, tenantNameStrategy: 'DOMAIN' | 'EMAIL' | 'CUSTOM', tenantNamePattern?: string | undefined, customerNamePattern?: string | undefined, defaultDashboardName?: string | undefined, alwaysFullScreen?: boolean | undefined}; export type OAuth2CustomMapperConfig = {url?: string | undefined, username?: string | undefined, password?: string | undefined, sendToken?: boolean | undefined}; export type OAuth2MapperConfig = {allowUserCreation?: boolean | undefined, activateUser?: boolean | undefined, type: 'BASIC' | 'CUSTOM' | 'GITHUB' | 'APPLE', basic?: OAuth2BasicMapperConfig | undefined, custom?: OAuth2CustomMapperConfig | undefined}; export type OAuth2Client = {id?: OAuth2ClientId | undefined, createdTime?: number | undefined, additionalInfo: JsonNode, tenantId?: TenantId | undefined, title: string, mapperConfig: OAuth2MapperConfig, clientId: string, clientSecret: string, authorizationUri: string, accessTokenUri: string, scope: Array, userInfoUri?: string | undefined, userNameAttributeName: string, jwkSetUri?: string | undefined, clientAuthenticationMethod: string, loginButtonLabel: string, loginButtonIcon?: string | undefined, platforms?: (Array<'WEB' | 'ANDROID' | 'IOS'>) | undefined, name?: string | undefined}; export type CreateApiApiOauth2ClientArgs = {body: OAuth2Client}; export type CreateApiApiOauth2ClientOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const oAuth2ClientId = z.object({id: z.string(), entityType: z.enum(["TENANT", "CUSTOMER", "USER", "DASHBOARD", "ASSET", "DEVICE", "ALARM", "RULE_CHAIN", "RULE_NODE", "ENTITY_VIEW", "WIDGETS_BUNDLE", "WIDGET_TYPE", "TENANT_PROFILE", "DEVICE_PROFILE", "ASSET_PROFILE", "API_USAGE_STATE", "TB_RESOURCE", "OTA_PACKAGE", "EDGE", "RPC", "QUEUE", "NOTIFICATION_TARGET", "NOTIFICATION_TEMPLATE", "NOTIFICATION_REQUEST", "NOTIFICATION", "NOTIFICATION_RULE", "QUEUE_STATS", "OAUTH2_CLIENT", "DOMAIN", "MOBILE_APP", "MOBILE_APP_BUNDLE", "CALCULATED_FIELD", "JOB", "ADMIN_SETTINGS", "AI_MODEL", "API_KEY"])}); export const jsonNode = z.unknown(); export const tenantId = z.object({id: z.string(), entityType: z.literal("TENANT")}); export const oAuth2BasicMapperConfig = z.object({emailAttributeKey: z.string().optional(), firstNameAttributeKey: z.string().optional(), lastNameAttributeKey: z.string().optional(), tenantNameStrategy: z.enum(["DOMAIN", "EMAIL", "CUSTOM"]), tenantNamePattern: z.string().optional(), customerNamePattern: z.string().optional(), defaultDashboardName: z.string().optional(), alwaysFullScreen: z.boolean().optional()}); export const oAuth2CustomMapperConfig = z.object({url: z.string().optional(), username: z.string().optional(), password: z.string().optional(), sendToken: z.boolean().optional()}); export const oAuth2MapperConfig = z.object({allowUserCreation: z.boolean().optional(), activateUser: z.boolean().optional(), type: z.enum(["BASIC", "CUSTOM", "GITHUB", "APPLE"]), basic: oAuth2BasicMapperConfig.optional(), custom: oAuth2CustomMapperConfig.optional()}); export const oAuth2Client = z.object({id: oAuth2ClientId.optional(), createdTime: z.number().int().optional(), additionalInfo: jsonNode, tenantId: tenantId.optional(), title: z.string().min(1), mapperConfig: oAuth2MapperConfig, clientId: z.string().min(1), clientSecret: z.string().min(1), authorizationUri: z.string().min(1), accessTokenUri: z.string().min(1), scope: z.array(z.string()), userInfoUri: z.string().optional(), userNameAttributeName: z.string().min(1), jwkSetUri: z.string().optional(), clientAuthenticationMethod: z.string().min(1), loginButtonLabel: z.string().min(1), loginButtonIcon: z.string().optional(), platforms: z.array(z.enum(["WEB", "ANDROID", "IOS"])).optional(), name: z.string().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Save OAuth2 Client (saveOAuth2Client) * * POST /api/oauth2/client */ export const createApiApiOauth2Client = async (args: CreateApiApiOauth2ClientArgs, options?: CreateApiApiOauth2ClientOptions) => { const {baseUrl = "https://demo.thingsboard.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/oauth2/client${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(oAuth2Client, await res.json()) };