Important Fixes, New mechanics, and many more
Some checks failed
CI / validate (push) Failing after 9m21s
Some checks failed
CI / validate (push) Failing after 9m21s
This commit is contained in:
56
apps/web/server/api/v1/campaigns/[id].get.ts
Normal file
56
apps/web/server/api/v1/campaigns/[id].get.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const access = await requireCampaignAccess(campaignId, user.id)
|
||||
const campaign = access.campaign
|
||||
const worldId = String(campaign.world_id)
|
||||
const [worlds, members, characters, openRounds, rounds] = await Promise.all([
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`worlds?select=id,title,genre,tone,premise,content_boundaries,hook,opening_scene&id=eq.${worldId}&limit=1`,
|
||||
),
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`campaign_members?select=id,user_id,role,active,ai_takeover_allowed,joined_at&campaign_id=eq.${campaignId}&order=joined_at.asc`,
|
||||
),
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`characters?select=id,campaign_id,user_id,name,concept,controller,abilities,hp,max_hp,defense,proficiency,inventory,statuses,persona,created_at&campaign_id=eq.${campaignId}&order=created_at.asc`,
|
||||
),
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`rounds?select=id,campaign_id,number,status,forced_by,narration,next_prompt,queued_at,resolved_at,error,created_at&campaign_id=eq.${campaignId}&status=eq.open&order=number.desc&limit=1`,
|
||||
),
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`rounds?select=id,campaign_id,number,status,forced_by,narration,next_prompt,queued_at,resolved_at,error,created_at&campaign_id=eq.${campaignId}&order=number.desc&limit=30`,
|
||||
),
|
||||
])
|
||||
const fallbackRounds = openRounds.length ? [] : await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`rounds?select=id,campaign_id,number,status,forced_by,narration,next_prompt,queued_at,resolved_at,error,created_at&campaign_id=eq.${campaignId}&order=number.desc&limit=1`,
|
||||
)
|
||||
const round = openRounds[0] ?? fallbackRounds[0] ?? null
|
||||
const userIds = [...new Set(members.map(member => String(member.user_id)))]
|
||||
const profiles = userIds.length
|
||||
? await stageTwoDatabase<Array<{ id: string; display_name: string }>>(
|
||||
`profiles?select=id,display_name&id=in.(${userIds.join(',')})`,
|
||||
)
|
||||
: []
|
||||
const profileById = new Map(profiles.map(profile => [profile.id, profile]))
|
||||
const visibleMembers = members.map(member => ({ ...member, profile: profileById.get(String(member.user_id)) ?? null }))
|
||||
const visibleRounds = rounds.slice().reverse()
|
||||
const visibleRoundIds = visibleRounds.map(item => String(item.id))
|
||||
const [intents, events, diceRolls] = await Promise.all([
|
||||
round ? stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`player_intents?select=id,round_id,member_id,character_id,action,ready,created_at,updated_at&round_id=eq.${String(round.id)}&order=created_at.asc`,
|
||||
) : Promise.resolve([]),
|
||||
stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`game_events?select=id,campaign_id,round_id,event_type,payload,created_at&campaign_id=eq.${campaignId}&order=created_at.desc&limit=50`,
|
||||
),
|
||||
visibleRoundIds.length ? stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`dice_rolls?select=id,round_id,actor_id,target_id,check_kind,formula,rolls,kept,modifier,total,difficulty,success,created_at&round_id=in.(${visibleRoundIds.join(',')})&order=created_at.asc`,
|
||||
) : Promise.resolve([]),
|
||||
])
|
||||
return { campaign, world: worlds[0] ?? null, members: visibleMembers, characters, round, rounds: visibleRounds, intents, events: events.slice().reverse(), diceRolls }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
53
apps/web/server/api/v1/campaigns/[id]/characters.post.ts
Normal file
53
apps/web/server/api/v1/campaigns/[id]/characters.post.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { AbilityScoresSchema } from '@dng/shared'
|
||||
import { z } from 'zod'
|
||||
import { requireCampaignAccess, requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
concept: z.string().trim().min(3).max(600),
|
||||
controller: z.enum(['human', 'ai']).default('human'),
|
||||
abilities: AbilityScoresSchema,
|
||||
hp: z.number().int().min(0),
|
||||
maxHp: z.number().int().min(1),
|
||||
defense: z.number().int().min(1).max(40),
|
||||
proficiency: z.number().int().min(1).max(10).default(2),
|
||||
inventory: z.array(z.string().trim().min(1).max(120)).max(50).default([]),
|
||||
statuses: z.array(z.string().trim().min(1).max(80)).max(12).default([]),
|
||||
persona: z.record(z.string(), z.unknown()).default({}),
|
||||
}).strict().refine(value => value.hp <= value.maxHp, { message: 'hp must not exceed maxHp', path: ['hp'] })
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const access = await requireCampaignAccess(campaignId, user.id)
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
if (body.controller === 'ai' && !access.owner) {
|
||||
throw createError({ statusCode: 403, statusMessage: 'Only the campaign owner can add AI heroes.' })
|
||||
}
|
||||
requireStageTwoSafeText([body.name, body.concept, ...body.inventory, ...body.statuses, JSON.stringify(body.persona)].join('\n'))
|
||||
const rows = await stageTwoDatabase<Array<Record<string, unknown>>>('characters', {
|
||||
method: 'POST',
|
||||
prefer: 'return=representation',
|
||||
body: JSON.stringify({
|
||||
campaign_id: campaignId,
|
||||
user_id: body.controller === 'human' ? user.id : null,
|
||||
name: body.name,
|
||||
concept: body.concept,
|
||||
controller: body.controller,
|
||||
abilities: body.abilities,
|
||||
hp: body.hp,
|
||||
max_hp: body.maxHp,
|
||||
defense: body.defense,
|
||||
proficiency: body.proficiency,
|
||||
inventory: body.inventory,
|
||||
statuses: body.statuses,
|
||||
persona: body.persona,
|
||||
}),
|
||||
})
|
||||
setResponseStatus(event, 201)
|
||||
return { character: rows[0] }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
32
apps/web/server/api/v1/campaigns/[id]/invites.post.ts
Normal file
32
apps/web/server/api/v1/campaigns/[id]/invites.post.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({
|
||||
maxUses: z.number().int().min(1).max(20).default(1),
|
||||
expiresInHours: z.number().int().min(1).max(720).default(72),
|
||||
}).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
await requireCampaignAccess(campaignId, user.id, true)
|
||||
const body = BodySchema.parse((await readBody(event)) ?? {})
|
||||
const token = randomBytes(32).toString('base64url')
|
||||
const tokenHash = createHash('sha256').update(token).digest('hex')
|
||||
const expiresAt = new Date(Date.now() + body.expiresInHours * 3_600_000).toISOString()
|
||||
await stageTwoDatabase('invites', {
|
||||
method: 'POST',
|
||||
prefer: 'return=minimal',
|
||||
body: JSON.stringify({
|
||||
campaign_id: campaignId, created_by: user.id, token_hash: tokenHash,
|
||||
max_uses: body.maxUses, expires_at: expiresAt,
|
||||
}),
|
||||
})
|
||||
setResponseStatus(event, 201)
|
||||
return { token, expiresAt, maxUses: body.maxUses }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from 'zod'
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ aiTakeoverAllowed: z.boolean() }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const memberId = stageTwoUuid(getRouterParam(event, 'memberId'), 'member id')
|
||||
await requireCampaignAccess(campaignId, user.id, true)
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
const members = await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`campaign_members?id=eq.${memberId}&campaign_id=eq.${campaignId}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
prefer: 'return=representation',
|
||||
body: JSON.stringify({ ai_takeover_allowed: body.aiTakeoverAllowed }),
|
||||
},
|
||||
)
|
||||
if (!members[0]) throw createError({ statusCode: 404, statusMessage: 'Campaign member not found.' })
|
||||
return { member: members[0] }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const roundId = stageTwoUuid(getRouterParam(event, 'roundId'), 'round id')
|
||||
await requireCampaignAccess(campaignId, user.id, true)
|
||||
const rounds = await stageTwoDatabase<Array<{ id: string; status: string }>>(
|
||||
`rounds?select=id,status&id=eq.${roundId}&campaign_id=eq.${campaignId}&limit=1`,
|
||||
)
|
||||
if (!rounds[0]) throw createError({ statusCode: 404, statusMessage: 'Round not found.' })
|
||||
if (rounds[0].status !== 'open') throw createError({ statusCode: 409, statusMessage: 'Round is not open.' })
|
||||
const jobId = await stageTwoRpc<string>('stage_two_force_round', {
|
||||
p_round_id: roundId, p_owner_id: user.id,
|
||||
})
|
||||
setResponseStatus(event, 202)
|
||||
return { jobId, status: 'queued' }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import { requireCampaignAccess, requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({
|
||||
characterId: z.string().uuid(),
|
||||
action: z.string().trim().min(1).max(2000),
|
||||
ready: z.boolean().default(false),
|
||||
}).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const roundId = stageTwoUuid(getRouterParam(event, 'roundId'), 'round id')
|
||||
await requireCampaignAccess(campaignId, user.id)
|
||||
const rounds = await stageTwoDatabase<Array<{ id: string; status: string }>>(
|
||||
`rounds?select=id,status&id=eq.${roundId}&campaign_id=eq.${campaignId}&limit=1`,
|
||||
)
|
||||
if (!rounds[0]) throw createError({ statusCode: 404, statusMessage: 'Round not found.' })
|
||||
if (rounds[0].status !== 'open') throw createError({ statusCode: 409, statusMessage: 'Round is not open.' })
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
requireStageTwoSafeText(body.action)
|
||||
const result = await stageTwoRpc<Record<string, unknown>>('stage_two_submit_intent', {
|
||||
p_round_id: roundId,
|
||||
p_user_id: user.id,
|
||||
p_character_id: body.characterId,
|
||||
p_action: body.action,
|
||||
p_ready: body.ready,
|
||||
})
|
||||
return result
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from 'zod'
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ ready: z.boolean().default(true) }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const roundId = stageTwoUuid(getRouterParam(event, 'roundId'), 'round id')
|
||||
await requireCampaignAccess(campaignId, user.id)
|
||||
const body = BodySchema.parse((await readBody(event)) ?? {})
|
||||
const rounds = await stageTwoDatabase<Array<{ id: string; status: string }>>(
|
||||
`rounds?select=id,status&id=eq.${roundId}&campaign_id=eq.${campaignId}&limit=1`,
|
||||
)
|
||||
if (!rounds[0]) throw createError({ statusCode: 404, statusMessage: 'Round not found.' })
|
||||
if (rounds[0].status !== 'open') throw createError({ statusCode: 409, statusMessage: 'Round is not open.' })
|
||||
const members = await stageTwoDatabase<Array<{ id: string }>>(
|
||||
`campaign_members?select=id&campaign_id=eq.${campaignId}&user_id=eq.${user.id}&active=eq.true&limit=1`,
|
||||
)
|
||||
if (!members[0]) throw createError({ statusCode: 403, statusMessage: 'Active campaign membership not found.' })
|
||||
const intents = await stageTwoDatabase<Array<{ character_id: string; action: string }>>(
|
||||
`player_intents?select=character_id,action&round_id=eq.${roundId}&member_id=eq.${members[0].id}&limit=1`,
|
||||
)
|
||||
if (!intents[0]) throw createError({ statusCode: 409, statusMessage: 'Submit an action before marking ready.' })
|
||||
return await stageTwoRpc<Record<string, unknown>>('stage_two_submit_intent', {
|
||||
p_round_id: roundId,
|
||||
p_user_id: user.id,
|
||||
p_character_id: intents[0].character_id,
|
||||
p_action: intents[0].action,
|
||||
p_ready: body.ready,
|
||||
})
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
||||
const roundId = stageTwoUuid(getRouterParam(event, 'roundId'), 'round id')
|
||||
await requireCampaignAccess(campaignId, user.id, true)
|
||||
const rounds = await stageTwoDatabase<Array<{ id: string; status: string }>>(
|
||||
`rounds?select=id,status&id=eq.${roundId}&campaign_id=eq.${campaignId}&limit=1`,
|
||||
)
|
||||
if (!rounds[0]) throw createError({ statusCode: 404, statusMessage: 'Round not found.' })
|
||||
if (rounds[0].status !== 'failed') throw createError({ statusCode: 409, statusMessage: 'Only a failed round can be retried.' })
|
||||
const jobId = await stageTwoRpc<string>('stage_two_retry_failed_round', {
|
||||
p_round_id: roundId,
|
||||
p_owner_id: user.id,
|
||||
})
|
||||
setResponseStatus(event, 202)
|
||||
return { jobId, status: 'queued' }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
17
apps/web/server/api/v1/campaigns/index.get.ts
Normal file
17
apps/web/server/api/v1/campaigns/index.get.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { requireStageTwoUser, stageTwoApiError, stageTwoDatabase } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const memberships = await stageTwoDatabase<Array<{ campaign_id: string }>>(
|
||||
`campaign_members?select=campaign_id&user_id=eq.${user.id}&active=eq.true`,
|
||||
)
|
||||
const filters = [`owner_id.eq.${user.id}`, ...memberships.map(item => `id.eq.${item.campaign_id}`)]
|
||||
const campaigns = await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`campaigns?select=id,world_id,owner_id,title,current_scene,next_prompt,status,created_at,updated_at&or=(${filters.join(',')})&order=updated_at.desc`,
|
||||
)
|
||||
return { campaigns }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
19
apps/web/server/api/v1/campaigns/index.post.ts
Normal file
19
apps/web/server/api/v1/campaigns/index.post.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod'
|
||||
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ worldId: z.string().uuid(), title: z.string().trim().min(3).max(100) }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
requireStageTwoSafeText(body.title)
|
||||
const campaignId = await stageTwoRpc<string>('stage_two_create_campaign', {
|
||||
p_world_id: stageTwoUuid(body.worldId, 'world id'), p_owner_id: user.id, p_title: body.title,
|
||||
})
|
||||
setResponseStatus(event, 201)
|
||||
return { campaignId }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
15
apps/web/server/api/v1/coauthor/sessions/[id].get.ts
Normal file
15
apps/web/server/api/v1/coauthor/sessions/[id].get.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const id = stageTwoUuid(getRouterParam(event, 'id'))
|
||||
const sessions = await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`coauthor_sessions?select=id,status,messages,generated_world,confirmed_world_id,created_at,updated_at&id=eq.${id}&owner_id=eq.${user.id}&limit=1`,
|
||||
)
|
||||
if (!sessions[0]) throw createError({ statusCode: 404, statusMessage: 'Coauthor session not found.' })
|
||||
return { session: { ...sessions[0], generatedWorld: sessions[0].generated_world ?? null } }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { WorldStarterSchema } from '@dng/shared'
|
||||
import { z } from 'zod'
|
||||
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ world: WorldStarterSchema.optional() }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const sessionId = stageTwoUuid(getRouterParam(event, 'id'), 'session id')
|
||||
const body = BodySchema.parse((await readBody(event)) ?? {})
|
||||
const sessions = await stageTwoDatabase<Array<{ generated_world: unknown }>>(
|
||||
`coauthor_sessions?select=generated_world&id=eq.${sessionId}&owner_id=eq.${user.id}&limit=1`,
|
||||
)
|
||||
if (!sessions[0]) throw createError({ statusCode: 404, statusMessage: 'Coauthor session not found.' })
|
||||
const world = WorldStarterSchema.parse(body.world ?? sessions[0].generated_world)
|
||||
requireStageTwoSafeText(JSON.stringify(world))
|
||||
if (body.world) {
|
||||
await stageTwoDatabase(`coauthor_sessions?id=eq.${sessionId}&owner_id=eq.${user.id}`, {
|
||||
method: 'PATCH', prefer: 'return=minimal', body: JSON.stringify({ generated_world: world, updated_at: new Date().toISOString() }),
|
||||
})
|
||||
}
|
||||
const worldId = await stageTwoRpc<string>('stage_two_confirm_world', {
|
||||
p_session_id: sessionId, p_owner_id: user.id,
|
||||
})
|
||||
return { worldId }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { requireStageTwoUser, stageTwoApiError, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const sessionId = stageTwoUuid(getRouterParam(event, 'id'), 'session id')
|
||||
const jobId = await stageTwoRpc<string>('stage_two_enqueue_world_generation', {
|
||||
p_session_id: sessionId, p_owner_id: user.id,
|
||||
})
|
||||
setResponseStatus(event, 202)
|
||||
return { jobId, status: 'queued' }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod'
|
||||
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ content: z.string().trim().min(1).max(5000) }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const sessionId = stageTwoUuid(getRouterParam(event, 'id'), 'session id')
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
requireStageTwoSafeText(body.content)
|
||||
const session = await stageTwoRpc<Record<string, unknown>>('stage_two_append_coauthor_message', {
|
||||
p_session_id: sessionId, p_owner_id: user.id, p_content: body.content,
|
||||
})
|
||||
return { session }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { z } from 'zod'
|
||||
import { buildJsonCompletion, parseJsonCompletion } from '~/server/utils/ai-provider'
|
||||
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const MessageSchema = z.object({ role: z.enum(['user', 'assistant']), content: z.string().min(1).max(5000) })
|
||||
const QuestionSchema = z.object({
|
||||
question: z.string().trim().min(5).max(300),
|
||||
options: z.array(z.string().trim().min(1).max(100)).length(3),
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const sessionId = stageTwoUuid(getRouterParam(event, 'id'), 'session id')
|
||||
const sessions = await stageTwoDatabase<Array<{ status: string; messages: unknown }>>(
|
||||
`coauthor_sessions?select=status,messages&id=eq.${sessionId}&owner_id=eq.${user.id}&limit=1`,
|
||||
)
|
||||
const session = sessions[0]
|
||||
if (!session) throw createError({ statusCode: 404, statusMessage: 'Coauthor session not found.' })
|
||||
if (session.status !== 'collecting') throw createError({ statusCode: 409, statusMessage: 'This coauthor session is not accepting answers.' })
|
||||
const messages = z.array(MessageSchema).min(1).max(12).parse(session.messages)
|
||||
const answerCount = Math.max(0, messages.filter(message => message.role === 'user').length - 1)
|
||||
if (answerCount >= 4) return { readyToGenerate: true }
|
||||
|
||||
const completion = buildJsonCompletion(useRuntimeConfig(), {
|
||||
system: `You are the Dungeons & Ground coauthor. Based only on this conversation, ask one focused question that makes the original TTRPG world more playable. This is clarification ${answerCount + 1} of 4. Do not repeat a topic already answered. Adapt to the requested genre. Provide exactly three concise, mutually distinct answer options. Keep everything suitable for ages 13+.`,
|
||||
messages,
|
||||
schemaName: 'coauthor_question',
|
||||
jsonSchema: QuestionSchema.toJSONSchema(),
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 30_000)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(completion.endpoint, {
|
||||
method: 'POST', headers: completion.headers, body: JSON.stringify(completion.body), signal: controller.signal,
|
||||
})
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
if (!response.ok) throw createError({ statusCode: 502, statusMessage: 'The coauthor is temporarily unavailable.' })
|
||||
const question = QuestionSchema.parse(parseJsonCompletion(await response.json()))
|
||||
requireStageTwoSafeText([question.question, ...question.options].join('\n'))
|
||||
await stageTwoRpc('stage_two_append_coauthor_assistant_message', {
|
||||
p_session_id: sessionId, p_owner_id: user.id, p_content: question.question,
|
||||
})
|
||||
return {
|
||||
readyToGenerate: false,
|
||||
question: { id: `question-${messages.length}`, label: question.question, options: question.options },
|
||||
}
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
13
apps/web/server/api/v1/coauthor/sessions/index.get.ts
Normal file
13
apps/web/server/api/v1/coauthor/sessions/index.get.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { requireStageTwoUser, stageTwoApiError, stageTwoDatabase } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const sessions = await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`coauthor_sessions?select=id,status,messages,generated_world,confirmed_world_id,created_at,updated_at&owner_id=eq.${user.id}&order=updated_at.desc`,
|
||||
)
|
||||
return { sessions }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
24
apps/web/server/api/v1/coauthor/sessions/index.post.ts
Normal file
24
apps/web/server/api/v1/coauthor/sessions/index.post.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod'
|
||||
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ message: z.string().trim().min(1).max(5000).optional() }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const body = BodySchema.parse((await readBody(event)) ?? {})
|
||||
if (body.message) requireStageTwoSafeText(body.message)
|
||||
const sessions = await stageTwoDatabase<Array<Record<string, unknown>>>('coauthor_sessions', {
|
||||
method: 'POST',
|
||||
prefer: 'return=representation',
|
||||
body: JSON.stringify({
|
||||
owner_id: user.id,
|
||||
messages: body.message ? [{ role: 'user', content: body.message }] : [],
|
||||
}),
|
||||
})
|
||||
setResponseStatus(event, 201)
|
||||
return { session: sessions[0] }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
19
apps/web/server/api/v1/invites/join.post.ts
Normal file
19
apps/web/server/api/v1/invites/join.post.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import { requireStageTwoUser, stageTwoApiError, stageTwoRpc } from '~/server/utils/stage-two-supabase'
|
||||
|
||||
const BodySchema = z.object({ token: z.string().trim().min(20).max(200) }).strict()
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const user = await requireStageTwoUser(event)
|
||||
const body = BodySchema.parse(await readBody(event))
|
||||
const tokenHash = createHash('sha256').update(body.token).digest('hex')
|
||||
const campaignId = await stageTwoRpc<string>('stage_two_join_campaign', {
|
||||
p_token_hash: tokenHash, p_user_id: user.id,
|
||||
})
|
||||
return { campaignId }
|
||||
} catch (error) {
|
||||
stageTwoApiError(error)
|
||||
}
|
||||
})
|
||||
@@ -9,4 +9,12 @@ describe('required Supabase runtime config', () => {
|
||||
it('reports missing credentials clearly', () => {
|
||||
expect(() => assertRequiredSupabaseConfig({ public: {} })).toThrow('SUPABASE_SERVICE_ROLE_KEY is required')
|
||||
})
|
||||
|
||||
it('rejects credentials from different Supabase projects', () => {
|
||||
expect(() => assertRequiredSupabaseConfig({
|
||||
supabaseUrl: 'https://server-project.supabase.co',
|
||||
supabaseServiceRoleKey: 'service',
|
||||
public: { supabaseUrl: 'https://public-project.supabase.co', supabaseAnonKey: 'anon' },
|
||||
})).toThrow('must point to the same project')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,4 +15,10 @@ export function assertRequiredSupabaseConfig(config: unknown): void {
|
||||
const details = result.error.issues.map(issue => issue.message).join('; ')
|
||||
throw new Error(`Invalid Supabase runtime configuration: ${details}`)
|
||||
}
|
||||
|
||||
const serverOrigin = new URL(result.data.supabaseUrl).origin
|
||||
const publicOrigin = new URL(result.data.public.supabaseUrl).origin
|
||||
if (serverOrigin !== publicOrigin) {
|
||||
throw new Error('Invalid Supabase runtime configuration: SUPABASE_URL and NUXT_PUBLIC_SUPABASE_URL must point to the same project')
|
||||
}
|
||||
}
|
||||
|
||||
21
apps/web/server/utils/stage-two-supabase.test.ts
Normal file
21
apps/web/server/utils/stage-two-supabase.test.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { stageTwoDatabase } from './stage-two-supabase'
|
||||
|
||||
describe('stage-two Supabase client', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('accepts successful PostgREST return=minimal responses with an empty body', async () => {
|
||||
vi.stubGlobal('useRuntimeConfig', () => ({
|
||||
supabaseUrl: 'https://example.supabase.co',
|
||||
supabaseServiceRoleKey: 'service-role-key',
|
||||
public: { supabaseAnonKey: 'anon-key' },
|
||||
}))
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 201 })))
|
||||
|
||||
await expect(stageTwoDatabase('invites', {
|
||||
method: 'POST',
|
||||
prefer: 'return=minimal',
|
||||
body: '{}',
|
||||
})).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
126
apps/web/server/utils/stage-two-supabase.ts
Normal file
126
apps/web/server/utils/stage-two-supabase.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { z } from 'zod'
|
||||
import type { H3Event } from 'h3'
|
||||
import { moderate13Plus } from '@dng/shared'
|
||||
|
||||
const UuidSchema = z.string().uuid()
|
||||
const AuthEmailSchema = z.preprocess(
|
||||
value => value === null || value === '' ? undefined : value,
|
||||
z.string().email().optional(),
|
||||
)
|
||||
const AuthUserSchema = z.object({ id: UuidSchema, email: AuthEmailSchema })
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
prefer?: string
|
||||
}
|
||||
|
||||
export interface StageTwoUser {
|
||||
id: string
|
||||
email?: string
|
||||
}
|
||||
|
||||
export class StageTwoDatabaseError extends Error {
|
||||
constructor(public status: number, message: string, public code?: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
function runtime() {
|
||||
const config = useRuntimeConfig()
|
||||
const url = z.string().url().parse(config.supabaseUrl)
|
||||
const serviceKey = z.string().min(1).parse(config.supabaseServiceRoleKey)
|
||||
const anonKey = z.string().min(1).parse(config.public.supabaseAnonKey)
|
||||
return { url: url.replace(/\/$/, ''), serviceKey, anonKey }
|
||||
}
|
||||
|
||||
export function stageTwoUuid(value: unknown, label = 'id'): string {
|
||||
const parsed = UuidSchema.safeParse(value)
|
||||
if (!parsed.success) throw createError({ statusCode: 400, statusMessage: `Invalid ${label}.` })
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export function requireStageTwoSafeText(text: string): void {
|
||||
const result = moderate13Plus(text)
|
||||
if (!result.allowed) {
|
||||
throw createError({ statusCode: 422, statusMessage: `Content is outside the 13+ policy: ${result.categories.join(', ')}.` })
|
||||
}
|
||||
}
|
||||
|
||||
export async function stageTwoDatabase<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { url, serviceKey } = runtime()
|
||||
const response = await fetch(new URL(`/rest/v1/${path}`, url), {
|
||||
...options,
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
Authorization: `Bearer ${serviceKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(options.prefer ? { Prefer: options.prefer } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
})
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as { code?: string; message?: string } | null
|
||||
throw new StageTwoDatabaseError(response.status, payload?.message || `Supabase request failed (${response.status}).`, payload?.code)
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
// PostgREST commonly returns 201/200 with an empty body for
|
||||
// `Prefer: return=minimal`; parsing that as JSON throws after a successful
|
||||
// database mutation and incorrectly turns the route into HTTP 500.
|
||||
const text = await response.text()
|
||||
if (!text.trim()) return undefined as T
|
||||
return JSON.parse(text) as T
|
||||
}
|
||||
|
||||
export function stageTwoRpc<T>(name: string, body: Record<string, unknown>): Promise<T> {
|
||||
return stageTwoDatabase<T>(`rpc/${name}`, { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export async function requireStageTwoUser(event: H3Event): Promise<StageTwoUser> {
|
||||
const authorization = getHeader(event, 'authorization')
|
||||
if (!authorization?.startsWith('Bearer ') || authorization.length <= 7) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'A Supabase access token is required.' })
|
||||
}
|
||||
const { url, anonKey } = runtime()
|
||||
const response = await fetch(new URL('/auth/v1/user', url), {
|
||||
headers: { apikey: anonKey, Authorization: authorization },
|
||||
})
|
||||
if (!response.ok) throw createError({ statusCode: 401, statusMessage: 'The access token is invalid or expired.' })
|
||||
const parsed = AuthUserSchema.safeParse(await response.json())
|
||||
if (!parsed.success) throw createError({ statusCode: 401, statusMessage: 'Supabase returned an invalid user.' })
|
||||
|
||||
const profiles = await stageTwoDatabase<Array<{ id: string }>>(`profiles?select=id&id=eq.${parsed.data.id}&limit=1`)
|
||||
if (!profiles[0]) throw createError({ statusCode: 403, statusMessage: 'This account is not enabled for the alpha.' })
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export async function requireCampaignAccess(campaignId: string, userId: string, ownerOnly = false) {
|
||||
const campaigns = await stageTwoDatabase<Array<Record<string, unknown>>>(
|
||||
`campaigns?select=*&id=eq.${campaignId}&limit=1`,
|
||||
)
|
||||
const campaign = campaigns[0]
|
||||
if (!campaign) throw createError({ statusCode: 404, statusMessage: 'Campaign not found.' })
|
||||
if (campaign.owner_id === userId) return { campaign, owner: true }
|
||||
if (ownerOnly) throw createError({ statusCode: 403, statusMessage: 'Only the campaign owner can do that.' })
|
||||
const members = await stageTwoDatabase<Array<{ id: string; active: boolean }>>(
|
||||
`campaign_members?select=id,active&campaign_id=eq.${campaignId}&user_id=eq.${userId}&active=eq.true&limit=1`,
|
||||
)
|
||||
if (!members[0]) throw createError({ statusCode: 404, statusMessage: 'Campaign not found.' })
|
||||
return { campaign, owner: false, memberId: members[0].id }
|
||||
}
|
||||
|
||||
export function stageTwoApiError(error: unknown): never {
|
||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||
if (error instanceof StageTwoDatabaseError) {
|
||||
if (error.code === 'PGRST202' || error.code === 'PGRST205') {
|
||||
throw createError({
|
||||
statusCode: 503,
|
||||
statusMessage: 'The Supabase database schema is not installed or is out of date. Apply supabase/bootstrap.sql.',
|
||||
})
|
||||
}
|
||||
const conflict = /duplicate key|already exists|not claimable/i.test(error.message)
|
||||
throw createError({ statusCode: conflict ? 409 : error.status >= 500 ? 502 : 400, statusMessage: error.message })
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
throw createError({ statusCode: 400, statusMessage: error.issues.map(issue => issue.message).join('; ') })
|
||||
}
|
||||
throw createError({ statusCode: 500, statusMessage: error instanceof Error ? error.message : 'Unexpected server error.' })
|
||||
}
|
||||
Reference in New Issue
Block a user