feat: add public read-only sharing for computers
Build & Deploy / build (push) Failing after 5s
Build & Deploy / docker (push) Skipped

Adds the ability for an owner to share a computer build via a public,
unauthenticated link, inspired by a feature request from the original
pcbuilder repo (no such feature actually existed there — implemented
from scratch here).

- New columns on computers: share_token (unique, nullable), share_enabled,
  share_show_sell_price, share_show_cost
- computer_share_service.ts: generates a non-guessable share token
  (crypto.randomBytes, base64url), enables/disables sharing, and supports
  rotating the token to invalidate previously distributed links
- ComputerShareController (authenticated, owner-scoped like the rest of
  the app): PUT /computers/:id/share to update settings, POST
  /computers/:id/share/rotate to rotate the token
- PublicComputerController + GET /share/:token (outside any auth/guest
  group, reachable anonymously): resolves only computers with
  share_enabled = true, 404 otherwise
- ComputerPublicTransformer: dedicated read-only projection that never
  leaks userId, and only includes sellPrice/cost when the owner opted in
  via share_show_sell_price / share_show_cost — everything else (title,
  scores, state, components, pictures) is always visible on a shared link
- ComputerShareModal.vue: owner-facing UI (toggle sharing, choose which
  prices to expose, copy the public link, revoke/rotate it) wired into
  computers/show.vue via a new 'Share' button
- share/show.vue: public page rendered with EmptyLayout (no authenticated
  header/sidebar)
- Boolean columns use a  cast since MySQL returns tinyint(1),
  not native booleans, through Lucid
- 6 new functional tests covering: enabling sharing, price visibility
  toggles, disabling sharing revokes the link, cross-user protection on
  the share settings endpoint (404), token rotation invalidating the old
  link, and anonymous access to a shared computer
This commit is contained in:
Kevin L'Hereec committed 2026-07-23 11:43:38 +02:00
1 parent 84ae2b9617
commit da71d33450
22 files changed
+714 -8

No files matched your search

