Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/assets/renderer.css

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/assets/renderer.js

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions hub/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ TEST_DATABASE_URL=postgresql://replica:replica@127.0.0.1:5432/postgres
# HUB_HOSTED_PUBLIC_SHARING_ENABLED=false
# Public share-link maximum: 1, 7, or 30 days. Defaults to 7.
# HUB_SHARE_LINK_MAX_DAYS=7
# Public share exports are off by default. When true, set the reader origin and export storage;
# Hub refuses a generated azurecontainerapps.io Hub hostname unless the shared-site override is
# true, which is for non-production installations only. See docs/share-links.md.
# HUB_PUBLIC_SHARE_ENABLED=false
# HUB_PUBLIC_SHARE_ORIGIN=https://share.example.net
# HUB_PUBLIC_SHARE_STORAGE_ACCOUNT=
# HUB_PUBLIC_SHARE_STORAGE_CONTAINER=public-share-exports
# HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=false
# Generate 32 random bytes and encode them as base64.
# HUB_AUTHENTICATION_ENCRYPTION_KEY=
# Use a random value containing at least 32 characters.
Expand Down
25 changes: 25 additions & 0 deletions hub/client/application/hub/product-contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,30 @@ export const productShareLinkSchema = z.object({
createdAt: timestamp,
expiresAt: timestamp,
revokedAt: timestamp.nullable(),
// Public share export links only.
url: httpUrl.optional(),
exportStatus: z
.enum(["pending", "ready", "updating", "failed", "revoking"])
.nullable()
.optional(),
hasPassword: z.boolean().optional(),
})

const productSharePasswordSchema = z
.string()
.refine(
(value) => [...value.normalize("NFC")].length >= 8,
"Use a password with at least 8 characters.",
)
.refine(
(value) => new TextEncoder().encode(value).byteLength <= 256,
"Use at most 256 bytes for the password.",
)

export const productSharePasswordInputSchema = z
.object({ password: productSharePasswordSchema.nullable() })
.strict()

export const productShareInputSchema = z
.object({
label: z
Expand All @@ -93,6 +115,7 @@ export const productShareInputSchema = z
),
expiration: z.enum(["one_day", "seven_days", "thirty_days"]),
buildNumber: identifier,
password: productSharePasswordSchema.optional(),
})
.strict()

Expand All @@ -102,6 +125,8 @@ export const productSharingResponseSchema = z.object({
enabled: z.boolean(),
canManage: z.boolean(),
expirationOptions: z.array(z.enum(["one_day", "seven_days", "thirty_days"])),
backend: z.enum(["legacy", "export"]).optional(),
selectedBuildShareable: z.boolean().optional(),
})

