diff --git a/projects/developer/src/lib/api/developerErrorMessage.spec.ts b/projects/developer/src/lib/api/developerErrorMessage.spec.ts index 03f587af..3449d2bb 100644 --- a/projects/developer/src/lib/api/developerErrorMessage.spec.ts +++ b/projects/developer/src/lib/api/developerErrorMessage.spec.ts @@ -19,6 +19,18 @@ const API_ERROR_CODES = [ 'github_account_taken', 'github_account_mismatch', 'production_apps_unavailable', + 'application_not_dev', + 'user_not_found', + 'cannot_allow_owner', + 'allowed_user_limit_reached', + 'owner_only', + 'production_review_pending', + 'production_application_linked', + 'production_review_conflict', + 'production_requires_sign_in', + 'profile_not_found', + 'review_not_found', + 'redirect_not_allowed', ]; describe('developerErrorMessage', () => { diff --git a/projects/developer/src/lib/api/developerErrorMessage.ts b/projects/developer/src/lib/api/developerErrorMessage.ts index a7a3f2a2..4703fd4d 100644 --- a/projects/developer/src/lib/api/developerErrorMessage.ts +++ b/projects/developer/src/lib/api/developerErrorMessage.ts @@ -22,16 +22,25 @@ const DEVELOPER_ERROR_MESSAGES = { 'This GitHub account is already connected to another Trakt account.', github_account_mismatch: 'Your Trakt account is connected to a different GitHub account. Use Switch GitHub account to change it.', - dev_redirect_not_local: - 'Development apps can only redirect to localhost, 127.0.0.1 or [::1].', production_apps_unavailable: - 'Production apps are currently unavailable. Contact support@trakt.tv if you need one.', + 'Create a Development app first, then request Production access from its page.', application_not_dev: 'Only development apps have a sign-in list.', user_not_found: 'No Trakt account has that username.', cannot_allow_owner: 'You own this app, so you can always sign in to it.', allowed_user_limit_reached: 'This app already has 16 people who can sign in. Remove someone to add another.', owner_only: 'Only the app owner can do this.', + production_review_pending: 'A review is already waiting for this app.', + production_application_linked: + 'Delete the Production app first, then delete this Development app.', + production_review_conflict: + 'Another request was just sent for this app. Reload to see it.', + production_requires_sign_in: + 'This Production app already supports sign-in. Choose PKCE or device code.', + profile_not_found: 'This app has no app information yet.', + review_not_found: 'This app has no review yet.', + redirect_not_allowed: + 'Production redirect URIs must use https:// on a domain you control. Localhost and custom app schemes only work on Development apps.', } as const; type DeveloperErrorCode = keyof typeof DEVELOPER_ERROR_MESSAGES; diff --git a/projects/developer/src/lib/features/apps/ApplicationForm.svelte b/projects/developer/src/lib/features/apps/ApplicationForm.svelte index 359c2cbf..984fccbe 100644 --- a/projects/developer/src/lib/features/apps/ApplicationForm.svelte +++ b/projects/developer/src/lib/features/apps/ApplicationForm.svelte @@ -1,6 +1,5 @@ + +{#snippet links(urls: string[])} + +{/snippet} + +
+
What it does
+
{profile.summary}
+
Open source
+
{profile.open_source ? "Yes" : "No"}
+
Links
+
{@render links(profile.product_links)}
+
Privacy policy
+
{@render links([profile.privacy_url])}
+
Trakt notice
+
{@render links(profile.notice_links)}
+
Expected users
+
{profile.expected_mau.toLocaleString()} a month
+
Uses Trakt for
+
{profileUsageLabel(profile)}
+
Movie and show data
+
{profile.other_data_sources ?? "Only Trakt"}
+
Syncs with
+
{profile.other_sync_services ?? "Only Trakt"}
+ {#if updated}
Updated
+
{formatDate(updated.at)} by @{updated.by}
{/if} +
+ + diff --git a/projects/developer/src/lib/features/apps/ApplicationProfileDraft.ts b/projects/developer/src/lib/features/apps/ApplicationProfileDraft.ts new file mode 100644 index 00000000..9e2d1b89 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ApplicationProfileDraft.ts @@ -0,0 +1,16 @@ +import type { ProductionSignIn } from './ProductionSignIn.ts'; + +export type ApplicationProfileDraft = { + summary: string; + openSource: boolean; + productLinks: string; + privacyUrl: string; + noticeLinks: string; + expectedMau: string; + signIn: ProductionSignIn; + writesUserData: boolean; + usesOtherData: boolean; + otherDataSources: string; + syncsElsewhere: boolean; + otherSyncServices: string; +}; diff --git a/projects/developer/src/lib/features/apps/ApplicationProfileForm.svelte b/projects/developer/src/lib/features/apps/ApplicationProfileForm.svelte new file mode 100644 index 00000000..afe8418c --- /dev/null +++ b/projects/developer/src/lib/features/apps/ApplicationProfileForm.svelte @@ -0,0 +1,569 @@ + + +
{ + event.preventDefault(); + if (busy) return; + void submit(); + }} +> +
+ + {#snippet control(attributes)} + + {/snippet} + + + + + + {#snippet control(attributes)} + + {/snippet} + + + + {#snippet control(attributes)} + + {/snippet} + + + + {#snippet control(attributes)} + + {/snippet} + + + + {#snippet control(attributes)} + + {/snippet} + + + value !== "none")} + hint={draft.signIn === "none" + ? "Apps that only read public data get read-only Production access: they use their own Client ID and nobody signs in. To let users sign in later, request another review." + : undefined} + bind:value={draft.signIn} + /> + + {#if draft.signIn !== "none"} + + {/if} + +
+ + + {#if otherData === "others"} + + {#snippet control(attributes)} + + {/snippet} + + {/if} +
+ +
+ + + {#if otherSync === "others"} + + {#snippet control(attributes)} + + {/snippet} + + {/if} +
+ + {#if asksRedirects} + + {#snippet control(attributes)} + + {/snippet} + + {/if} + + {#if !hasClientSecret && draft.signIn !== "none"} +
+ + + {#if wantsSecret} + + {#snippet control(attributes)} + + {/snippet} + + {/if} +
+ {/if} + +
+ + {#snippet label()} + {appName} follows the + API Use Policy, + including the Trakt notice. + {/snippet} + {#snippet control(attributes)} + + {/snippet} + + + {#if wantsSecret || hasClientSecret} + + {#snippet control(attributes)} + + {/snippet} + + {/if} +
+ +

+ {createsProductionApp && draft.signIn !== "none" + ? "Production access lets anyone with a Trakt account sign in to your app." + : premium + ? "Changes apply right away. A Client Secret waits for a review." + : "Nothing changes until the review is granted."} Granting a review is not + an endorsement or certification of your app or how you use it. You stay responsible + for following the API Use Policy and the law. We can remove access at any time. +

+ + {#if issues.length > 0}

{issueSummary}

{/if} +
+ +
+ +
+
+ + diff --git a/projects/developer/src/lib/features/apps/ApplicationProfileFormProps.ts b/projects/developer/src/lib/features/apps/ApplicationProfileFormProps.ts new file mode 100644 index 00000000..32811e3c --- /dev/null +++ b/projects/developer/src/lib/features/apps/ApplicationProfileFormProps.ts @@ -0,0 +1,19 @@ +import type { DeveloperTier } from '$lib/features/premium/DeveloperTier.ts'; +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; +import type { ProductionReviewInput } from './ProductionReviewInput.ts'; + +export type ApplicationProfileFormProps = { + appName: string; + profile: ApplicationProfileInput | null; + createsProductionApp: boolean; + redirectsNeeded: boolean; + allowsPublicDataOnly: boolean; + initialRedirects?: string; + initialSecretReason?: string | null; + asksForSecret?: boolean; + tier: DeveloperTier; + hasClientSecret: boolean; + busy: boolean; + onSubmit: (review: ProductionReviewInput) => void; + onCancel: () => void; +}; diff --git a/projects/developer/src/lib/features/apps/ApplicationProfileInput.ts b/projects/developer/src/lib/features/apps/ApplicationProfileInput.ts new file mode 100644 index 00000000..7dafd2e8 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ApplicationProfileInput.ts @@ -0,0 +1,6 @@ +import type { ApplicationProfile } from './ApplicationProfile.ts'; + +export type ApplicationProfileInput = Omit< + ApplicationProfile, + 'updated_at' | 'updated_by' +>; diff --git a/projects/developer/src/lib/features/apps/Applications.svelte b/projects/developer/src/lib/features/apps/Applications.svelte index 89545e1f..ebf844f2 100644 --- a/projects/developer/src/lib/features/apps/Applications.svelte +++ b/projects/developer/src/lib/features/apps/Applications.svelte @@ -27,6 +27,9 @@ import type { AppSection } from "./AppSection.ts"; import MembersPanel from "./MembersPanel.svelte"; import PkceNotice from "./PkceNotice.svelte"; + import { productionNeedsRedirects } from "./productionNeedsRedirects.ts"; + import ProductionPanel from "./ProductionPanel.svelte"; + import { productionCardBadge } from "./productionCardBadge.ts"; import RedirectUriWarning from "./RedirectUriWarning.svelte"; import { unsafeRedirectUris } from "./unsafeRedirectUris.ts"; import { developerApiHost } from "$lib/features/premium/developerApiHost.ts"; @@ -120,6 +123,13 @@ { id: "credentials", label: "Credentials" }, { id: "settings", label: "Settings" }, { id: "details", label: "Details" }, + { + id: "production", + label: + selected.dev && !selected.linked_application + ? "Production access" + : "App information", + }, { id: "members", label: `Members · ${memberCount}` }, ...(isOwner ? [{ id: "delete", label: "Delete app" }] : []), ] @@ -254,6 +264,19 @@ loading = false; } + async function refresh() { + try { + const next = await listApplications(slot); + if (alive) apps = next; + } catch (cause) { + if (alive) + error = + cause instanceof Error + ? cause.message + : "Could not reload your apps."; + } + } + async function save(input: ApplicationInput) { if (busy || (mode === "edit" && !selected)) return; busy = true; @@ -308,13 +331,19 @@ {title} | Trakt Developer {#snippet appCard(app: Application)} + {@const badge = productionCardBadge(app.production_review)}
</>{#if app.dev}Development{/if}{app.approved ? "Approved" : "Pending approval"}{/if}{#if app.app_type === "production_read_only"}Read-only{/if}{#if badge}{badge.label}{/if}{#if !app.approved}Blocked{/if}

{app.name}

@@ -368,6 +397,10 @@ class="badge" data-variant="dev">Development{/if} + {#if mode !== "list" && selected?.app_type === "production_read_only"}Read-only{/if} {#if mode !== "list" && selected?.role === "manager"}Managed - + {#if selected.client_secret}
Client Secret DeprecatedClient Secret {#if selected.client_secret_granted}Server to server{:else}Deprecated{/if}
Your role
Manager
{/if}
Type
-
{selected.dev ? "Development" : "Production"}
-
Status
-
{selected.approved ? "Approved" : "Pending approval"}
-
Created
-
{formatDate(selected.created_at)}
- {#if selected.approved_at}
Approved
+
+ {selected.dev + ? "Development" + : selected.app_type === "production_read_only" + ? "Production (read-only: public data, no sign-in)" + : "Production"} +
+ {#if selected.linked_application}
+ {selected.linked_application.dev + ? "Development app" + : "Production app"} +
- {formatDate(selected.approved_at)} + {selected.linked_application.name}
{/if} +
API key
+
{selected.approved ? "Active" : "Blocked by Trakt"}
+
Created
+
{formatDate(selected.created_at)}
{#if tier && isOwner}
Plan
@@ -618,6 +672,17 @@ +
+ +
+
+ import type { ChoiceGroupProps } from "./ChoiceGroupProps.ts"; + + let { + legend, + name, + options, + value = $bindable(), + hint, + }: ChoiceGroupProps = $props(); + + const hintId = $props.id(); + + +
+ {legend} + {#each options as option (option.value)}{/each} + {#if hint}{hint}{/if} +
+ + diff --git a/projects/developer/src/lib/features/apps/ChoiceGroupProps.ts b/projects/developer/src/lib/features/apps/ChoiceGroupProps.ts new file mode 100644 index 00000000..3ed507d8 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ChoiceGroupProps.ts @@ -0,0 +1,7 @@ +export type ChoiceGroupProps = { + legend: string; + name: string; + options: readonly { value: T; label: string; hint?: string }[]; + value: T; + hint?: string; +}; diff --git a/projects/developer/src/lib/features/apps/DEVELOPMENT_SEAT_LIMIT.ts b/projects/developer/src/lib/features/apps/DEVELOPMENT_SEAT_LIMIT.ts new file mode 100644 index 00000000..1f568384 --- /dev/null +++ b/projects/developer/src/lib/features/apps/DEVELOPMENT_SEAT_LIMIT.ts @@ -0,0 +1 @@ +export const DEVELOPMENT_SEAT_LIMIT = 16; diff --git a/projects/developer/src/lib/features/apps/FormField.svelte b/projects/developer/src/lib/features/apps/FormField.svelte new file mode 100644 index 00000000..73e17809 --- /dev/null +++ b/projects/developer/src/lib/features/apps/FormField.svelte @@ -0,0 +1,92 @@ + + +{#snippet labelText()} + {#if typeof label === "string"}{label}{:else}{@render label()}{/if} +{/snippet} + +
+ {#if variant === "check"} + + {:else} + + {#if hint}{hint}{/if} + {@render control(attributes)} + {/if} + + {#if warning}{warning}{/if} + {#if error}{error}{/if} +
+ + diff --git a/projects/developer/src/lib/features/apps/FormFieldControlAttributes.ts b/projects/developer/src/lib/features/apps/FormFieldControlAttributes.ts new file mode 100644 index 00000000..0454fd01 --- /dev/null +++ b/projects/developer/src/lib/features/apps/FormFieldControlAttributes.ts @@ -0,0 +1,5 @@ +export type FormFieldControlAttributes = { + id: string; + 'aria-invalid': 'true' | undefined; + 'aria-describedby': string | undefined; +}; diff --git a/projects/developer/src/lib/features/apps/FormFieldProps.ts b/projects/developer/src/lib/features/apps/FormFieldProps.ts new file mode 100644 index 00000000..5f69b35c --- /dev/null +++ b/projects/developer/src/lib/features/apps/FormFieldProps.ts @@ -0,0 +1,15 @@ +import type { Snippet } from 'svelte'; +import type { FormFieldControlAttributes } from './FormFieldControlAttributes.ts'; +import type { ProductionFormField } from './ProductionFormField.ts'; + +export type FormFieldProps = { + uid: string; + field: ProductionFormField; + label: string | Snippet; + hint?: string; + warning?: string; + error?: string; + variant?: 'stacked' | 'check'; + size?: 'default' | 'small'; + control: Snippet<[FormFieldControlAttributes]>; +}; diff --git a/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_LIMIT.ts b/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_LIMIT.ts new file mode 100644 index 00000000..11a279ad --- /dev/null +++ b/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_LIMIT.ts @@ -0,0 +1 @@ +export const PROFILE_SUMMARY_LIMIT = 500; diff --git a/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_MINIMUM.ts b/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_MINIMUM.ts new file mode 100644 index 00000000..51f4297f --- /dev/null +++ b/projects/developer/src/lib/features/apps/PROFILE_SUMMARY_MINIMUM.ts @@ -0,0 +1 @@ +export const PROFILE_SUMMARY_MINIMUM = 100; diff --git a/projects/developer/src/lib/features/apps/ProductionFormField.ts b/projects/developer/src/lib/features/apps/ProductionFormField.ts new file mode 100644 index 00000000..6f644f76 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionFormField.ts @@ -0,0 +1,12 @@ +export type ProductionFormField = + | 'summary' + | 'productLinks' + | 'privacyUrl' + | 'noticeLinks' + | 'expectedMau' + | 'otherDataSources' + | 'otherSyncServices' + | 'redirects' + | 'secretReason' + | 'confirmPolicy' + | 'confirmSecret'; diff --git a/projects/developer/src/lib/features/apps/ProductionFormIssue.ts b/projects/developer/src/lib/features/apps/ProductionFormIssue.ts new file mode 100644 index 00000000..b3f28e22 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionFormIssue.ts @@ -0,0 +1,6 @@ +import type { ProductionFormField } from './ProductionFormField.ts'; + +export type ProductionFormIssue = { + field: ProductionFormField; + message: string; +}; diff --git a/projects/developer/src/lib/features/apps/ProductionPanel.svelte b/projects/developer/src/lib/features/apps/ProductionPanel.svelte new file mode 100644 index 00000000..24cfb54b --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionPanel.svelte @@ -0,0 +1,378 @@ + + +
+

+ {createsProductionApp ? "Production access" : "App information"} +

+ + {#if linked}

+ {linked.dev ? "Development app" : "Production app"}: + {linked.name} +

{/if} + + {#if createsProductionApp}

+ A Development app covers you plus up to {DEVELOPMENT_SEAT_LIMIT} people you + invite, with any redirect URI. When {app.name} is ready for everyone, request + Production access: you get a separate Production app with its own Client ID, + and this one stays your sandbox. +

{:else if productionReadOnly}

+ Read-only Production access: your Production app reads public data and + nobody can sign in to it. To let users sign in, update your app + information to say how they sign in and request a review. +

{:else}

+ Changes to your app information or a Client Secret go through a review. + Nothing changes until it's granted. +

{/if} + +
+ + {#if notice}

{notice}

{/if} +
+ + {#if error}{/if} + + {#if editing} + { + editing = null; + error = ""; + }} + /> + {:else if loading} +

Loading app information…

+ {:else} + {#if review && status !== "granted" && status !== "granted_instantly"} +
+ What you asked for + + {#if review.redirect_uri.length > 0}

+ Production redirect URIs: {review.redirect_uri.join(", ")} +

{/if} + {#if review.client_secret_reason}

+ Client Secret requested: {review.client_secret_reason} +

{/if} +
+ {/if} + + {#if profile}

Current app information

+ + {:else if !app.has_profile && !createsProductionApp}

+ Add your app information so we know how {app.name} uses Trakt. It goes through + a review like any other change. +

{/if} + + {#if canRequest}
+ {#if reopensReview}{:else if createsProductionApp}{/if} + {#if !createsProductionApp}{#if !hasClientSecret && !productionReadOnly}{/if}{/if} +
{/if} + + {#if !isOwner}

+ Only the owner, @{app.owner.username}, can request a review. +

{/if} + {/if} +
+ + diff --git a/projects/developer/src/lib/features/apps/ProductionPanelProps.ts b/projects/developer/src/lib/features/apps/ProductionPanelProps.ts new file mode 100644 index 00000000..7bc84089 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionPanelProps.ts @@ -0,0 +1,11 @@ +import type { DeveloperTier } from '$lib/features/premium/DeveloperTier.ts'; +import type { Application } from './Application.ts'; + +export type ProductionPanelProps = { + slot: number; + app: Application; + redirectsNeeded: boolean; + tier: DeveloperTier; + readOnly: boolean; + onChanged: () => Promise; +}; diff --git a/projects/developer/src/lib/features/apps/ProductionReview.ts b/projects/developer/src/lib/features/apps/ProductionReview.ts new file mode 100644 index 00000000..46f43354 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionReview.ts @@ -0,0 +1,4 @@ +import type { z } from 'zod'; +import type { productionReviewSchema } from './productionReviewSchema.ts'; + +export type ProductionReview = z.infer; diff --git a/projects/developer/src/lib/features/apps/ProductionReviewAnswers.ts b/projects/developer/src/lib/features/apps/ProductionReviewAnswers.ts new file mode 100644 index 00000000..cd97d1fd --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionReviewAnswers.ts @@ -0,0 +1,9 @@ +export type ProductionReviewAnswers = { + redirectsNeeded: boolean; + redirects: string; + needsSecret: boolean; + secretReason: string; + confirmPolicy: boolean; + confirmSecret: boolean; + hasClientSecret: boolean; +}; diff --git a/projects/developer/src/lib/features/apps/ProductionReviewDetail.ts b/projects/developer/src/lib/features/apps/ProductionReviewDetail.ts new file mode 100644 index 00000000..68f90163 --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionReviewDetail.ts @@ -0,0 +1,6 @@ +import type { z } from 'zod'; +import type { productionReviewDetailSchema } from './productionReviewDetailSchema.ts'; + +export type ProductionReviewDetail = z.infer< + typeof productionReviewDetailSchema +>; diff --git a/projects/developer/src/lib/features/apps/ProductionReviewInput.ts b/projects/developer/src/lib/features/apps/ProductionReviewInput.ts new file mode 100644 index 00000000..b852544e --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionReviewInput.ts @@ -0,0 +1,9 @@ +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; + +export type ProductionReviewInput = { + profile: ApplicationProfileInput; + redirect_uri: string[]; + client_secret: { reason: string } | null; + confirm_api_use_policy: true; + confirm_secret_not_shipped?: true; +}; diff --git a/projects/developer/src/lib/features/apps/ProductionSignIn.ts b/projects/developer/src/lib/features/apps/ProductionSignIn.ts new file mode 100644 index 00000000..256bb3db --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionSignIn.ts @@ -0,0 +1,4 @@ +import type { z } from 'zod'; +import type { productionSignInSchema } from './productionSignInSchema.ts'; + +export type ProductionSignIn = z.infer; diff --git a/projects/developer/src/lib/features/apps/ProductionStatus.ts b/projects/developer/src/lib/features/apps/ProductionStatus.ts new file mode 100644 index 00000000..df17b38b --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionStatus.ts @@ -0,0 +1,4 @@ +import type { z } from 'zod'; +import type { productionStatusSchema } from './productionStatusSchema.ts'; + +export type ProductionStatus = z.infer; diff --git a/projects/developer/src/lib/features/apps/ProductionStatusBanner.svelte b/projects/developer/src/lib/features/apps/ProductionStatusBanner.svelte new file mode 100644 index 00000000..21369c5c --- /dev/null +++ b/projects/developer/src/lib/features/apps/ProductionStatusBanner.svelte @@ -0,0 +1,65 @@ + + +{#if copy}
+ {copy.title} + {#if review?.review_note}
+ {review.review_note} +
{/if} +

{copy.detail}

+
{/if} + + diff --git a/projects/developer/src/lib/features/apps/applicationProfileIssues.spec.ts b/projects/developer/src/lib/features/apps/applicationProfileIssues.spec.ts new file mode 100644 index 00000000..db47dce2 --- /dev/null +++ b/projects/developer/src/lib/features/apps/applicationProfileIssues.spec.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import type { ApplicationProfileDraft } from './ApplicationProfileDraft.ts'; +import { applicationProfileIssues } from './applicationProfileIssues.ts'; + +const draft: ApplicationProfileDraft = { + summary: 'a'.repeat(120), + openSource: false, + productLinks: 'https://example.app', + privacyUrl: 'https://example.app/privacy', + noticeLinks: 'https://example.app/about', + expectedMau: '2000', + signIn: 'pkce', + writesUserData: true, + usesOtherData: false, + otherDataSources: '', + syncsElsewhere: false, + otherSyncServices: '', +}; + +describe('applicationProfileIssues', () => { + it('finds nothing in a complete draft', () => { + expect(applicationProfileIssues(draft)).toEqual([]); + }); + + it('lists every field with a problem, in form order', () => { + const issues = applicationProfileIssues({ + ...draft, + summary: 'Too short', + privacyUrl: '', + expectedMau: 'lots', + syncsElsewhere: true, + }); + + expect(issues.map((issue) => issue.field)).toEqual([ + 'summary', + 'privacyUrl', + 'expectedMau', + 'otherSyncServices', + ]); + }); + + it('accepts the Workers limits and flags values just over them', () => { + const link = (length: number) => 'https://example.app/'.padEnd(length, 'a'); + const atLimits = { + ...draft, + productLinks: link(2048), + privacyUrl: link(500), + noticeLinks: link(2048), + expectedMau: '4294967295', + }; + expect(applicationProfileIssues(atLimits)).toEqual([]); + + expect( + applicationProfileIssues({ + ...atLimits, + productLinks: link(2049), + privacyUrl: link(501), + noticeLinks: link(2049), + expectedMau: '4294967296', + }).map((issue) => issue.field), + ).toEqual(['productLinks', 'privacyUrl', 'noticeLinks', 'expectedMau']); + }); + + it('ignores the other services fields while they are hidden', () => { + expect( + applicationProfileIssues({ ...draft, otherDataSources: 'x'.repeat(300) }), + ).toEqual([]); + }); +}); diff --git a/projects/developer/src/lib/features/apps/applicationProfileIssues.ts b/projects/developer/src/lib/features/apps/applicationProfileIssues.ts new file mode 100644 index 00000000..ab02b939 --- /dev/null +++ b/projects/developer/src/lib/features/apps/applicationProfileIssues.ts @@ -0,0 +1,102 @@ +import type { ApplicationProfileDraft } from './ApplicationProfileDraft.ts'; +import { isWebUrl } from './isWebUrl.ts'; +import { PROFILE_SUMMARY_LIMIT } from './PROFILE_SUMMARY_LIMIT.ts'; +import { PROFILE_SUMMARY_MINIMUM } from './PROFILE_SUMMARY_MINIMUM.ts'; +import type { ProductionFormField } from './ProductionFormField.ts'; +import type { ProductionFormIssue } from './ProductionFormIssue.ts'; +import { splitLinks } from './splitLinks.ts'; + +const LINK_LIMIT = 10; +const LINK_MAX_LENGTH = 2048; +const PRIVACY_URL_MAX_LENGTH = 500; +const EXPECTED_MAU_MAX = 4_294_967_295; +const OTHER_SERVICES_LIMIT = 255; + +function summaryIssue(text: string): string | null { + const length = text.trim().length; + if (length < PROFILE_SUMMARY_MINIMUM) { + return `Describe what your app does in at least ${PROFILE_SUMMARY_MINIMUM} characters.`; + } + if (length > PROFILE_SUMMARY_LIMIT) { + return `Keep the description within ${PROFILE_SUMMARY_LIMIT} characters.`; + } + + return null; +} + +function linksIssue(text: string, label: string): string | null { + const links = splitLinks(text); + if (links.length === 0) return `Add at least one ${label}.`; + if (links.length > LINK_LIMIT) return `Add up to ${LINK_LIMIT} ${label}s.`; + + if (links.some((link) => link.length > LINK_MAX_LENGTH)) { + return `Keep each ${label} within 2,048 characters.`; + } + + const invalid = links.find((link) => !isWebUrl(link) || /\s/.test(link)); + if (invalid) return `${invalid} isn't a valid http:// or https:// link.`; + + return null; +} + +function privacyIssue(text: string): string | null { + const url = text.trim(); + if (url.length > PRIVACY_URL_MAX_LENGTH) { + return `Keep the privacy policy link within ${PRIVACY_URL_MAX_LENGTH} characters.`; + } + if (isWebUrl(url) && !/\s/.test(url)) return null; + + return 'Enter a valid link to your privacy policy.'; +} + +function mauIssue(text: string): string | null { + const mau = text.trim(); + if (/^\d+$/.test(mau)) { + return Number(mau) <= EXPECTED_MAU_MAX + ? null + : 'Enter no more than 4,294,967,295 expected monthly active users.'; + } + + return 'Enter your expected monthly active users as a number.'; +} + +function otherIssue(enabled: boolean, text: string, label: string) { + if (!enabled) return null; + + const value = text.trim(); + if (!value) return `Name the other ${label} your app uses.`; + if (value.length > OTHER_SERVICES_LIMIT) { + return `Keep the other ${label} within ${OTHER_SERVICES_LIMIT} characters.`; + } + + return null; +} + +/** Every problem in a profile draft, at most one per field, in form order. */ +export function applicationProfileIssues( + draft: ApplicationProfileDraft, +): ReadonlyArray { + const checks: ReadonlyArray<[ProductionFormField, string | null]> = [ + ['summary', summaryIssue(draft.summary)], + ['productLinks', linksIssue(draft.productLinks, 'link to your app')], + ['privacyUrl', privacyIssue(draft.privacyUrl)], + ['noticeLinks', linksIssue(draft.noticeLinks, 'notice link')], + ['expectedMau', mauIssue(draft.expectedMau)], + [ + 'otherDataSources', + otherIssue(draft.usesOtherData, draft.otherDataSources, 'data sources'), + ], + [ + 'otherSyncServices', + otherIssue( + draft.syncsElsewhere, + draft.otherSyncServices, + 'sync services', + ), + ], + ]; + + return checks.flatMap(([field, message]) => + message ? [{ field, message }] : [], + ); +} diff --git a/projects/developer/src/lib/features/apps/applicationProfileSchema.ts b/projects/developer/src/lib/features/apps/applicationProfileSchema.ts new file mode 100644 index 00000000..89952d4e --- /dev/null +++ b/projects/developer/src/lib/features/apps/applicationProfileSchema.ts @@ -0,0 +1,17 @@ +import { z } from 'zod'; +import { productionSignInSchema } from './productionSignInSchema.ts'; + +export const applicationProfileSchema = z.object({ + summary: z.string(), + open_source: z.boolean(), + product_links: z.array(z.string()), + privacy_url: z.string(), + notice_links: z.array(z.string()), + expected_mau: z.number(), + sign_in: productionSignInSchema, + writes_user_data: z.boolean(), + other_data_sources: z.string().nullable(), + other_sync_services: z.string().nullable(), + updated_at: z.string(), + updated_by: z.object({ username: z.string() }), +}); diff --git a/projects/developer/src/lib/features/apps/applicationSchema.ts b/projects/developer/src/lib/features/apps/applicationSchema.ts index ffa47256..6545bb02 100644 --- a/projects/developer/src/lib/features/apps/applicationSchema.ts +++ b/projects/developer/src/lib/features/apps/applicationSchema.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { productionReviewSchema } from './productionReviewSchema.ts'; export const applicationSchema = z.object({ id: z.number(), @@ -6,6 +7,7 @@ export const applicationSchema = z.object({ description: z.string().nullish(), client_id: z.string(), client_secret: z.string().nullish(), + client_secret_granted: z.boolean().nullish(), redirect_uri: z.string(), origins: z.array(z.string()), approved: z.boolean(), @@ -13,6 +15,9 @@ export const applicationSchema = z.object({ scopes: z.array(z.string()), created_at: z.string(), dev: z.boolean(), + app_type: z + .enum(['development', 'production_read_only', 'production']) + .nullish(), allowed_user_count: z.number(), manager_count: z.number(), role: z.enum(['owner', 'manager']), @@ -22,4 +27,15 @@ export const applicationSchema = z.object({ checkin: z.boolean().nullish(), account_create: z.boolean().nullish(), }), + linked_application: z + .object({ + id: z.number(), + name: z.string(), + dev: z.boolean(), + read_only: z.boolean(), + has_client_secret: z.boolean(), + }) + .nullish(), + production_review: productionReviewSchema.nullish(), + has_profile: z.boolean().nullish(), }); diff --git a/projects/developer/src/lib/features/apps/asksProductionRedirects.spec.ts b/projects/developer/src/lib/features/apps/asksProductionRedirects.spec.ts new file mode 100644 index 00000000..2aa724c7 --- /dev/null +++ b/projects/developer/src/lib/features/apps/asksProductionRedirects.spec.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { asksProductionRedirects } from './asksProductionRedirects.ts'; + +describe('asksProductionRedirects', () => { + it('asks only PKCE apps that need Production redirects', () => { + expect( + asksProductionRedirects({ redirectsNeeded: true, signIn: 'pkce' }), + ).toBe(true); + expect( + asksProductionRedirects({ redirectsNeeded: true, signIn: 'device_code' }), + ).toBe(false); + expect( + asksProductionRedirects({ redirectsNeeded: false, signIn: 'pkce' }), + ).toBe(false); + }); +}); diff --git a/projects/developer/src/lib/features/apps/asksProductionRedirects.ts b/projects/developer/src/lib/features/apps/asksProductionRedirects.ts new file mode 100644 index 00000000..1cf9128c --- /dev/null +++ b/projects/developer/src/lib/features/apps/asksProductionRedirects.ts @@ -0,0 +1,11 @@ +import type { ProductionSignIn } from './ProductionSignIn.ts'; + +export function asksProductionRedirects({ + redirectsNeeded, + signIn, +}: { + redirectsNeeded: boolean; + signIn: ProductionSignIn; +}): boolean { + return redirectsNeeded && signIn === 'pkce'; +} diff --git a/projects/developer/src/lib/features/apps/getApplicationProfile.ts b/projects/developer/src/lib/features/apps/getApplicationProfile.ts new file mode 100644 index 00000000..f73dd375 --- /dev/null +++ b/projects/developer/src/lib/features/apps/getApplicationProfile.ts @@ -0,0 +1,20 @@ +import { accountRequest } from '$lib/api/accountRequest.ts'; +import type { ApplicationProfile } from './ApplicationProfile.ts'; +import { applicationProfileSchema } from './applicationProfileSchema.ts'; + +export async function getApplicationProfile( + slot: number, + appId: number, +): Promise { + const response = await accountRequest({ + slot, + path: `/v3/users/me/applications/${appId}/profile`, + }); + const parsed = applicationProfileSchema.safeParse(await response.json()); + if (!parsed.success) { + throw new Error( + 'Your app information could not be read. Please try again.', + ); + } + return parsed.data; +} diff --git a/projects/developer/src/lib/features/apps/getProductionReview.ts b/projects/developer/src/lib/features/apps/getProductionReview.ts new file mode 100644 index 00000000..546687e0 --- /dev/null +++ b/projects/developer/src/lib/features/apps/getProductionReview.ts @@ -0,0 +1,18 @@ +import { accountRequest } from '$lib/api/accountRequest.ts'; +import type { ProductionReviewDetail } from './ProductionReviewDetail.ts'; +import { productionReviewDetailSchema } from './productionReviewDetailSchema.ts'; + +export async function getProductionReview( + slot: number, + appId: number, +): Promise { + const response = await accountRequest({ + slot, + path: `/v3/users/me/applications/${appId}/production-review`, + }); + const parsed = productionReviewDetailSchema.safeParse(await response.json()); + if (!parsed.success) { + throw new Error('Your last review could not be read. Please try again.'); + } + return parsed.data; +} diff --git a/projects/developer/src/lib/features/apps/isLoopbackRedirect.ts b/projects/developer/src/lib/features/apps/isLoopbackRedirect.ts deleted file mode 100644 index f0d43d04..00000000 --- a/projects/developer/src/lib/features/apps/isLoopbackRedirect.ts +++ /dev/null @@ -1,14 +0,0 @@ -const LOOPBACK_HOSTNAMES: ReadonlySet = new Set([ - 'localhost', - '127.0.0.1', - '[::1]', -]); - -export function isLoopbackRedirect(uri: string): boolean { - if (!URL.canParse(uri)) return false; - const { protocol, hostname } = new URL(uri); - return ( - (protocol === 'http:' || protocol === 'https:') && - LOOPBACK_HOSTNAMES.has(hostname.toLowerCase()) - ); -} diff --git a/projects/developer/src/lib/features/apps/isWebUrl.ts b/projects/developer/src/lib/features/apps/isWebUrl.ts new file mode 100644 index 00000000..96c2ef30 --- /dev/null +++ b/projects/developer/src/lib/features/apps/isWebUrl.ts @@ -0,0 +1,11 @@ +export function isWebUrl(value: string): boolean { + try { + const url = new URL(value); + return ( + ['http:', 'https:'].includes(url.protocol) && + value.toLowerCase().startsWith(`${url.protocol}//`) + ); + } catch { + return false; + } +} diff --git a/projects/developer/src/lib/features/apps/latestReview.spec.ts b/projects/developer/src/lib/features/apps/latestReview.spec.ts new file mode 100644 index 00000000..da69ea44 --- /dev/null +++ b/projects/developer/src/lib/features/apps/latestReview.spec.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import type { ProductionReview } from './ProductionReview.ts'; +import { latestReview } from './latestReview.ts'; + +const review = (id: number, status: ProductionReview['status']) => + ({ + id, + kind: 'production', + status, + submitted_at: '2026-11-09T12:00:00Z', + reviewed_at: null, + review_note: null, + client_secret_requested: false, + granted_access: null, + }) satisfies ProductionReview; + +describe('latestReview', () => { + it('uses the listed review until something was submitted', () => { + expect(latestReview(review(1, 'declined'), null)?.id).toBe(1); + expect(latestReview(undefined, null)).toBeNull(); + }); + + it('keeps a just-submitted review when the list is stale', () => { + expect(latestReview(undefined, review(2, 'pending'))?.status).toBe( + 'pending', + ); + expect(latestReview(review(1, 'declined'), review(2, 'pending'))?.id).toBe( + 2, + ); + }); + + it('prefers the list once it has caught up or moved on', () => { + expect( + latestReview(review(2, 'granted'), review(2, 'pending'))?.status, + ).toBe('granted'); + expect(latestReview(review(3, 'pending'), review(2, 'pending'))?.id).toBe( + 3, + ); + }); +}); diff --git a/projects/developer/src/lib/features/apps/latestReview.ts b/projects/developer/src/lib/features/apps/latestReview.ts new file mode 100644 index 00000000..e92f5e6b --- /dev/null +++ b/projects/developer/src/lib/features/apps/latestReview.ts @@ -0,0 +1,10 @@ +import type { ProductionReview } from './ProductionReview.ts'; + +export function latestReview( + listed: ProductionReview | null | undefined, + submitted: ProductionReview | null, +): ProductionReview | null { + if (!submitted) return listed ?? null; + if (!listed) return submitted; + return submitted.id > listed.id ? submitted : listed; +} diff --git a/projects/developer/src/lib/features/apps/nonLocalRedirectUris.spec.ts b/projects/developer/src/lib/features/apps/nonLocalRedirectUris.spec.ts deleted file mode 100644 index 226aedbc..00000000 --- a/projects/developer/src/lib/features/apps/nonLocalRedirectUris.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { nonLocalRedirectUris } from './nonLocalRedirectUris.ts'; - -describe('nonLocalRedirectUris', () => { - it('accepts localhost, 127.0.0.1 and [::1] on any port', () => { - expect( - nonLocalRedirectUris( - 'http://localhost:5173/callback\nhttp://127.0.0.1:4173\nhttp://[::1]:8080/cb', - ), - ).toEqual([]); - }); - - it('lists each non-local redirect once', () => { - expect( - nonLocalRedirectUris( - 'http://localhost:5173/callback\nhttps://example.com/cb\ntrakt://auth\nhttps://example.com/cb', - ), - ).toEqual(['https://example.com/cb', 'trakt://auth']); - }); -}); diff --git a/projects/developer/src/lib/features/apps/nonLocalRedirectUris.ts b/projects/developer/src/lib/features/apps/nonLocalRedirectUris.ts deleted file mode 100644 index 4658ded3..00000000 --- a/projects/developer/src/lib/features/apps/nonLocalRedirectUris.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { isLoopbackRedirect } from './isLoopbackRedirect.ts'; - -export function nonLocalRedirectUris(redirects: string): ReadonlyArray { - const lines = redirects.split('\n').map((line) => line.trim()); - return [ - ...new Set(lines.filter(Boolean).filter((uri) => !isLoopbackRedirect(uri))), - ]; -} diff --git a/projects/developer/src/lib/features/apps/parseApplication.spec.ts b/projects/developer/src/lib/features/apps/parseApplication.spec.ts index 7ded41f3..9041d2c2 100644 --- a/projects/developer/src/lib/features/apps/parseApplication.spec.ts +++ b/projects/developer/src/lib/features/apps/parseApplication.spec.ts @@ -22,6 +22,8 @@ describe('V3 application validation parity', () => { it.each([ 'javascript:alert(1)', 'data:text/plain,hello', + 'vbscript:msgbox(1)', + 'blob:https://example.com/callback', 'https://example.com/?code=x', 'https://example.com/#fragment', ])('rejects unsafe or unsupported callback %s', (uri) => { @@ -31,6 +33,7 @@ describe('V3 application validation parity', () => { description: '', redirects: uri, originsText: '', + dev: true, }), ).toThrow(); }); @@ -102,24 +105,54 @@ describe('V3 application validation parity', () => { ).toThrow(); }); - it('keeps a development app on localhost redirects', () => { - const base = { name: 'Dev App', description: '', originsText: '' }; + it('accepts hosted and native callbacks on a development app', () => { + const redirects = + 'http://localhost:5173/callback\nhttps://you.github.io/app/\nmyapp://callback\ncom.example.app:/oauth'; expect( parseApplication({ - ...base, - redirects: 'http://localhost:5173/callback', + name: 'Dev App', + description: '', + originsText: '', + redirects, dev: true, }).redirect_uri, - ).toEqual(['http://localhost:5173/callback']); + ).toEqual(redirects.split('\n')); + }); + + it('holds new or edited production redirects to public https', () => { + const base = { name: 'App', description: '', originsText: '' }; + expect(() => parseApplication({ ...base, - redirects: 'http://localhost:5173/callback\nhttps://example.com/cb', - dev: true, + redirects: + 'https://example.com/cb\nmyapp://callback\nhttp://localhost:5173', + enforceProductionRedirects: true, }), ).toThrow( - 'Development apps can only redirect to localhost. Remove https://example.com/cb.', + 'Production redirect URIs must use https:// on a domain you control. Change myapp://callback, http://localhost:5173.', ); + expect( + parseApplication({ + ...base, + redirects: 'myapp://callback', + enforceProductionRedirects: false, + }).redirect_uri, + ).toEqual(['myapp://callback']); + }); + + it('lets a read-only Production app save without a redirect', () => { + const base = { + name: 'Poster Wall', + description: '', + redirects: '', + originsText: '', + }; + + expect(() => parseApplication(base)).toThrow('Enter 1-25 redirect URIs'); + expect( + parseApplication({ ...base, redirectsOptional: true }).redirect_uri, + ).toEqual([]); }); }); diff --git a/projects/developer/src/lib/features/apps/parseApplication.ts b/projects/developer/src/lib/features/apps/parseApplication.ts index 3bc6c725..7378733d 100644 --- a/projects/developer/src/lib/features/apps/parseApplication.ts +++ b/projects/developer/src/lib/features/apps/parseApplication.ts @@ -1,11 +1,13 @@ import type { ApplicationInput } from './ApplicationInput.ts'; -import { nonLocalRedirectUris } from './nonLocalRedirectUris.ts'; +import { splitLines } from './splitLines.ts'; +import { unsafeRedirectUris } from './unsafeRedirectUris.ts'; -const lines = (value: string) => - value - .split('\n') - .map((line) => line.trim()) - .filter(Boolean); +const DANGEROUS_REDIRECT_SCHEMES: ReadonlySet = new Set([ + 'javascript:', + 'data:', + 'vbscript:', + 'blob:', +]); export function parseApplication({ name, @@ -13,15 +15,20 @@ export function parseApplication({ redirects, originsText, dev = false, + enforceProductionRedirects = false, + redirectsOptional = false, }: { name: string; description: string; redirects: string; originsText: string; dev?: boolean; + enforceProductionRedirects?: boolean; + /** Production apps without browser sign-in can have an empty redirect list. */ + redirectsOptional?: boolean; }): ApplicationInput { - const redirect_uri = lines(redirects); - const origins = lines(originsText); + const redirect_uri = splitLines(redirects); + const origins = splitLines(originsText); if (!name.trim() || name.trim().length > 255) { throw new Error('Enter an app name of 1-255 characters.'); @@ -30,7 +37,7 @@ export function parseApplication({ throw new Error('Keep the description within 255 characters.'); } if ( - !redirect_uri.length || + (!redirect_uri.length && !redirectsOptional) || redirect_uri.length > 25 || redirect_uri.join('\n').length > 2048 ) { @@ -48,22 +55,22 @@ export function parseApplication({ throw new Error('Enter valid redirect URIs, one per line.'); } if ( - url.search || - url.hash || - !uri.toLowerCase().startsWith(`${url.protocol}//`) + DANGEROUS_REDIRECT_SCHEMES.has(url.protocol) || + (!dev && !uri.toLowerCase().startsWith(`${url.protocol}//`)) ) { - throw new Error( - 'Redirect URIs must use a URL scheme and cannot contain queries or fragments.', - ); + throw new Error('Enter valid redirect URIs, one per line.'); + } + if (url.search || url.hash) { + throw new Error('Redirect URIs cannot contain queries or fragments.'); } } - const nonLocal = dev ? nonLocalRedirectUris(redirects) : []; - if (nonLocal.length > 0) { + const blocked = enforceProductionRedirects + ? unsafeRedirectUris(redirects) + : []; + if (blocked.length > 0) { throw new Error( - `Development apps can only redirect to localhost. Remove ${nonLocal.join( - ', ', - )}.`, + `Production redirect URIs must use https:// on a domain you control. Change ${blocked.join(', ')}.`, ); } diff --git a/projects/developer/src/lib/features/apps/parseApplicationProfile.spec.ts b/projects/developer/src/lib/features/apps/parseApplicationProfile.spec.ts new file mode 100644 index 00000000..7a324025 --- /dev/null +++ b/projects/developer/src/lib/features/apps/parseApplicationProfile.spec.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import type { ApplicationProfileDraft } from './ApplicationProfileDraft.ts'; +import { parseApplicationProfile } from './parseApplicationProfile.ts'; + +const draft: ApplicationProfileDraft = { + summary: + ' TV media player for people who keep their own home libraries. It syncs watch history and progress with Trakt. ', + openSource: true, + productLinks: 'https://github.com/example/player, https://example.app', + privacyUrl: ' https://example.app/privacy ', + noticeLinks: 'https://github.com/example/player#readme', + expectedMau: '2000', + signIn: 'pkce', + writesUserData: true, + usesOtherData: false, + otherDataSources: 'ignored', + syncsElsewhere: true, + otherSyncServices: ' Another tracker ', +}; + +describe('parseApplicationProfile', () => { + it('turns a complete draft into the API payload', () => { + expect(parseApplicationProfile(draft)).toEqual({ + summary: + 'TV media player for people who keep their own home libraries. It syncs watch history and progress with Trakt.', + open_source: true, + product_links: [ + 'https://github.com/example/player', + 'https://example.app', + ], + privacy_url: 'https://example.app/privacy', + notice_links: ['https://github.com/example/player#readme'], + expected_mau: 2000, + sign_in: 'pkce', + writes_user_data: true, + other_data_sources: null, + other_sync_services: 'Another tracker', + }); + }); + + it('never reports writes for an app that uses public data only', () => { + expect( + parseApplicationProfile({ ...draft, signIn: 'none' }).writes_user_data, + ).toBe(false); + }); + + it.each([ + [{ summary: ' ' }, 'at least 100 characters'], + [{ summary: 'a'.repeat(99) }, 'at least 100 characters'], + [{ summary: 'a'.repeat(501) }, 'within 500 characters'], + [{ productLinks: ' , ' }, 'at least one link to your app'], + [{ productLinks: 'ftp://example.app' }, "isn't a valid"], + [ + { + productLinks: Array(11) + .fill('https://x.example/') + .map((url, index) => `${url}${index}`) + .join(','), + }, + 'up to 10', + ], + [{ privacyUrl: 'example.app/privacy' }, 'privacy policy'], + [{ noticeLinks: '' }, 'at least one notice link'], + [{ expectedMau: '2k' }, 'as a number'], + [{ expectedMau: '-5' }, 'as a number'], + [{ usesOtherData: true, otherDataSources: ' ' }, 'other data sources'], + [{ otherSyncServices: 'x'.repeat(256) }, 'within 255 characters'], + ] as const)('rejects %o', (change, message) => { + expect(() => parseApplicationProfile({ ...draft, ...change })).toThrow( + message, + ); + }); + + it('accepts descriptions of 100 to 500 characters and zero expected users', () => { + const parsed = parseApplicationProfile({ + ...draft, + summary: 'a'.repeat(500), + expectedMau: '0', + }); + + expect(parsed.summary).toHaveLength(500); + expect( + parseApplicationProfile({ ...draft, summary: 'a'.repeat(100) }).summary, + ).toHaveLength(100); + expect(parsed.expected_mau).toBe(0); + }); +}); diff --git a/projects/developer/src/lib/features/apps/parseApplicationProfile.ts b/projects/developer/src/lib/features/apps/parseApplicationProfile.ts new file mode 100644 index 00000000..cb427fde --- /dev/null +++ b/projects/developer/src/lib/features/apps/parseApplicationProfile.ts @@ -0,0 +1,31 @@ +import type { ApplicationProfileDraft } from './ApplicationProfileDraft.ts'; +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; +import { applicationProfileIssues } from './applicationProfileIssues.ts'; +import { splitLinks } from './splitLinks.ts'; + +function otherValue(enabled: boolean, text: string): string | null { + return enabled ? text.trim() : null; +} + +export function parseApplicationProfile( + draft: ApplicationProfileDraft, +): ApplicationProfileInput { + const issue = applicationProfileIssues(draft).at(0); + if (issue) throw new Error(issue.message); + + return { + summary: draft.summary.trim(), + open_source: draft.openSource, + product_links: splitLinks(draft.productLinks), + privacy_url: draft.privacyUrl.trim(), + notice_links: splitLinks(draft.noticeLinks), + expected_mau: Number(draft.expectedMau.trim()), + sign_in: draft.signIn, + writes_user_data: draft.signIn === 'none' ? false : draft.writesUserData, + other_data_sources: otherValue(draft.usesOtherData, draft.otherDataSources), + other_sync_services: otherValue( + draft.syncsElsewhere, + draft.otherSyncServices, + ), + }; +} diff --git a/projects/developer/src/lib/features/apps/parseProductionReview.spec.ts b/projects/developer/src/lib/features/apps/parseProductionReview.spec.ts new file mode 100644 index 00000000..387293db --- /dev/null +++ b/projects/developer/src/lib/features/apps/parseProductionReview.spec.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest'; +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; +import { parseProductionReview } from './parseProductionReview.ts'; + +const profile: ApplicationProfileInput = { + summary: + 'TV media player for people who keep their own home libraries. It syncs watch history and progress with Trakt.', + open_source: false, + product_links: ['https://example.app'], + privacy_url: 'https://example.app/privacy', + notice_links: ['https://example.app/about'], + expected_mau: 2000, + sign_in: 'pkce', + writes_user_data: true, + other_data_sources: null, + other_sync_services: null, +}; + +const base = { + profile, + redirectsNeeded: true, + redirects: ' https://example.app/callback \n\n', + needsSecret: false, + secretReason: '', + confirmPolicy: true, + confirmSecret: false, + hasClientSecret: false, +}; + +describe('parseProductionReview', () => { + it('sends trimmed https redirects when a PKCE app asks for Production', () => { + expect(parseProductionReview(base)).toEqual({ + profile, + redirect_uri: ['https://example.app/callback'], + client_secret: null, + confirm_api_use_policy: true, + }); + }); + + it('asks for no redirects on device code apps or later reviews', () => { + expect( + parseProductionReview({ + ...base, + profile: { ...profile, sign_in: 'device_code' }, + redirects: 'http://localhost:5173', + }).redirect_uri, + ).toEqual([]); + expect( + parseProductionReview({ ...base, redirectsNeeded: false }).redirect_uri, + ).toEqual([]); + }); + + it.each([ + ['', 'at least one production redirect URI'], + ['http://example.app/callback', 'Change http://example.app/callback'], + ['https://localhost:5173/callback', 'Change https://localhost'], + ['myapp://callback', 'Change myapp://callback'], + ])('refuses the production redirect %j', (redirects, message) => { + expect(() => parseProductionReview({ ...base, redirects })).toThrow( + message, + ); + }); + + it('needs a reason and the secret confirmation to ask for a Client Secret', () => { + expect(() => + parseProductionReview({ + ...base, + needsSecret: true, + confirmSecret: true, + }), + ).toThrow('why your server needs'); + expect(() => + parseProductionReview({ + ...base, + needsSecret: true, + secretReason: 'Our server refreshes tokens.', + }), + ).toThrow('never ships'); + expect( + parseProductionReview({ + ...base, + needsSecret: true, + secretReason: ' Our server refreshes tokens. ', + confirmSecret: true, + }), + ).toMatchObject({ + client_secret: { reason: 'Our server refreshes tokens.' }, + confirm_secret_not_shipped: true, + }); + }); + + it('never asks again for a secret the app already has', () => { + expect( + parseProductionReview({ + ...base, + needsSecret: true, + hasClientSecret: true, + confirmSecret: true, + }), + ).toMatchObject({ client_secret: null, confirm_secret_not_shipped: true }); + }); + + it('never asks for a Client Secret for an app that only reads public data', () => { + expect( + parseProductionReview({ + ...base, + profile: { ...profile, sign_in: 'none' }, + needsSecret: true, + secretReason: 'Server refresh.', + confirmSecret: true, + }).client_secret, + ).toBeNull(); + }); + + it('requires the API Use Policy confirmation', () => { + expect(() => + parseProductionReview({ ...base, confirmPolicy: false }), + ).toThrow('API Use Policy'); + }); +}); diff --git a/projects/developer/src/lib/features/apps/parseProductionReview.ts b/projects/developer/src/lib/features/apps/parseProductionReview.ts new file mode 100644 index 00000000..0c0fc7c3 --- /dev/null +++ b/projects/developer/src/lib/features/apps/parseProductionReview.ts @@ -0,0 +1,32 @@ +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; +import { asksProductionRedirects } from './asksProductionRedirects.ts'; +import { productionReviewIssues } from './productionReviewIssues.ts'; +import type { ProductionReviewAnswers } from './ProductionReviewAnswers.ts'; +import type { ProductionReviewInput } from './ProductionReviewInput.ts'; +import { requestsClientSecret } from './requestsClientSecret.ts'; +import { splitLines } from './splitLines.ts'; + +export function parseProductionReview({ + profile, + ...answers +}: ProductionReviewAnswers & { + profile: ApplicationProfileInput; +}): ProductionReviewInput { + const signIn = profile.sign_in; + const issue = productionReviewIssues({ ...answers, signIn }).at(0); + if (issue) throw new Error(issue.message); + + const asksRedirects = asksProductionRedirects({ ...answers, signIn }); + const requestsSecret = requestsClientSecret({ ...answers, signIn }); + const coversSecret = requestsSecret || answers.hasClientSecret; + + return { + profile, + redirect_uri: asksRedirects ? splitLines(answers.redirects) : [], + client_secret: requestsSecret + ? { reason: answers.secretReason.trim() } + : null, + confirm_api_use_policy: true, + ...(coversSecret && { confirm_secret_not_shipped: true as const }), + }; +} diff --git a/projects/developer/src/lib/features/apps/productionCardBadge.spec.ts b/projects/developer/src/lib/features/apps/productionCardBadge.spec.ts new file mode 100644 index 00000000..f7d70b5c --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionCardBadge.spec.ts @@ -0,0 +1,28 @@ +import { expect, it } from 'vitest'; +import { productionCardBadge } from './productionCardBadge.ts'; + +const base = { + id: 1, + kind: 'production' as const, + submitted_at: '2026-11-03T09:00:00.000Z', + client_secret_requested: false, +}; + +it.each([ + ['pending', 'Review requested'], + ['changes_requested', 'Changes requested'], + ['declined', 'Review declined'], +] as const)('flags %s reviews on the app card', (status, label) => { + expect(productionCardBadge({ ...base, status })).toEqual({ label, status }); +}); + +it.each(['granted', 'granted_instantly'] as const)( + 'leaves %s apps without a badge', + (status) => { + expect(productionCardBadge({ ...base, status })).toBeNull(); + }, +); + +it('has no badge for apps that never asked', () => { + expect(productionCardBadge(null)).toBeNull(); +}); diff --git a/projects/developer/src/lib/features/apps/productionCardBadge.ts b/projects/developer/src/lib/features/apps/productionCardBadge.ts new file mode 100644 index 00000000..cb88077b --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionCardBadge.ts @@ -0,0 +1,18 @@ +import type { ProductionReview } from './ProductionReview.ts'; +import type { ProductionStatus } from './ProductionStatus.ts'; +import { productionStatusCopy } from './productionStatusCopy.ts'; + +const SHOWN_ON_CARD: ReadonlySet = new Set([ + 'pending', + 'changes_requested', + 'declined', +]); + +export function productionCardBadge( + review: ProductionReview | null | undefined, +): { label: string; status: ProductionStatus } | null { + if (!review || !SHOWN_ON_CARD.has(review.status)) return null; + + const copy = productionStatusCopy(review); + return copy ? { label: copy.badge, status: review.status } : null; +} diff --git a/projects/developer/src/lib/features/apps/productionNeedsRedirects.spec.ts b/projects/developer/src/lib/features/apps/productionNeedsRedirects.spec.ts new file mode 100644 index 00000000..19f63f29 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionNeedsRedirects.spec.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest'; +import { productionNeedsRedirects } from './productionNeedsRedirects.ts'; + +const callback = 'https://example.app/callback'; +const linked = { + id: 2, + name: 'Production app', + dev: false, + read_only: false, + has_client_secret: false, +}; +const dev = { dev: true, redirect_uri: 'http://localhost/callback' }; +const production = { dev: false, redirect_uri: callback }; + +describe('productionNeedsRedirects', () => { + it('asks for callbacks when the Production app does not exist yet', () => { + expect(productionNeedsRedirects(dev, [])).toBe(true); + }); + + it('asks for callbacks on both sides of a pair when Production has none', () => { + expect( + productionNeedsRedirects({ ...production, redirect_uri: '' }, []), + ).toBe(true); + expect( + productionNeedsRedirects({ ...dev, linked_application: linked }, [ + { id: linked.id, redirect_uri: '' }, + ]), + ).toBe(true); + }); + + it('asks for callbacks when the linked Production app is not listed', () => { + expect( + productionNeedsRedirects({ ...dev, linked_application: linked }, []), + ).toBe(true); + }); + + it('keeps existing Production callbacks', () => { + expect(productionNeedsRedirects(production, [])).toBe(false); + expect( + productionNeedsRedirects({ ...dev, linked_application: linked }, [ + { id: linked.id, redirect_uri: callback }, + ]), + ).toBe(false); + }); + + it('still asks for callbacks when upgrading a read-only app', () => { + expect( + productionNeedsRedirects( + { ...production, app_type: 'production_read_only' }, + [], + ), + ).toBe(true); + expect( + productionNeedsRedirects( + { ...dev, linked_application: { ...linked, read_only: true } }, + [], + ), + ).toBe(true); + }); +}); diff --git a/projects/developer/src/lib/features/apps/productionNeedsRedirects.ts b/projects/developer/src/lib/features/apps/productionNeedsRedirects.ts new file mode 100644 index 00000000..a83ae4b1 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionNeedsRedirects.ts @@ -0,0 +1,21 @@ +import type { Application } from './Application.ts'; + +export function productionNeedsRedirects( + app: Pick< + Application, + 'dev' | 'redirect_uri' | 'app_type' | 'linked_application' + >, + apps: ReadonlyArray>, +): boolean { + if (!app.dev) { + return ( + app.app_type === 'production_read_only' || app.redirect_uri.trim() === '' + ); + } + + const linked = app.linked_application; + if (!linked || linked.read_only) return true; + + const production = apps.find(({ id }) => id === linked.id); + return production === undefined || production.redirect_uri.trim() === ''; +} diff --git a/projects/developer/src/lib/features/apps/productionReviewDetailSchema.ts b/projects/developer/src/lib/features/apps/productionReviewDetailSchema.ts new file mode 100644 index 00000000..fb13b8d1 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionReviewDetailSchema.ts @@ -0,0 +1,12 @@ +import { z } from 'zod'; +import { applicationProfileSchema } from './applicationProfileSchema.ts'; +import { productionReviewSchema } from './productionReviewSchema.ts'; + +export const productionReviewDetailSchema = productionReviewSchema.extend({ + profile: applicationProfileSchema.omit({ + updated_at: true, + updated_by: true, + }), + redirect_uri: z.array(z.string()), + client_secret_reason: z.string().nullable(), +}); diff --git a/projects/developer/src/lib/features/apps/productionReviewIssues.spec.ts b/projects/developer/src/lib/features/apps/productionReviewIssues.spec.ts new file mode 100644 index 00000000..0005c95c --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionReviewIssues.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { productionReviewIssues } from './productionReviewIssues.ts'; + +const answers = { + signIn: 'pkce' as const, + redirectsNeeded: true, + redirects: 'https://example.app/callback', + needsSecret: false, + secretReason: '', + confirmPolicy: true, + confirmSecret: false, + hasClientSecret: false, +}; + +describe('productionReviewIssues', () => { + it('finds nothing in complete answers', () => { + expect(productionReviewIssues(answers)).toEqual([]); + }); + + it('lists every field with a problem, in form order', () => { + const issues = productionReviewIssues({ + ...answers, + redirects: 'myapp://callback', + needsSecret: true, + confirmPolicy: false, + }); + + expect(issues.map((issue) => issue.field)).toEqual([ + 'redirects', + 'secretReason', + 'confirmPolicy', + 'confirmSecret', + ]); + }); + + it.each([ + ['https://example.app/callback?next=home', /queries or fragments/], + ['https://example.app/callback#home', /queries or fragments/], + ['https://example.app/my callback', /whitespace/], + [ + Array.from({ length: 26 }, (_, i) => `https://example.app/${i}`).join( + '\n', + ), + /1-25/, + ], + [`https://example.app/${'a'.repeat(2048)}`, /2,048/], + ])('flags invalid callback lists before submission', (redirects, message) => { + expect(productionReviewIssues({ ...answers, redirects })).toEqual([ + { field: 'redirects', message: expect.stringMatching(message) }, + ]); + }); + + it('skips redirects and the Client Secret for apps that only read public data', () => { + expect( + productionReviewIssues({ + ...answers, + signIn: 'none', + redirects: '', + needsSecret: true, + }), + ).toEqual([]); + }); +}); diff --git a/projects/developer/src/lib/features/apps/productionReviewIssues.ts b/projects/developer/src/lib/features/apps/productionReviewIssues.ts new file mode 100644 index 00000000..a763d8fe --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionReviewIssues.ts @@ -0,0 +1,82 @@ +import { asksProductionRedirects } from './asksProductionRedirects.ts'; +import type { ProductionFormField } from './ProductionFormField.ts'; +import type { ProductionFormIssue } from './ProductionFormIssue.ts'; +import type { ProductionReviewAnswers } from './ProductionReviewAnswers.ts'; +import type { ProductionSignIn } from './ProductionSignIn.ts'; +import { requestsClientSecret } from './requestsClientSecret.ts'; +import { splitLines } from './splitLines.ts'; +import { unsafeRedirectUris } from './unsafeRedirectUris.ts'; + +const SECRET_REASON_LIMIT = 500; + +function redirectsIssue(asks: boolean, redirects: string): string | null { + if (!asks) return null; + const lines = splitLines(redirects); + if (lines.length === 0) { + return 'Add at least one production redirect URI.'; + } + + if (lines.some((uri) => /\s/.test(uri))) { + return 'Production redirect URIs cannot contain whitespace.'; + } + const blocked = unsafeRedirectUris(redirects); + if (blocked.length > 0) { + return `Production redirect URIs must use https:// on a domain you control. Change ${blocked.join(', ')}.`; + } + if ( + lines.some((uri) => { + const url = new URL(uri); + return url.search || url.hash; + }) + ) { + return 'Production redirect URIs cannot contain queries or fragments.'; + } + if (lines.length > 25 || lines.join('\n').length > 2048) { + return 'Enter 1-25 redirect URIs, within 2,048 characters in total.'; + } + + return null; +} + +function secretReasonIssue(requests: boolean, text: string): string | null { + if (!requests) return null; + + const reason = text.trim(); + if (!reason) return 'Tell us why your server needs a Client Secret.'; + if (reason.length > SECRET_REASON_LIMIT) { + return `Keep the Client Secret reason within ${SECRET_REASON_LIMIT} characters.`; + } + + return null; +} + +/** Every problem in the review part of the form, at most one per field, in form order. */ +export function productionReviewIssues( + answers: ProductionReviewAnswers & { signIn: ProductionSignIn }, +): ReadonlyArray { + const requests = requestsClientSecret(answers); + const coversSecret = requests || answers.hasClientSecret; + const checks: ReadonlyArray<[ProductionFormField, string | null]> = [ + [ + 'redirects', + redirectsIssue(asksProductionRedirects(answers), answers.redirects), + ], + ['secretReason', secretReasonIssue(requests, answers.secretReason)], + [ + 'confirmPolicy', + answers.confirmPolicy + ? null + : 'Confirm that your app follows the API Use Policy.', + ], + [ + 'confirmSecret', + coversSecret && !answers.confirmSecret + ? 'Confirm that your Client Secret never ships in your app or website.' + : null, + ], + ]; + + return checks.flatMap(([field, message]) => + message ? [{ field, message }] : [], + ); +} diff --git a/projects/developer/src/lib/features/apps/productionReviewSchema.ts b/projects/developer/src/lib/features/apps/productionReviewSchema.ts new file mode 100644 index 00000000..46683bf0 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionReviewSchema.ts @@ -0,0 +1,13 @@ +import { z } from 'zod'; +import { productionStatusSchema } from './productionStatusSchema.ts'; + +export const productionReviewSchema = z.object({ + id: z.number(), + kind: z.enum(['production', 'update', 'client_secret']), + status: productionStatusSchema, + submitted_at: z.string(), + reviewed_at: z.string().nullish(), + review_note: z.string().nullish(), + client_secret_requested: z.boolean(), + granted_access: z.enum(['read_only', 'full']).nullish(), +}); diff --git a/projects/developer/src/lib/features/apps/productionSignInSchema.ts b/projects/developer/src/lib/features/apps/productionSignInSchema.ts new file mode 100644 index 00000000..52ce1913 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionSignInSchema.ts @@ -0,0 +1,3 @@ +import { z } from 'zod'; + +export const productionSignInSchema = z.enum(['none', 'pkce', 'device_code']); diff --git a/projects/developer/src/lib/features/apps/productionStatusCopy.spec.ts b/projects/developer/src/lib/features/apps/productionStatusCopy.spec.ts new file mode 100644 index 00000000..05c0314c --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionStatusCopy.spec.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest'; +import { formatDate } from './formatDate.ts'; +import type { ProductionReview } from './ProductionReview.ts'; +import { productionStatusCopy } from './productionStatusCopy.ts'; + +const submitted_at = '2026-11-03T09:00:00.000Z'; +const reviewed_at = '2026-11-05T09:00:00.000Z'; + +function review(change: Partial): ProductionReview { + return { + id: 1, + kind: 'production', + status: 'pending', + submitted_at, + client_secret_requested: false, + ...change, + }; +} + +describe('productionStatusCopy', () => { + it('returns nothing when the app never asked for a review', () => { + expect(productionStatusCopy(null)).toBeNull(); + expect(productionStatusCopy(undefined)).toBeNull(); + }); + + it('dates a pending review by when it was sent and says nothing changes yet', () => { + expect(productionStatusCopy(review({}))).toMatchObject({ + title: `Review requested · ${formatDate(submitted_at)}`, + detail: expect.stringMatching(/Nothing changes until then/), + tone: 'info', + }); + }); + + it('says the Production app is ready while a Client Secret request waits', () => { + expect( + productionStatusCopy(review({ kind: 'client_secret' })), + ).toMatchObject({ + badge: 'Client Secret requested', + detail: expect.stringMatching( + /Production app is ready.*Client Secret request is waiting for a review/, + ), + tone: 'info', + }); + }); + + it.each(['granted', 'granted_instantly'] as const)( + 'says Production access was granted, never approved, for a first %s review', + (status) => { + const copy = productionStatusCopy(review({ status, reviewed_at })); + + expect(copy?.title).toMatch(/^Production access granted/); + expect(copy?.detail).toMatch(/Production app is ready/); + expect(copy?.detail).toMatch(/doesn't mean Trakt endorses/); + expect(JSON.stringify(copy)).not.toMatch(/approv/i); + }, + ); + + it('calls a granted later review a change, not new access', () => { + expect( + productionStatusCopy( + review({ kind: 'update', status: 'granted', reviewed_at }), + )?.title, + ).toBe(`Changes granted · ${formatDate(reviewed_at)}`); + }); + + it('says when access was granted read-only and how to change it', () => { + const copy = productionStatusCopy( + review({ status: 'granted', reviewed_at, granted_access: 'read_only' }), + ); + + expect(copy?.title).toBe( + `Read-only Production access granted · ${formatDate(reviewed_at)}`, + ); + expect(copy?.detail).toMatch(/Nobody can sign in to it/); + expect(copy?.detail).toMatch(/doesn't mean Trakt endorses/); + }); + + it('describes a historical read-only grant using the actual Production access', () => { + const copy = productionStatusCopy( + review({ + kind: 'update', + status: 'granted', + granted_access: 'read_only', + }), + true, + ); + + expect(copy?.title).toMatch(/^Changes granted/); + expect(copy?.detail).not.toMatch(/Nobody can sign in/); + }); + + it('tells a declined developer that nothing changed and they can ask again', () => { + expect( + productionStatusCopy(review({ status: 'declined', reviewed_at })), + ).toMatchObject({ + title: `Review declined · ${formatDate(reviewed_at)}`, + detail: expect.stringMatching(/request another review/), + tone: 'danger', + }); + }); +}); diff --git a/projects/developer/src/lib/features/apps/productionStatusCopy.ts b/projects/developer/src/lib/features/apps/productionStatusCopy.ts new file mode 100644 index 00000000..0e187035 --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionStatusCopy.ts @@ -0,0 +1,74 @@ +import { formatDate } from './formatDate.ts'; +import type { ProductionReview } from './ProductionReview.ts'; + +export type ProductionStatusCopy = { + badge: string; + title: string; + detail: string; + tone: 'info' | 'warning' | 'success' | 'danger'; +}; + +const NOT_AN_ENDORSEMENT = + "This doesn't mean Trakt endorses or certifies your app."; + +export function productionStatusCopy( + review: ProductionReview | null | undefined, + fullProduction = false, +): ProductionStatusCopy | null { + if (!review) return null; + + const decided = formatDate(review.reviewed_at ?? review.submitted_at); + const firstTime = review.kind === 'production'; + switch (review.status) { + case 'pending': + if (review.kind === 'client_secret') + return { + badge: 'Client Secret requested', + title: `Client Secret requested · ${formatDate(review.submitted_at)}`, + detail: + "Your Production app is ready. Your Client Secret request is waiting for a review. We'll email you when it's reviewed.", + tone: 'info', + }; + return { + badge: 'Review requested', + title: `Review requested · ${formatDate(review.submitted_at)}`, + detail: + "We'll email you when it's reviewed. Nothing changes until then.", + tone: 'info', + }; + case 'changes_requested': + return { + badge: 'Changes requested', + title: `Changes requested · ${decided}`, + detail: 'Update your request, then resubmit.', + tone: 'warning', + }; + case 'granted': + case 'granted_instantly': { + const readOnly = !fullProduction && review.granted_access === 'read_only'; + const label = readOnly + ? 'Read-only Production access granted' + : firstTime + ? 'Production access granted' + : 'Changes granted'; + const lead = readOnly + ? 'Your app can read public data. Nobody can sign in to it; to change that, request a review.' + : firstTime + ? 'Your Production app is ready.' + : ''; + return { + badge: label, + title: `${label} · ${decided}`, + detail: `${lead} ${NOT_AN_ENDORSEMENT}`.trim(), + tone: 'success', + }; + } + case 'declined': + return { + badge: 'Review declined', + title: `Review declined · ${decided}`, + detail: 'Nothing changed. You can request another review.', + tone: 'danger', + }; + } +} diff --git a/projects/developer/src/lib/features/apps/productionStatusSchema.ts b/projects/developer/src/lib/features/apps/productionStatusSchema.ts new file mode 100644 index 00000000..cb1e6e0e --- /dev/null +++ b/projects/developer/src/lib/features/apps/productionStatusSchema.ts @@ -0,0 +1,9 @@ +import { z } from 'zod'; + +export const productionStatusSchema = z.enum([ + 'pending', + 'changes_requested', + 'granted', + 'granted_instantly', + 'declined', +]); diff --git a/projects/developer/src/lib/features/apps/profileDraftFrom.spec.ts b/projects/developer/src/lib/features/apps/profileDraftFrom.spec.ts new file mode 100644 index 00000000..ab333bd0 --- /dev/null +++ b/projects/developer/src/lib/features/apps/profileDraftFrom.spec.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest'; +import type { ApplicationProfile } from './ApplicationProfile.ts'; +import { parseApplicationProfile } from './parseApplicationProfile.ts'; +import { profileDraftFrom } from './profileDraftFrom.ts'; + +const profile: ApplicationProfile = { + summary: + 'TV media player for people who keep their own home libraries. It syncs watch history and progress with Trakt.', + open_source: true, + product_links: ['https://github.com/example/player', 'https://example.app'], + privacy_url: 'https://example.app/privacy', + notice_links: ['https://example.app/about'], + expected_mau: 2000, + sign_in: 'device_code', + writes_user_data: true, + other_data_sources: 'Another movie and show database', + other_sync_services: null, + updated_at: '2026-11-03T09:00:00.000Z', + updated_by: { username: 'dev_example' }, +}; + +describe('profileDraftFrom', () => { + it('starts an empty draft for apps without app information', () => { + expect(profileDraftFrom(null)).toMatchObject({ + summary: '', + expectedMau: '', + signIn: 'pkce', + usesOtherData: false, + syncsElsewhere: false, + }); + }); + + it('round-trips saved app information through the form', () => { + const { updated_at: _at, updated_by: _by, ...input } = profile; + + expect(parseApplicationProfile(profileDraftFrom(profile))).toEqual(input); + }); +}); diff --git a/projects/developer/src/lib/features/apps/profileDraftFrom.ts b/projects/developer/src/lib/features/apps/profileDraftFrom.ts new file mode 100644 index 00000000..c9c3d7ca --- /dev/null +++ b/projects/developer/src/lib/features/apps/profileDraftFrom.ts @@ -0,0 +1,21 @@ +import type { ApplicationProfileInput } from './ApplicationProfileInput.ts'; +import type { ApplicationProfileDraft } from './ApplicationProfileDraft.ts'; + +export function profileDraftFrom( + profile: ApplicationProfileInput | null, +): ApplicationProfileDraft { + return { + summary: profile?.summary ?? '', + openSource: profile?.open_source ?? false, + productLinks: profile?.product_links.join(', ') ?? '', + privacyUrl: profile?.privacy_url ?? '', + noticeLinks: profile?.notice_links.join(', ') ?? '', + expectedMau: profile ? String(profile.expected_mau) : '', + signIn: profile?.sign_in ?? 'pkce', + writesUserData: profile?.writes_user_data ?? false, + usesOtherData: !!profile?.other_data_sources, + otherDataSources: profile?.other_data_sources ?? '', + syncsElsewhere: !!profile?.other_sync_services, + otherSyncServices: profile?.other_sync_services ?? '', + }; +} diff --git a/projects/developer/src/lib/features/apps/profileUsageLabel.spec.ts b/projects/developer/src/lib/features/apps/profileUsageLabel.spec.ts new file mode 100644 index 00000000..e00a222a --- /dev/null +++ b/projects/developer/src/lib/features/apps/profileUsageLabel.spec.ts @@ -0,0 +1,10 @@ +import { expect, it } from 'vitest'; +import { profileUsageLabel } from './profileUsageLabel.ts'; + +it.each([ + ['none', false, 'Public data only'], + ['pkce', true, 'Signs users in (PKCE) · reads and writes'], + ['device_code', false, 'Signs users in (device code) · read only'], +] as const)('describes %s apps that write: %s', (sign_in, writes, label) => { + expect(profileUsageLabel({ sign_in, writes_user_data: writes })).toBe(label); +}); diff --git a/projects/developer/src/lib/features/apps/profileUsageLabel.ts b/projects/developer/src/lib/features/apps/profileUsageLabel.ts new file mode 100644 index 00000000..96ab4802 --- /dev/null +++ b/projects/developer/src/lib/features/apps/profileUsageLabel.ts @@ -0,0 +1,16 @@ +import type { ApplicationProfile } from './ApplicationProfile.ts'; + +const SIGN_IN_LABELS = { + none: 'Public data only', + pkce: 'Signs users in (PKCE)', + device_code: 'Signs users in (device code)', +} as const; + +export function profileUsageLabel( + profile: Pick, +): string { + const signIn = SIGN_IN_LABELS[profile.sign_in]; + if (profile.sign_in === 'none') return signIn; + + return `${signIn} · ${profile.writes_user_data ? 'reads and writes' : 'read only'}`; +} diff --git a/projects/developer/src/lib/features/apps/requestProductionReview.ts b/projects/developer/src/lib/features/apps/requestProductionReview.ts new file mode 100644 index 00000000..bc99f2e0 --- /dev/null +++ b/projects/developer/src/lib/features/apps/requestProductionReview.ts @@ -0,0 +1,25 @@ +import { accountRequest } from '$lib/api/accountRequest.ts'; +import type { ProductionReview } from './ProductionReview.ts'; +import type { ProductionReviewInput } from './ProductionReviewInput.ts'; +import { productionReviewSchema } from './productionReviewSchema.ts'; + +export async function requestProductionReview({ + slot, + appId, + input, +}: { + slot: number; + appId: number; + input: ProductionReviewInput; +}): Promise { + const response = await accountRequest({ + slot, + path: `/v3/users/me/applications/${appId}/production-review`, + init: { method: 'POST', body: JSON.stringify(input) }, + }); + const parsed = productionReviewSchema.safeParse(await response.json()); + if (!parsed.success) { + throw new Error('Your request was sent but its status could not be read.'); + } + return parsed.data; +} diff --git a/projects/developer/src/lib/features/apps/requestsClientSecret.spec.ts b/projects/developer/src/lib/features/apps/requestsClientSecret.spec.ts new file mode 100644 index 00000000..a96920ca --- /dev/null +++ b/projects/developer/src/lib/features/apps/requestsClientSecret.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { requestsClientSecret } from './requestsClientSecret.ts'; + +describe('requestsClientSecret', () => { + it('requests a secret only for sign-in apps that do not have one', () => { + const answers = { needsSecret: true, hasClientSecret: false }; + + expect(requestsClientSecret({ ...answers, signIn: 'pkce' })).toBe(true); + expect(requestsClientSecret({ ...answers, signIn: 'none' })).toBe(false); + expect( + requestsClientSecret({ + ...answers, + hasClientSecret: true, + signIn: 'pkce', + }), + ).toBe(false); + }); +}); diff --git a/projects/developer/src/lib/features/apps/requestsClientSecret.ts b/projects/developer/src/lib/features/apps/requestsClientSecret.ts new file mode 100644 index 00000000..c3274b13 --- /dev/null +++ b/projects/developer/src/lib/features/apps/requestsClientSecret.ts @@ -0,0 +1,13 @@ +import type { ProductionSignIn } from './ProductionSignIn.ts'; + +export function requestsClientSecret({ + needsSecret, + hasClientSecret, + signIn, +}: { + needsSecret: boolean; + hasClientSecret: boolean; + signIn: ProductionSignIn; +}): boolean { + return needsSecret && !hasClientSecret && signIn !== 'none'; +} diff --git a/projects/developer/src/lib/features/apps/splitLines.spec.ts b/projects/developer/src/lib/features/apps/splitLines.spec.ts new file mode 100644 index 00000000..543745ad --- /dev/null +++ b/projects/developer/src/lib/features/apps/splitLines.spec.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest'; +import { splitLines } from './splitLines.ts'; + +describe('splitLines', () => { + it('trims each line and drops blank ones', () => { + expect(splitLines(' https://a.example \n\n https://b.example')).toEqual([ + 'https://a.example', + 'https://b.example', + ]); + }); +}); diff --git a/projects/developer/src/lib/features/apps/splitLines.ts b/projects/developer/src/lib/features/apps/splitLines.ts new file mode 100644 index 00000000..900ecaae --- /dev/null +++ b/projects/developer/src/lib/features/apps/splitLines.ts @@ -0,0 +1,6 @@ +export function splitLines(text: string): string[] { + return text + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); +} diff --git a/projects/developer/src/lib/features/apps/splitLinks.spec.ts b/projects/developer/src/lib/features/apps/splitLinks.spec.ts new file mode 100644 index 00000000..99c0ea4c --- /dev/null +++ b/projects/developer/src/lib/features/apps/splitLinks.spec.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { splitLinks } from './splitLinks.ts'; + +describe('splitLinks', () => { + it('splits on commas and new lines and trims each link', () => { + expect( + splitLinks(' https://a.example , https://b.example\nhttps://c.example '), + ).toEqual(['https://a.example', 'https://b.example', 'https://c.example']); + }); + + it('drops blanks and duplicates while keeping the first order', () => { + expect( + splitLinks('https://a.example,, ,https://b.example,https://a.example'), + ).toEqual(['https://a.example', 'https://b.example']); + }); + + it('returns nothing for an empty field', () => { + expect(splitLinks(' \n , ')).toEqual([]); + }); +}); diff --git a/projects/developer/src/lib/features/apps/splitLinks.ts b/projects/developer/src/lib/features/apps/splitLinks.ts new file mode 100644 index 00000000..f8f57249 --- /dev/null +++ b/projects/developer/src/lib/features/apps/splitLinks.ts @@ -0,0 +1,8 @@ +export function splitLinks(text: string): string[] { + const links = text + .split(/[,\n]/) + .map((link) => link.trim()) + .filter(Boolean); + + return [...new Set(links)]; +} diff --git a/projects/developer/src/lib/features/apps/summaryCountLabel.spec.ts b/projects/developer/src/lib/features/apps/summaryCountLabel.spec.ts new file mode 100644 index 00000000..c3f7836d --- /dev/null +++ b/projects/developer/src/lib/features/apps/summaryCountLabel.spec.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { summaryCountLabel } from './summaryCountLabel.ts'; + +describe('summaryCountLabel', () => { + it('counts down to the minimum, ignoring surrounding spaces', () => { + expect(summaryCountLabel(' ')).toBe('100 more characters needed.'); + expect(summaryCountLabel(` ${'a'.repeat(99)} `)).toBe( + '1 more character needed.', + ); + }); + + it('shows the count against the limit once the minimum is reached', () => { + expect(summaryCountLabel('a'.repeat(100))).toBe('100/500'); + }); +}); diff --git a/projects/developer/src/lib/features/apps/summaryCountLabel.ts b/projects/developer/src/lib/features/apps/summaryCountLabel.ts new file mode 100644 index 00000000..9d5b0a4b --- /dev/null +++ b/projects/developer/src/lib/features/apps/summaryCountLabel.ts @@ -0,0 +1,11 @@ +import { PROFILE_SUMMARY_LIMIT } from './PROFILE_SUMMARY_LIMIT.ts'; +import { PROFILE_SUMMARY_MINIMUM } from './PROFILE_SUMMARY_MINIMUM.ts'; + +export function summaryCountLabel(summary: string): string { + const length = summary.trim().length; + const missing = PROFILE_SUMMARY_MINIMUM - length; + if (missing === 1) return '1 more character needed.'; + if (missing > 1) return `${missing} more characters needed.`; + + return `${length}/${PROFILE_SUMMARY_LIMIT}`; +} diff --git a/projects/developer/src/lib/features/apps/unsafeRedirectUris.spec.ts b/projects/developer/src/lib/features/apps/unsafeRedirectUris.spec.ts index c67ad320..365e4eb3 100644 --- a/projects/developer/src/lib/features/apps/unsafeRedirectUris.spec.ts +++ b/projects/developer/src/lib/features/apps/unsafeRedirectUris.spec.ts @@ -10,6 +10,18 @@ describe('unsafeRedirectUris', () => { ).toEqual([]); }); + it('accepts domains whose first label looks like a private range', () => { + expect( + unsafeRedirectUris( + [ + 'https://10.example.com/cb', + 'https://127.example.org/cb', + 'https://192.168.example.net/cb', + ].join('\n'), + ), + ).toEqual([]); + }); + it('accepts public addresses next to the private ranges', () => { expect( unsafeRedirectUris( @@ -19,6 +31,7 @@ describe('unsafeRedirectUris', () => { 'https://11.0.0.1/callback', 'https://[2001:db8::1]/callback', 'https://localhost.example.com/callback', + 'https://[::ffff:11.0.0.1]/callback', ].join('\n'), ), ).toEqual([]); @@ -30,6 +43,12 @@ describe('unsafeRedirectUris', () => { 'urn:ietf:wg:oauth:2.0:oob', 'http://example.com/callback', 'https://localhost:3000/callback', + 'https://localhost./callback', + 'https://dev.localhost./callback', + 'https://printer.local./callback', + 'https://[::ffff:127.0.0.1]/callback', + 'https://[::ffff:192.168.1.10]/callback', + 'https://[::]/callback', 'http://localhost/callback', 'https://dev.localhost/callback', 'http://127.0.0.1:8080/callback', diff --git a/projects/developer/src/lib/features/apps/unsafeRedirectUris.ts b/projects/developer/src/lib/features/apps/unsafeRedirectUris.ts index 94a511cd..782cce97 100644 --- a/projects/developer/src/lib/features/apps/unsafeRedirectUris.ts +++ b/projects/developer/src/lib/features/apps/unsafeRedirectUris.ts @@ -1,18 +1,30 @@ const LOCAL_HOSTS: ReadonlySet = new Set(['localhost', '0.0.0.0']); +const IPV4_LITERAL = /^\d{1,3}(\.\d{1,3}){3}$/; + // Loopback, private (RFC 1918), and link-local IPv4 ranges. const PRIVATE_IPV4 = /^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/; -// Loopback, unique local (fc00::/7), and link-local (fe80::/10) IPv6. -const PRIVATE_IPV6 = /^\[(::1|f[cd][0-9a-f]{0,2}:|fe[89ab][0-9a-f]?:)/; +// Unspecified, loopback, unique local, and link-local IPv6. +const PRIVATE_IPV6 = /^\[(::1?\]|f[cd][0-9a-f]{0,2}:|fe[89ab][0-9a-f]?:)/; +const MAPPED_IPV4 = /^\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\]$/; + +function mappedIPv4(hostname: string): string { + const [, high, low] = MAPPED_IPV4.exec(hostname) ?? []; + if (!high || !low) return hostname; + + const first = Number.parseInt(high, 16); + const second = Number.parseInt(low, 16); + return [first >> 8, first & 255, second >> 8, second & 255].join('.'); +} function isPrivateHost(hostname: string): boolean { return ( LOCAL_HOSTS.has(hostname) || hostname.endsWith('.localhost') || hostname.endsWith('.local') || - PRIVATE_IPV4.test(hostname) || + (IPV4_LITERAL.test(hostname) && PRIVATE_IPV4.test(hostname)) || PRIVATE_IPV6.test(hostname) ); } @@ -29,7 +41,10 @@ function isSafe(uri: string): boolean { const url = parseUrl(uri); if (!url) return false; - return url.protocol === 'https:' && !isPrivateHost(url.hostname); + return ( + url.protocol === 'https:' && + !isPrivateHost(mappedIPv4(url.hostname.replace(/\.$/, ''))) + ); } /** diff --git a/projects/developer/src/lib/guides/create-an-app.md b/projects/developer/src/lib/guides/create-an-app.md index 6523296e..448d532e 100644 --- a/projects/developer/src/lib/guides/create-an-app.md +++ b/projects/developer/src/lib/guides/create-an-app.md @@ -23,3 +23,42 @@ By creating an app, you agree to the following terms: * Use only **documented API methods** and please don't scrape the website for information. * Please don't create additional API apps to avoid rate limits or other API restrictions we put in place. * Be a good API developer and remember the API is shared by a lot of apps. Make sure to effectively cache data and keep your API hits as low as you can. Optimized API usage helps everyone! + +## Going to production + +Every app starts as a **Development** app: you and up to 16 people you invite +can sign in, and any redirect URI works for testing, including localhost, +hosted test sites and custom app schemes. Apps for yourself or a few people +stay on Development. + +When your app is ready for everyone, open it from [My Apps](/apps) and choose +**Request Production access**. Premium developers see **Create Production app** +instead. Once access is granted, you get a separate **Production app** with its +own Client ID, and your Development app stays your sandbox. + +Have these ready before you start: + +* A short description of what your app does and who it's for (100 to 500 characters). +* At least one link to your app: repository, docs, store page, TestFlight or website. +* A link to your privacy policy. +* At least one link showing the notice "*Your app* uses Trakt but is not endorsed or certified by Trakt". A page, a README, or a screenshot or video you host is fine. +* How many monthly active users you expect, how your app uses Trakt, and which other services it relies on. +* For apps that sign users in with PKCE, your production redirect URIs: `https://` on a domain you control. Production apps don't accept localhost or custom app schemes; on mobile, use Universal Links or verified App Links. + +Apps that only read public data (trending, search, ratings) get **read-only** +Production access: they use their own Client ID and nobody can sign in to +them. To let users sign in later, request another review. + +Apps get no Client Secret by default. If your server exchanges and refreshes +tokens itself, ask for one in the same form and tell us why. + +Standard developers wait for a review, usually within a few business days. +Premium developers get their Production app right away, and later changes to +your app information apply right away too. A Client Secret is always reviewed: +the request waits until we grant it. Nothing changes until a review is +granted, and a declined review leaves your apps as they were. + +Granting Production access is not a review, endorsement or certification of +your app or how you use it. You stay responsible for following the +[API Use Policy](/docs/api-use-policy) and the law, and Trakt can remove access +at any time.