+5
View File
@@ -6,10 +6,15 @@
/// <reference path="./manifest.d.ts" />
import type { InferData, InferVariants } from '@adonisjs/core/types/transformers'
import type { InferSharedProps } from '@adonisjs/inertia/types'
import type ComputerPublicTransformer from '#transformers/computer_public_transformer'
import type UserTransformer from '#transformers/user_transformer'
import type InertiaMiddleware from '#middleware/inertia_middleware'
export namespace Data {
export type ComputerPublic = InferData<ComputerPublicTransformer>
export namespace ComputerPublic {
export type Variants = InferVariants<ComputerPublicTransformer>
}
export type User = InferData<UserTransformer>
export namespace User {
export type Variants = InferVariants<UserTransformer>
+18
View File
@@ -84,6 +84,24 @@ const routes = {
tokens: [{"old":"/computers/:id","type":0,"val":"computers","end":""},{"old":"/computers/:id","type":1,"val":"id","end":""}],
types: placeholder as Registry['computers.destroy']['types'],
},
'computers.share.update': {
methods: ["PUT"],
pattern: '/computers/:id/share',
tokens: [{"old":"/computers/:id/share","type":0,"val":"computers","end":""},{"old":"/computers/:id/share","type":1,"val":"id","end":""},{"old":"/computers/:id/share","type":0,"val":"share","end":""}],
types: placeholder as Registry['computers.share.update']['types'],
},
'computers.share.rotate': {
methods: ["POST"],
pattern: '/computers/:id/share/rotate',
tokens: [{"old":"/computers/:id/share/rotate","type":0,"val":"computers","end":""},{"old":"/computers/:id/share/rotate","type":1,"val":"id","end":""},{"old":"/computers/:id/share/rotate","type":0,"val":"share","end":""},{"old":"/computers/:id/share/rotate","type":0,"val":"rotate","end":""}],
types: placeholder as Registry['computers.share.rotate']['types'],
},
'share.show': {
methods: ["GET","HEAD"],
pattern: '/share/:token',
tokens: [{"old":"/share/:token","type":0,"val":"share","end":""},{"old":"/share/:token","type":1,"val":"token","end":""}],
types: placeholder as Registry['share.show']['types'],
},
'components.index': {
methods: ["GET","HEAD"],
pattern: '/components',
+36
View File
@@ -163,6 +163,42 @@ export interface Registry {
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/computers_controller').default['destroy']>>>
}
}
'computers.share.update': {
methods: ["PUT"]
pattern: '/computers/:id/share'
types: {
body: ExtractBody<InferInput<(typeof import('#validators/Computers/share').updateShareSettingsValidator)>>
paramsTuple: [ParamValue]
params: { id: ParamValue }
query: ExtractQuery<InferInput<(typeof import('#validators/Computers/share').updateShareSettingsValidator)>>
response: ExtractResponse<Awaited<ReturnType<import('#controllers/computer_share_controller').default['update']>>>
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/computer_share_controller').default['update']>>> | { status: 422; response: { errors: SimpleError[] } }
}
}
'computers.share.rotate': {
methods: ["POST"]
pattern: '/computers/:id/share/rotate'
types: {
body: {}
paramsTuple: [ParamValue]
params: { id: ParamValue }
query: {}
response: ExtractResponse<Awaited<ReturnType<import('#controllers/computer_share_controller').default['rotate']>>>
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/computer_share_controller').default['rotate']>>>
}
}
'share.show': {
methods: ["GET","HEAD"]
pattern: '/share/:token'
types: {
body: {}
paramsTuple: [ParamValue]
params: { token: ParamValue }
query: {}
response: ExtractResponse<Awaited<ReturnType<import('#controllers/public_computer_controller').default['show']>>>
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/public_computer_controller').default['show']>>>
}
}
'components.index': {
methods: ["GET","HEAD"]
pattern: '/components'
+7
View File
@@ -20,6 +20,13 @@ export interface ApiDefinition {
edit: typeof routes['computers.edit']
update: typeof routes['computers.update']
destroy: typeof routes['computers.destroy']
share: {
update: typeof routes['computers.share.update']
rotate: typeof routes['computers.share.rotate']
}
}
share: {
show: typeof routes['share.show']
}
components: {
index: typeof routes['components.index']
+2
View File
@@ -5,7 +5,9 @@
export const controllers = {
Components: () => import('#controllers/components_controller'),
ComputerShare: () => import('#controllers/computer_share_controller'),
Computers: () => import('#controllers/computers_controller'),
NewAccount: () => import('#controllers/new_account_controller'),
PublicComputer: () => import('#controllers/public_computer_controller'),
Session: () => import('#controllers/session_controller'),
}
+2
View File
@@ -26,11 +26,13 @@ declare module '@adonisjs/inertia/types' {
'layout/emptyLayout': ExtractProps<(typeof import('../../inertia/pages/layout/emptyLayout.vue'))['default']>
'layout/header': ExtractProps<(typeof import('../../inertia/pages/layout/header.vue'))['default']>
'layout/sidebar': ExtractProps<(typeof import('../../inertia/pages/layout/sidebar.vue'))['default']>
'share/show': ExtractProps<(typeof import('../../inertia/pages/share/show.vue'))['default']>
'widgets/AuthErrorAlert': ExtractProps<(typeof import('../../inertia/pages/widgets/AuthErrorAlert.vue'))['default']>
'widgets/ComponentEditor': ExtractProps<(typeof import('../../inertia/pages/widgets/ComponentEditor.vue'))['default']>
'widgets/ComponentsViewer': ExtractProps<(typeof import('../../inertia/pages/widgets/ComponentsViewer.vue'))['default']>
'widgets/ComputerCard': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputerCard.vue'))['default']>
'widgets/ComputerComponentsTable': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputerComponentsTable.vue'))['default']>
'widgets/ComputerShareModal': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputerShareModal.vue'))['default']>
'widgets/ComputersViewer': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputersViewer.vue'))['default']>
'widgets/CustomSelect': ExtractProps<(typeof import('../../inertia/pages/widgets/CustomSelect.vue'))['default']>
'widgets/DeleteConfirmationModal': ExtractProps<(typeof import('../../inertia/pages/widgets/DeleteConfirmationModal.vue'))['default']>
+7
View File
@@ -17,6 +17,9 @@ export type ScannedRoutes = {
'computers.edit': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.share.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.share.rotate': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'share.show': { paramsTuple: [ParamValue]; params: {'token': ParamValue} }
'components.index': { paramsTuple?: []; params?: {} }
'components.create': { paramsTuple?: []; params?: {} }
'components.store': { paramsTuple?: []; params?: {} }
@@ -33,6 +36,7 @@ export type ScannedRoutes = {
'computers.create': { paramsTuple?: []; params?: {} }
'computers.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.edit': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'share.show': { paramsTuple: [ParamValue]; params: {'token': ParamValue} }
'components.index': { paramsTuple?: []; params?: {} }
'components.create': { paramsTuple?: []; params?: {} }
'components.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
@@ -46,6 +50,7 @@ export type ScannedRoutes = {
'computers.create': { paramsTuple?: []; params?: {} }
'computers.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.edit': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'share.show': { paramsTuple: [ParamValue]; params: {'token': ParamValue} }
'components.index': { paramsTuple?: []; params?: {} }
'components.create': { paramsTuple?: []; params?: {} }
'components.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
@@ -56,10 +61,12 @@ export type ScannedRoutes = {
'session.store': { paramsTuple?: []; params?: {} }
'session.destroy': { paramsTuple?: []; params?: {} }
'computers.store': { paramsTuple?: []; params?: {} }
'computers.share.rotate': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'components.store': { paramsTuple?: []; params?: {} }
}
PUT: {
'computers.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'computers.share.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
'components.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
}
DELETE: {
@@ -0,0 +1,46 @@
import type { HttpContext } from '@adonisjs/core/http'
import Computer from '#models/computer'
import { updateShareSettingsValidator } from '#validators/Computers/share'
import { disableSharing, enableSharing, rotateShareToken } from '#services/computer_share_service'
export default class ComputerShareController {
/**
* Update the share settings (enable/disable + which prices are visible)
* for a computer owned by the current user.
*/
async update({ auth, params, request, response }: HttpContext) {
const user = await auth.authenticate()
const computer = await Computer.query()
.where('user_id', user.id)
.andWhere('id', params.id)
.firstOrFail()
const { enabled, showSellPrice, showCost } = await request.validateUsing(
updateShareSettingsValidator
)
if (enabled) {
await enableSharing(computer, { showSellPrice, showCost })
} else {
await disableSharing(computer)
}
return response.redirect(`/computers/${computer.id}`)
}
/**
* Rotate the share token for a computer, invalidating any previously
* distributed public link.
*/
async rotate({ auth, params, response }: HttpContext) {
const user = await auth.authenticate()
const computer = await Computer.query()
.where('user_id', user.id)
.andWhere('id', params.id)
.firstOrFail()
await rotateShareToken(computer)
return response.redirect(`/computers/${computer.id}`)
}
}
+3 -1
View File
@@ -80,7 +80,9 @@ export default class ComputersController {
.where('user_id', user.id)
.andWhere('id', computerId)
.firstOrFail()
return inertia.render('computers/show', { computer: asPageProp(computer.serialize()) })
return inertia.render('computers/show', {
computer: asPageProp({ ...computer.serialize(), shareToken: computer.shareToken }),
})
}
async edit({ params, inertia, auth }: HttpContext) {
@@ -0,0 +1,32 @@
import type { HttpContext } from '@adonisjs/core/http'
import Computer from '#models/computer'
import ComputerPublicTransformer from '#transformers/computer_public_transformer'
export default class PublicComputerController {
/**
* Publicly display a computer via its share token. No authentication
* required. Only resolves computers with sharing explicitly enabled.
*/
async show({ params, inertia, response }: HttpContext) {
const computer = await Computer.query()
.where('share_token', params.token)
.andWhere('share_enabled', true)
.preload('state')
.preload('components', (componentsQuery) => {
componentsQuery.preload('type')
})
.preload('pictures', (picturesQuery) => {
picturesQuery.orderBy('order')
})
.first()
if (!computer) {
response.status(404)
return inertia.render('errors/not_found', {})
}
return inertia.render('share/show', {
computer: ComputerPublicTransformer.transform(computer),
})
}
}
+12
View File
@@ -44,6 +44,18 @@ export default class Computer extends BaseModel {
@column({ serializeAs: null })
declare userId: number
@column({ serializeAs: null })
declare shareToken: string | null
@column({ consume: (value: unknown) => Boolean(value) })
declare shareEnabled: boolean
@column({ consume: (value: unknown) => Boolean(value) })
declare shareShowSellPrice: boolean
@column({ consume: (value: unknown) => Boolean(value) })
declare shareShowCost: boolean
@column.dateTime({ autoCreate: true })
declare createdAt: DateTime
+50
View File
@@ -0,0 +1,50 @@
import { randomBytes } from 'node:crypto'
import Computer from '#models/computer'
/**
* Generates a URL-safe, non-guessable share token.
*/
function generateShareToken(): string {
return randomBytes(24).toString('base64url')
}
/**
* Enables sharing for a computer, generating a share token if it doesn't
* already have one. Idempotent: calling it again just updates the display
* options without rotating the existing token.
*/
async function enableSharing(
computer: Computer,
options: { showSellPrice: boolean; showCost: boolean }
) {
if (!computer.shareToken) {
computer.shareToken = generateShareToken()
}
computer.shareEnabled = true
computer.shareShowSellPrice = options.showSellPrice
computer.shareShowCost = options.showCost
await computer.save()
return computer
}
/**
* Disables sharing for a computer. The share token is kept so re-enabling
* later doesn't require distributing a new link, but the public route only
* resolves computers where shareEnabled is true.
*/
async function disableSharing(computer: Computer) {
computer.shareEnabled = false
await computer.save()
return computer
}
/**
* Rotates the share token, invalidating any previously distributed link.
*/
async function rotateShareToken(computer: Computer) {
computer.shareToken = generateShareToken()
await computer.save()
return computer
}
export { enableSharing, disableSharing, rotateShareToken }
@@ -0,0 +1,30 @@
import type Computer from '#models/computer'
/**
* Transforms a Computer into the shape exposed on the public share page.
* Unlike the regular serialize(), this never leaks the owner id, and only
* includes sellPrice/cost when the owner explicitly enabled that on the
* share settings.
*/
export default class ComputerPublicTransformer {
static transform(computer: typeof Computer.prototype) {
return {
id: computer.id,
title: computer.title,
gpuScore: computer.gpuScore,
cpuScore: computer.cpuScore,
globalScore: computer.globalScore,
state: { name: computer.state.name },
sellPrice: computer.shareShowSellPrice ? computer.sellPrice : null,
cost: computer.shareShowCost ? computer.cost : null,
pictures: computer.pictures
.map((picture) => ({ link: picture.link, order: picture.order }))
.sort((a, b) => a.order - b.order),
components: computer.components.map((component) => ({
id: component.id,
name: component.name,
type: { name: component.type.name },
})),
}
}
}
+9
View File
@@ -0,0 +1,9 @@
import vine from '@vinejs/vine'
export const updateShareSettingsValidator = vine.compile(
vine.object({
enabled: vine.boolean(),
showSellPrice: vine.boolean(),
showCost: vine.boolean(),
})
)
@@ -0,0 +1,23 @@
import { BaseSchema } from '@adonisjs/lucid/schema'
export default class extends BaseSchema {
protected tableName = 'computers'
async up() {
this.schema.alterTable(this.tableName, (table) => {
table.string('share_token', 64).nullable().unique()
table.boolean('share_enabled').notNullable().defaultTo(false)
table.boolean('share_show_sell_price').notNullable().defaultTo(false)
table.boolean('share_show_cost').notNullable().defaultTo(false)
})
}
async down() {
this.schema.alterTable(this.tableName, (table) => {
table.dropColumn('share_token')
table.dropColumn('share_enabled')
table.dropColumn('share_show_sell_price')
table.dropColumn('share_show_cost')
})
}
}
+9 -1
View File
@@ -68,7 +68,7 @@ export class ComputerStateSchema extends BaseModel {
}
export class ComputerSchema extends BaseModel {
static $columns = ['cpuScore', 'createdAt', 'globalScore', 'gpuScore', 'id', 'sellPrice', 'stateId', 'title', 'updatedAt', 'userId'] as const
static $columns = ['cpuScore', 'createdAt', 'globalScore', 'gpuScore', 'id', 'sellPrice', 'shareEnabled', 'shareShowCost', 'shareShowSellPrice', 'shareToken', 'stateId', 'title', 'updatedAt', 'userId'] as const
$columns = ComputerSchema.$columns
@column()
declare cpuScore: number
@@ -83,6 +83,14 @@ export class ComputerSchema extends BaseModel {
@column()
declare sellPrice: number | null
@column()
declare shareEnabled: boolean
@column()
declare shareShowCost: boolean
@column()
declare shareShowSellPrice: boolean
@column()
declare shareToken: string | null
@column()
declare stateId: number
@column()
declare title: string
+22 -3
View File
@@ -1,15 +1,34 @@
<script setup lang="ts">
import { ref } from 'vue'
import { Link } from '@adonisjs/inertia/vue'
import type { Computer } from '~/pages/types/UITypes'
import ComputerShareModal from '~/pages/widgets/ComputerShareModal.vue'
const { computer } = defineProps<{ computer: Computer }>()
const showShareModal = ref(false)
</script>
<template>
<div class="max-w-4xl mx-auto p-4 md:p-8 bg-white shadow-lg rounded-lg">
<h1 class="text-xl md:text-2xl font-semibold mb-4 md:mb-8 text-gray-800">
{{ computer.title }}
</h1>
<div class="flex items-center justify-between mb-4 md:mb-8">
<h1 class="text-xl md:text-2xl font-semibold text-gray-800">
{{ computer.title }}
</h1>
<button
type="button"
@click="showShareModal = true"
class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition text-sm shrink-0"
>
{{ computer.shareEnabled ? 'Shared' : 'Share' }}
</button>
</div>
<ComputerShareModal
:show="showShareModal"
:computer="computer"
@close="showShareModal = false"
/>
<div class="mt-2">
<label class="block text-gray-700 text-sm font-bold mb-2">Components</label>
+92
View File
@@ -0,0 +1,92 @@
<script setup lang="ts">
import EmptyLayout from '~/pages/layout/emptyLayout.vue'
import { noImagePlaceholder } from '~/assets/images'
import type { PublicComputer } from '~/pages/types/UITypes'
defineOptions({ layout: EmptyLayout })
const { computer } = defineProps<{ computer: PublicComputer }>()
</script>
<template>
<div class="min-h-screen bg-gradient-to-br from-gray-100 to-gray-200 py-8 px-4">
<div class="max-w-3xl mx-auto p-4 md:p-8 bg-white shadow-lg rounded-lg">
<p class="text-xs uppercase tracking-wide text-indigo-600 font-semibold mb-2">Shared build</p>
<h1 class="text-xl md:text-2xl font-semibold mb-6 text-gray-800">
{{ computer.title }}
</h1>
<img
class="w-full max-h-96 object-cover rounded-lg mb-6"
:src="computer.pictures[0]?.link || noImagePlaceholder"
alt="Computer picture"
/>
<div class="mt-2">
<label class="block text-gray-700 text-sm font-bold mb-2">Components</label>
<div class="overflow-x-auto">
<table class="w-full border-collapse">
<thead class="bg-gray-200">
<tr>
<th class="border px-4 py-2 text-left">Name</th>
<th class="border px-4 py-2 text-left">Type</th>
</tr>
</thead>
<tbody>
<tr
v-for="component in computer.components"
:key="component.id"
class="hover:bg-gray-50"
>
<td class="border px-4 py-2">{{ component.name }}</td>
<td class="border px-4 py-2">{{ component.type?.name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-6 flex flex-wrap gap-4">
<div class="flex-1 min-w-[100px]">
<label class="block text-gray-700 text-sm font-bold mb-2">GPU Score</label>
<p class="w-full border-gray-200 px-3 py-2 border rounded text-gray-700">
{{ computer.gpuScore }}
</p>
</div>
<div class="flex-1 min-w-[100px]">
<label class="block text-gray-700 text-sm font-bold mb-2">CPU Score</label>
<p class="w-full border-gray-200 px-3 py-2 border rounded text-gray-700">
{{ computer.cpuScore }}
</p>
</div>
<div class="flex-1 min-w-[100px]">
<label class="block text-gray-700 text-sm font-bold mb-2">Global Score</label>
<p class="w-full border-gray-200 px-3 py-2 border rounded text-gray-700">
{{ computer.globalScore }}
</p>
</div>
</div>
<div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="pt-2">
<label class="block text-gray-700 text-sm font-bold mb-2">State</label>
<p class="w-full mt-2 border-gray-200 px-3 py-2.5 border rounded text-gray-700">
{{ computer.state.name }}
</p>
</div>
<div v-if="computer.sellPrice !== null" class="mt-2">
<label class="block text-gray-700 text-sm font-bold mb-2">Sell Price</label>
<p class="w-full mt-2 border-gray-200 px-3 py-2 border rounded text-gray-700">
${{ computer.sellPrice.toFixed(2) }}
</p>
</div>
<div v-if="computer.cost !== null" class="mt-2">
<label class="block text-gray-700 text-sm font-bold mb-2">Cost</label>
<p class="w-full mt-2 border-gray-200 px-3 py-2 border rounded text-gray-700">
${{ computer.cost.toFixed(2) }}
</p>
</div>
</div>
</div>
</div>
</template>
+17
View File
@@ -20,6 +20,23 @@ export type Computer = {
cost: number
pictures: { link: string; order: number }[]
components: Component[]
shareEnabled: boolean
shareShowSellPrice: boolean
shareShowCost: boolean
shareToken?: string | null
}
export type PublicComputer = {
id: number
title: string
gpuScore: number
cpuScore: number
globalScore: number
state: { name: string }
sellPrice: number | null
cost: number | null
pictures: { link: string; order: number }[]
components: { id: number; name: string; type: { name: string } }[]
}
export type Component = {
@@ -0,0 +1,111 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useForm } from '@inertiajs/vue3'
import type { Computer } from '~/pages/types/UITypes'
const props = defineProps<{
show: boolean
computer: Computer
}>()
const emit = defineEmits(['close'])
const form = reactive({
enabled: props.computer.shareEnabled,
showSellPrice: props.computer.shareShowSellPrice,
showCost: props.computer.shareShowCost,
})
const copied = ref(false)
const shareUrl = computed(() => {
if (!props.computer.shareToken) return ''
return `${window.location.origin}/share/${props.computer.shareToken}`
})
function submit() {
useForm(form).put(`/computers/${props.computer.id}/share`, {
preserveScroll: true,
onSuccess: () => emit('close'),
})
}
function rotateToken() {
useForm({}).post(`/computers/${props.computer.id}/share/rotate`, {
preserveScroll: true,
})
}
async function copyLink() {
await navigator.clipboard.writeText(shareUrl.value)
copied.value = true
setTimeout(() => (copied.value = false), 2000)
}
</script>
<template>
<div v-if="show" class="fixed inset-0 flex items-center justify-center z-50">
<div class="fixed inset-0 bg-black opacity-50" @click="emit('close')"></div>
<div class="bg-white rounded-lg p-6 z-10 w-full max-w-md mx-4">
<h2 class="text-lg font-semibold mb-4 text-gray-800">Share this build</h2>
<label class="flex items-center gap-2 mb-4 cursor-pointer">
<input v-model="form.enabled" type="checkbox" class="w-4 h-4" />
<span class="text-sm font-medium text-gray-700">Enable public link</span>
</label>
<div v-if="form.enabled" class="space-y-3 mb-4 pl-6">
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.showSellPrice" type="checkbox" class="w-4 h-4" />
<span class="text-sm text-gray-700">Show sell price</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.showCost" type="checkbox" class="w-4 h-4" />
<span class="text-sm text-gray-700">Show components cost</span>
</label>
</div>
<div v-if="computer.shareEnabled && computer.shareToken" class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2">Public link</label>
<div class="flex gap-2">
<input
:value="shareUrl"
readonly
class="flex-1 border-gray-200 px-3 py-2 border rounded text-gray-700 text-sm bg-gray-50"
/>
<button
type="button"
@click="copyLink"
class="px-3 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 text-sm shrink-0"
>
{{ copied ? 'Copied!' : 'Copy' }}
</button>
</div>
<button
type="button"
@click="rotateToken"
class="mt-2 text-xs text-red-600 hover:text-red-800 underline"
>
Revoke and generate a new link
</button>
</div>
<div class="flex justify-end space-x-2 mt-6">
<button
type="button"
@click="submit"
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700"
>
Save
</button>
<button
type="button"
@click="emit('close')"
class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Close
</button>
</div>
</div>
</div>
</template>
+11 -3
View File
@@ -11,9 +11,11 @@ import { middleware } from '#start/kernel'
import { controllers } from '#generated/controllers'
import router from '@adonisjs/core/services/router'
router.get('/', async ({ response }) => {
return response.redirect('/auth/login')
}).as('home')
router
.get('/', async ({ response }) => {
return response.redirect('/auth/login')
})
.as('home')
router
.group(() => {
@@ -42,10 +44,16 @@ router
router.get('/:id/edit', [controllers.Computers, 'edit']).as('computers.edit')
router.put('/:id', [controllers.Computers, 'update']).as('computers.update')
router.delete('/:id', [controllers.Computers, 'destroy']).as('computers.destroy')
router.put('/:id/share', [controllers.ComputerShare, 'update']).as('computers.share.update')
router
.post('/:id/share/rotate', [controllers.ComputerShare, 'rotate'])
.as('computers.share.rotate')
})
.prefix('/computers')
.use(middleware.auth())
router.get('/share/:token', [controllers.PublicComputer, 'show']).as('share.show')
router
.group(() => {
router.get('/', [controllers.Components, 'index']).as('components.index')
+170
View File
@@ -0,0 +1,170 @@
import { test } from '@japa/runner'
import User from '#models/user'
import Computer from '#models/computer'
import ComputerState from '#models/computer_state'
async function createUser(email: string) {
return User.create({
name: 'Test User',
email,
password: 'secret@123A',
})
}
async function createState(name = 'ON_GOING') {
return ComputerState.firstOrCreate({ name }, { name })
}
async function createComputer(userId: number, stateId: number) {
return Computer.create({
title: 'Shared PC',
sellPrice: 999,
gpuScore: 5,
cpuScore: 5,
globalScore: 5,
stateId,
userId,
})
}
test.group('Computer sharing', () => {
test('owner can enable sharing and the public page becomes reachable', async ({
client,
assert,
}) => {
const owner = await createUser('share-owner-a@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
const enableResponse = await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: true, showCost: false })
enableResponse.assertStatus(302)
await computer.refresh()
assert.isTrue(computer.shareEnabled)
assert.isString(computer.shareToken)
const publicResponse = await client
.get(`/share/${computer.shareToken}`)
.header('X-Inertia', 'true')
.header('X-Inertia-Version', '1')
.redirects(0)
publicResponse.assertStatus(200)
publicResponse.assertBodyContains({ props: { computer: { title: 'Shared PC' } } })
})
test('sell price and cost are hidden unless explicitly enabled', async ({ client }) => {
const owner = await createUser('share-owner-b@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: false, showCost: false })
await computer.refresh()
const publicResponse = await client
.get(`/share/${computer.shareToken}`)
.header('X-Inertia', 'true')
.header('X-Inertia-Version', '1')
.redirects(0)
publicResponse.assertStatus(200)
publicResponse.assertBodyContains({ props: { computer: { sellPrice: null, cost: null } } })
})
test('disabling sharing makes the public link unreachable', async ({ client }) => {
const owner = await createUser('share-owner-c@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: false, showCost: false })
await computer.refresh()
const token = computer.shareToken
await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: false, showSellPrice: false, showCost: false })
const publicResponse = await client.get(`/share/${token}`).redirects(0)
publicResponse.assertStatus(404)
})
test('a user cannot enable sharing on another user computer', async ({ client }) => {
const owner = await createUser('share-owner-d@example.com')
const attacker = await createUser('share-attacker-d@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
const response = await client
.put(`/computers/${computer.id}/share`)
.loginAs(attacker)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: true, showCost: true })
response.assertStatus(404)
})
test('rotating the share token invalidates the previous link', async ({ client, assert }) => {
const owner = await createUser('share-owner-e@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: false, showCost: false })
await computer.refresh()
const oldToken = computer.shareToken
await client
.post(`/computers/${computer.id}/share/rotate`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
await computer.refresh()
assert.notEqual(computer.shareToken, oldToken)
const oldLinkResponse = await client.get(`/share/${oldToken}`).redirects(0)
oldLinkResponse.assertStatus(404)
const newLinkResponse = await client.get(`/share/${computer.shareToken}`).redirects(0)
newLinkResponse.assertStatus(200)
})
test('an unauthenticated visitor can view a shared computer', async ({ client }) => {
const owner = await createUser('share-owner-f@example.com')
const state = await createState()
const computer = await createComputer(owner.id, state.id)
await client
.put(`/computers/${computer.id}/share`)
.loginAs(owner)
.withCsrfToken()
.redirects(0)
.json({ enabled: true, showSellPrice: true, showCost: true })
await computer.refresh()
// No .loginAs() here: simulates a fully anonymous visitor.
const response = await client.get(`/share/${computer.shareToken}`).redirects(0)
response.assertStatus(200)
})
})