export const productSharingSettingsSchema = z.object({
Expand Down
97 changes: 97 additions & 0 deletions hub/client/application/hub/routes/expanded-flows.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,103 @@ describe("Hub Build share links", () => {
expect(screen.queryByRole("button", { name: /Account menu/ })).not.toBeInTheDocument()
})

it("creates public export links with a password and manages the password from the link", async () => {
const { path, repository, prototype, latest } = previewRecords({ canManageSharing: true })
const sharePath = `${path}/share-links`
const create = vi.fn()
const changePassword = vi.fn()
let link: ProductShareLink | undefined
const api = stubHubFetch(
...authenticatedWorkspace([repository]),
http.get(`/api${sharePath}`, () =>
Response.json({
resource: { repository, prototype, selectedBuild: { ...latest, previewUrl: null } },
links: link ? [link] : [],
enabled: true,
canManage: true,
expirationOptions: ["seven_days"],
backend: "export",
selectedBuildShareable: true,
}),
),
http.post(`/api${sharePath}`, async ({ request }) => {
const input = (await request.json()) as { label: string; buildNumber: number }
create(input)
link = {
...linkRecord(prototype, input.buildNumber, input.label),
url: "https://reader.example.net/s/12345678-1234-4234-8234-123456789abc",
exportStatus: "pending",
hasPassword: true,
}
return Response.json({ notice: "Share link created.", link }, { status: 201 })
}),
http.patch(`/api${sharePath}/:shareId`, async ({ request }) => {
changePassword(await request.json())
link = { ...link!, hasPassword: false }
return Response.json({ notice: "Password removed." })
}),
)
const router = await renderHubFlow(api, `${sharePath}?build=3`)

fireEvent.change(screen.getByRole("textbox", { name: "Label" }), {
target: { value: "Partner review" },
})
fireEvent.change(screen.getByLabelText("Password (optional)"), {
target: { value: "correct horse battery" },
})
await router.settle(() =>
fireEvent.click(screen.getByRole("button", { name: "Create share link" })),
)
expect(create).toHaveBeenCalledExactlyOnceWith({
label: "Partner review",
expiration: "seven_days",
buildNumber: 3,
password: "correct horse battery",
})
const pending = (await screen.findByRole("heading", { name: "Partner review" })).closest("li")!
expect(within(pending).getByRole("status")).toHaveTextContent(/Preparing the public copy/)
expect(within(pending).queryByRole("link", { name: "Open" })).not.toBeInTheDocument()

link = { ...link!, exportStatus: "ready" }
await router.settle(() => router.navigate(`${sharePath}?build=3`))
const ready = screen.getByRole("heading", { name: "Partner review" }).closest("li")!
expect(within(ready).getByRole("link", { name: "Open" })).toHaveAttribute(
"href",
"https://reader.example.net/s/12345678-1234-4234-8234-123456789abc",
)
expect(ready).toHaveTextContent("Password protected")
fireEvent.click(within(ready).getByText("Password"))
await router.settle(() =>
fireEvent.click(within(ready).getByRole("button", { name: "Remove password" })),
)
expect(changePassword).toHaveBeenCalledExactlyOnceWith({ password: null })
expect(await screen.findByText("Password removed.")).toBeVisible()
})

it("explains that a Build the private prototype service cannot play can't be shared publicly", async () => {
const { path, repository, prototype, latest } = previewRecords({ canManageSharing: true })
const api = stubHubFetch(
...authenticatedWorkspace([repository]),
http.get(`/api${path}/share-links`, () =>
Response.json({
resource: { repository, prototype, selectedBuild: latest },
links: [],
enabled: true,
canManage: true,
expirationOptions: ["seven_days"],
backend: "export",
selectedBuildShareable: false,
}),
),
)
await renderHubFlow(api, `${path}/share-links?build=3`)

expect(
screen.getByRole("heading", { name: "This Build can't be shared publicly" }),
).toBeVisible()
expect(screen.queryByRole("button", { name: "Create share link" })).not.toBeInTheDocument()
})

it("hides creation controls and previously created URLs when deployment sharing is disabled", async () => {
const { path, repository, prototype, latest } = previewRecords({ canManageSharing: true })
const api = stubHubFetch(
Expand Down
27 changes: 27 additions & 0 deletions hub/client/application/hub/routes/product-share-links/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
productMutationResponseSchema,
productShareIdSchema,
productShareInputSchema,
productSharePasswordInputSchema,
productSharingResponseSchema,
} from "@application/hub/product-contracts"
import type {
Expand Down Expand Up @@ -55,10 +56,12 @@ export async function clientAction({
const action = typeof actionValue === "string" ? actionValue.split("?")[0] : null
try {
if (action === base && !form.has("_method")) {
const password = form.get("share_link[password]")
const parsed = productShareInputSchema.safeParse({
label: form.get("share_link[label]"),
expiration: form.get("share_link[expiration]"),
buildNumber: Number(form.get("share_link[build_number]")),
...(typeof password === "string" && password ? { password } : {}),
})
if (!parsed.success) {
return data<ProductActionResult>(
Expand Down Expand Up @@ -86,6 +89,30 @@ export async function clientAction({
return data<ProductActionResult>({ saved: true, notice: response.notice })
}
}
if (action?.startsWith(`${base}/`) && form.get("_method") === "patch") {
const shareId = productShareIdSchema.safeParse(action.slice(base.length + 1))
const parsed = productSharePasswordInputSchema.safeParse({
password:
form.get("share_link[password_action]") === "remove"
? null
: form.get("share_link[password]"),
})
if (shareId.success && !parsed.success) {
return data<ProductActionResult>(
{ saved: false, error: parsed.error.issues.map(({ message }) => message).join(" ") },
{ status: 422 },
)
}
if (shareId.success && parsed.success) {
const response = await requestProductJson(
request,
`/api${base}/${shareId.data}`,
productMutationResponseSchema,
{ method: "PATCH", body: parsed.data },
)
return data<ProductActionResult>({ saved: true, notice: response.notice })
}
}
return data<ProductActionResult>(
{ saved: false, error: "This share-link action is not connected." },
{ status: 400 },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,38 @@ import type { ProductSharingResponse } from "@application/hub/product-contracts/
import { prototypeWorkspace } from "../prototype-workspace"
import { resourcePath } from "../resource-path"

const exportStatusLabels = {
pending: "Preparing the public copy. The link works when it's ready.",
ready: null,
updating: "Updating the public link. The previous password applies until Hub finishes.",
failed: "This link couldn't be prepared. Delete it and create a new one.",
revoking: "Revoked. Hub is still turning off the public copy and will keep retrying.",
}

function exportLinkState(
status: keyof typeof exportStatusLabels | null,
hasPassword: boolean,
passwordPath: string,
hasUrl: boolean,
) {
// Without a public origin, this Hub has turned exports off and cannot give out the link.
const statusLabel = hasUrl
? status
? exportStatusLabels[status]
: null
: "Public share exports are turned off for this Hub."
const live = hasUrl && (status === "ready" || status === "updating")
return {
...(statusLabel ? { statusLabel } : {}),
...(live ? {} : { unavailable: true }),
Comment on lines +28 to +31
canDelete: status !== "revoking",
...(hasUrl && (status === "ready" || status === "pending")
? { password: { hasPassword, path: passwordPath } }
: {}),
protectedLabel: hasPassword ? "Password protected" : undefined,
}
}

export function productShareLinksData(
workspace: WorkspaceResponse,
response: ProductSharingResponse,
Expand All @@ -14,11 +46,17 @@ export function productShareLinksData(
const { resource } = response
const { repository, prototype, selectedBuild } = resource
const base = `/repositories/${repository.id}/prototypes/${prototype.id}`
const selected =
selectedBuild?.state === "successful" && selectedBuild.previewUrl ? selectedBuild : null
const exports = response.backend === "export"
// Export links copy stored Build files, so they do not need the legacy preview address.
function hasPreview(build: { state: string; previewUrl?: string | null }) {
return build.state === "successful" && (exports || Boolean(build.previewUrl))
}
const selected = selectedBuild && hasPreview(selectedBuild) ? selectedBuild : null
const now = Date.now()
const active = response.links.filter(
(link) => response.enabled && !link.revokedAt && Date.parse(link.expiresAt) > now,
(link) =>
response.enabled &&
((!link.revokedAt && Date.parse(link.expiresAt) > now) || link.exportStatus === "revoking"),
)
return {
...prototypeWorkspace({
Expand All @@ -28,15 +66,13 @@ export function productShareLinksData(
search,
surface: "build",
}),
buildOptions: prototype.builds
.filter((build) => build.state === "successful" && build.previewUrl)
.map((build) => ({
number: build.number,
label: `v${build.number}`,
path: resourcePath(`${base}/share-links`, { build: build.number }),
state: build.state,
stateLabel: "Successful",
})),
buildOptions: prototype.builds.filter(hasPreview).map((build) => ({
number: build.number,
label: `v${build.number}`,
path: resourcePath(`${base}/share-links`, { build: build.number }),
state: build.state,
stateLabel: "Successful",
})),
closePath: resourcePath(base, { build: selected?.number ?? null }),
closeLabel: "Return to prototype",
alert: null,
Expand Down Expand Up @@ -68,7 +104,31 @@ export function productShareLinksData(
labelMaximumBytes: 100,
labelPlaceholder: "Usability review",
submitLabel: "Create share link",
...(exports
? {
passwordLabel: "Password (optional)",
passwordHint: "At least 8 characters. Leave blank for a link without a password.",
}
: {}),
},
...(exports
? {
passwordLabels: {
summary: "Password",
field: "New password",
hint: "At least 8 characters. Changing it signs out viewers who used the old password.",
save: "Save password",
remove: "Remove password",
},
}
: {}),
...(exports && selected && response.selectedBuildShareable === false
? {
unshareableHeading: "This Build can't be shared publicly",
unshareableLabel:
"Public links open Builds that Hub's private prototype service can already play. Choose another Build, or push a new Build from a proto/ branch.",
}
: {}),
heading: "Share links",
noBuildHeading: "No successful Build",
noBuildLabel: "A successful Build is required before creating a share link.",
Expand All @@ -88,12 +148,20 @@ export function productShareLinksData(
shareLinks: active.map((link) => ({
id: link.id,
label: link.label,
...(link.exportStatus !== undefined
? exportLinkState(
link.exportStatus ?? null,
link.hasPassword === true,
`${base}/share-links/${link.shareId}`,
Boolean(link.url),
)
: {}),
buildLabel: `Build ${link.buildNumber}`,
createdAt: link.createdAt,
createdLabel: `Created by @${link.createdBy}`,
expiresAt: link.expiresAt,
expiresLabel: `Expires ${new Date(link.expiresAt).toLocaleDateString()}`,
url: new URL(`/shared/${link.shareId}`, origin).href,
url: link.url ?? new URL(`/shared/${link.shareId}`, origin).href,
deletePath: `${base}/share-links/${link.shareId}`,
deletePrompt: `Delete “${link.label}”?`,
})),
Expand All @@ -104,7 +172,7 @@ export function productShareLinksData(
id: link.id,
label: link.label,
stateLabel: link.revokedAt ? "Revoked" : "Expired",
url: new URL(`/shared/${link.shareId}`, origin).href,
url: link.url ?? new URL(`/shared/${link.shareId}`, origin).href,
}))
: [],
}
Expand Down
Loading
Loading