code:
:: slave creation widgets [widget nobr]

/%
 Call as <<StartingGirlsWorkaround>>
%/
<<widget "StartingGirlsWorkaround">>
	<<display "Generate New Slave">>
	<<set $startingGirlCopied to 0>>
	<<set $activeSlave.health = 0>>
	<<set $activeSlave.devotion = 0>>
	<<set $activeSlave.trust = 0>>
	<<set $activeSlave.sexualQuirk to "none">>
	<<set $activeSlave.behavioralQuirk to "none">>
	<<set $activeSlave.fetishKnown to 1>>
	<<if $activeSlave.vagina < 0>>
	<<set $activeSlave.ovaries = 0>>
	<<elseif $activeSlave.vagina < 1>>
	<<set $activeSlave.vaginalSkill = 0>>
	<</if>>
	<<if $activeSlave.anus < 1>>
	<<set $activeSlave.analSkill = 0>>
	<</if>>

	<<set $activeSlave.actualAge to Number($activeSlave.actualAge)>>
	<<set $activeSlave.devotion = Number($activeSlave.devotion)>>
	<<set $activeSlave.trust = Number($activeSlave.trust)>>
	<<if $activeSlave.indenture >= 0>>
		<<set $activeSlave.indenture = Math.clamp($activeSlave.indenture, 26, 208)>>
	<</if>>
	<<set $activeSlave.height = Math.clamp($activeSlave.height, 85, 274)>>
	<<set $activeSlave.boobs = Math.clamp($activeSlave.boobs, 0, 10000)>>
	<<set $activeSlave.boobs = Number($activeSlave.boobs)>>
	<<set $activeSlave.boobs = Math.trunc($activeSlave.boobs/50)*50>>
<</widget>>

/%
 Call as <<StartingGirlsRefresh>>
%/
<<widget "StartingGirlsRefresh">>

	<<replace "#devotion">>
		@@color:yellow;Ambivalent.@@
	<</replace>>

	<<replace "#trust">>
		@@color:yellow;Fearful.@@
	<</replace>>

	<<replace "#legal">>
		Slave.
	<</replace>>

	<<replace "#voice">>
		<<if $activeSlave.voice == 0>>Mute.
		<<elseif $activeSlave.voice == 1>>Deep.
		<<elseif $activeSlave.voice is 2>>Normal.
		<<elseif $activeSlave.voice is 3>>High.
		<</if>>
	<</replace>>

	<<replace "#language">>
		<<if $activeSlave.accent == 0>>Unaccented.
		<<elseif $activeSlave.accent == 1>>Pretty $activeSlave.nationality accent.
		<<elseif $activeSlave.accent is 2>>Thick $activeSlave.nationality accent.
		<<else>>Not fluent.
		<</if>>
	<</replace>>

	<<replace "#age">>
		<<textbox "$activeSlave.actualAge" $activeSlave.actualAge "Starting Girls">>
	<</replace>>

	<<replace "#health">>
		@@color:yellow;Healthy.@@
	<</replace>>

	<<replace "#muscles">>
		Normal.
	<</replace>>

	<<replace "#waist">>
		Normal.
	<</replace>>

	<<if $seeExtreme == 1>>
		<<replace "#amp">>
			<<if $activeSlave.amp == 1>>Amputee.
			<<else>>Normal.
			<</if>>
		<</replace>>
	<</if>>

	<<replace "#height">>
		<<if $activeSlave.height < 150>>Petite.
		<<elseif $activeSlave.height < 160>>Short.
		<<elseif $activeSlave.height < 170>>Average.
		<<elseif $activeSlave.height < 185>>Tall.
		<<else>>Very tall.
		<</if>>
		<<textbox "$activeSlave.height" $activeSlave.height "Starting Girls">> cm
	<</replace>>

	<<replace "#weight">>
		<<if $activeSlave.weight < -95>>@@color:red;Emaciated.@@
		<<elseif $activeSlave.weight < -30>>@@color:red;Skinny.@@
		<<elseif $activeSlave.weight < -10>>Thin.
		<<elseif $activeSlave.weight <= 10>>Average.
		<<elseif $activeSlave.weight <= 30>>Plush.
		<<elseif $activeSlave.weight <= 95>>@@color:red;Chubby.@@
		<<else>>@@color:red;Fat.@@
		<</if>>
	<</replace>>

	<<if $seeRace == 1>>
		<<replace "#ethnicity">>
		<<textbox "$activeSlave.race" $activeSlave.race "Starting Girls">>
		<</replace>>
	<</if>>

	<<replace "#skin">>
		<<textbox "$activeSlave.skin" $activeSlave.skin "Starting Girls">>
	<</replace>>

	<<replace "#faceShape">>
		$activeSlave.faceShape
	<</replace>>

	<<replace "#face">>
		<<if $activeSlave.face < -2>>Very ugly.
		<<elseif $activeSlave.face is -2>>Ugly.
		<<elseif $activeSlave.face is -1>>Unattractive.
		<<elseif $activeSlave.face == 0>>Average.
		<<elseif $activeSlave.face == 1>>Attractive.
		<<elseif $activeSlave.face is 2>>Beautiful.
		<<else>>Very beautiful.
		<</if>>
	<</replace>>

	<<replace "#lips">>
		<<if $activeSlave.lips <= 10>>Thin.
		<<elseif $activeSlave.lips <= 20>>Normal.
		<<elseif $activeSlave.lips <= 40>>Plush.
		<<elseif $activeSlave.lips <= 70>>Big.
		<<elseif $activeSlave.lips <= 95>>Huge.
		<<else>>Facepussy.
		<</if>>
	<</replace>>

	<<replace "#teeth">>
		<<if $activeSlave.teeth is "crooked">>Crooked.
		<<elseif $activeSlave.teeth is "straightening braces">>Braces.
		<<else>>Straight.
		<</if>>
	<</replace>>

	<<replace "#vision">>
		<<if $seeExtreme == 1>>
			<<if $activeSlave.eyes is -2>>Blind.
			<<elseif $activeSlave.eyes is -1>>Nearsighted.
			<<else>>Normal.
			<</if>>
		<<else>>
			<<if $activeSlave.eyes is -1>>Nearsighted.
			<<else>>Normal.
			<</if>>
		<</if>>
	<</replace>>

	<<replace "#boobs">>
		<<if $activeSlave.boobs <= 200>>Flat.
		<<elseif $activeSlave.boobs <= 500>>Healthy.
		<<elseif $activeSlave.boobs <= 800>>Large.
		<<elseif $activeSlave.boobs <= 1200>>Very Large.
		<<elseif $activeSlave.boobs <= 2000>>Huge.
		<<elseif $activeSlave.boobs <= 4000>>Massive.
		<<elseif $activeSlave.boobs <= 6000>>Monstrous.
		<<else>>Science experiment.
		<</if>>
		<<textbox "$activeSlave.boobs" $activeSlave.boobs "Starting Girls">> CCs
	<</replace>>

	<<replace "#lactation">>
		<<if $activeSlave.lactation == 2>>Artificial.
		<<elseif $activeSlave.lactation == 1>>Natural.
		<<else>>None.
		<</if>>
	<</replace>>

	<<replace "#nipples">>
		$activeSlave.nipples
	<</replace>>

	<<replace "#areolae">>
		<<if $activeSlave.areolae == 1>>
		Large.
		<<elseif $activeSlave.areolae == 2>>
			Wide.
		<<elseif $activeSlave.areolae == 3>>
			Huge.
		<<else>>
			Normal.
		<</if>>
	<</replace>>

	<<replace "#shoulders">>
		<<if $activeSlave.shoulders < -1>>Very narrow.
		<<elseif $activeSlave.shoulders < 0>>Narrow.
		<<elseif $activeSlave.shoulders > 1>>Very broad.
		<<elseif $activeSlave.shoulders > 0>>Broad.
		<<else>>Feminine.
		<</if>>
	<</replace>>

	<<replace "#hips">>
		<<if $activeSlave.hips < -1>>Very narrow.
		<<elseif $activeSlave.hips < 0>>Narrow.
		<<elseif $activeSlave.hips > 1>>Very broad.
		<<elseif $activeSlave.hips > 0>>Broad.
		<<else>>Normal.
		<</if>>
	<</replace>>

	<<replace "#butt">>
		<<if $activeSlave.butt == 0>>Flat.
		<<elseif $activeSlave.butt < 2>>Small.
		<<elseif $activeSlave.butt < 3>>Plump.
		<<elseif $activeSlave.butt < 4>>Big.
		<<elseif $activeSlave.butt < 5>>Huge.
		<<elseif $activeSlave.butt < 6>>Enormous.
		<<elseif $activeSlave.butt < 7>>Gigantic.
		<<else>>Massive.
		<</if>>
	<</replace>>

	<<replace "#anus">>
		<<if $activeSlave.anus == 0>>@@color:lime;Virgin.@@
		<<elseif $activeSlave.anus == 1>>Normal.
		<<elseif $activeSlave.anus is 2>>Veteran.
		<<else>>Gaping.
		<</if>>
	<</replace>>

	<<replace "#vagina">>
		<<if $activeSlave.vagina is -1>>//No vagina.//
		<<elseif $activeSlave.vagina == 0>>@@color:lime;Virgin.@@
		<<elseif $activeSlave.vagina == 1>>Normal.
		<<elseif $activeSlave.vagina is 2>>Veteran.
		<<else>>Gaping.
		<</if>>
	<</replace>>

	<<replace "#vaginablock">>
		<<if $activeSlave.vagina > -1>>

		''Clit:''

			<<if $activeSlave.clit == 0>>Normal.
			<<elseif $activeSlave.clit == 1>>Large.
			<<else>>Huge.
			<</if>>

		<<click "Normal">>
			<<set $activeSlave.clit to 0>>
			<<replace #clit>>
				Normal.
			<</replace>>
		<</click>>
		|
		<<click "Large">>
			<<set $activeSlave.clit to 1>>
			<<replace #clit>>
				Large.
			<</replace>>
		<</click>>
		|
		<<click "Huge">>
			<<set $activeSlave.clit to 2>>
			<<replace #clit>>
				Huge.
			<</replace>>
		<</click>>
		<</if>>

		''Labia:''

			<<if $activeSlave.labia is 2>>Huge.
			<<elseif $activeSlave.labia == 1>>Large.
			<<else>>Normal.
			<</if>>

		<<click "Normal">>
			<<set $activeSlave.labia to 0>>
			<<replace #labia>>
				Normal.
			<</replace>>
		<</click>>
		|
		<<click "Large">>
			<<set $activeSlave.labia to 1>>
			<<replace #labia>>
				Large.
			<</replace>>
		<</click>>
		|
		<<click "Huge">>
			<<set $activeSlave.labia to 2>>
			<<replace #labia>>
				Huge.
			<</replace>>
		<</click>>

		''Vaginal wetness:''

		<<if $activeSlave.vaginaLube == 0>>Dry.
		<<elseif $activeSlave.vaginaLube == 1>>Normal.
		<<else>>Excessive.
		<</if>>

		<<click "Dry">><<set $activeSlave.vaginaLube = 0>><<replace "#wetness">>Dry.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Normal">><<set $activeSlave.vaginaLube = 1>><<replace "#wetness">>Normal.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Excessive">><<set $activeSlave.vaginaLube = 2>><<replace "#wetness">>Excessive.<</replace>><<StartingGirlsCost>><</click>>

		''Pregnancy:''

		<<if $activeSlave.preg > 20>>Ready to drop.
		<<elseif $activeSlave.preg > 20>>Advanced.
		<<elseif $activeSlave.preg > 5>>Early.
		<<elseif $activeSlave.preg > -2>>None.
		<<else>>Barren.
		<</if>>

		<<click "Ready to Drop">><<set $activeSlave.preg = 35,$activeSlave.pregType = 1,$activeSlave.pubertyXX = 1>><<replace "#preg">>Ready to drop.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Advanced">><<set $activeSlave.preg = 25,$activeSlave.pregType = 1,$activeSlave.pubertyXX = 1>><<replace "#preg">>Advanced.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Early">><<set $activeSlave.preg = 10,$activeSlave.pregType = 1,$activeSlave.pubertyXX = 1>><<replace "#preg">>Early.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "None">><<set $activeSlave.preg = 0,$activeSlave.pregType = 0,$activeSlave.pregSource = 0>><<replace "#preg">>None.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Barren">><<set $activeSlave.preg = -2,$activeSlave.pregType = 0,$activeSlave.pregSource = 0>><<replace "#preg">>Barren.<</replace>><<StartingGirlsCost>><</click>>

''Puberty:''

		<<if $activeSlave.pubertyXX == 1>>Postpubescent.
		<<else>>Prepubescent.
		<</if>>

		<<textbox "$activeSlave.pubertyAgeXX" $activeSlave.pubertyAgeXX "Starting Girls">>
		<<click "Postpubescent">><<set $activeSlave.pubertyXX = 1>><<replace "#pub">>Postpubescent.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Prepubescent">><<set $activeSlave.pubertyXX = 0,$activeSlave.pubertyAgeXX = $fertilityAge,$activeSlave.preg = 0,$activeSlave.pregType = 0,$activeSlave.pregSource = 0>><<replace "#pub">>Prepubescent.<</replace>><<StartingGirlsCost>><</click>>
		<<if $PC.dick == 1>>

 ''Father:''

		<<if $activeSlave.pregSource == -1>>My child.
		<<else>>
		<</if>>

		<<click "My child">><<set $activeSlave.pregSource = -1>><<replace "#father">>My child.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Clear">><<set $activeSlave.pregSource = 0>><<replace "#father">><</replace>><<StartingGirlsCost>><</click>>
		<</if>>
	<</replace>>

	<<replace "#dickblock">>
		<<if $seeDicks != 0>>

		''Penis:''

		<<if $activeSlave.dick == 0>>None.
		<<elseif $activeSlave.dick == 1>>Tiny.
		<<elseif $activeSlave.dick is 2>>Small.
		<<elseif $activeSlave.dick is 3>>Normal.
		<<elseif $activeSlave.dick is 4>>Large.
		<<else>>Massive.
		<</if>>

		<<click "No penis">><<set $activeSlave.dick = 0,$activeSlave.balls = 0,$activeSlave.clit = 0,$activeSlave.pubertyXY = 0,$activeSlave.pubertyAgeXY = $potencyAge>><<replace "#dick">>None.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Tiny">><<set $activeSlave.dick = 1,$activeSlave.clit = 0>><<replace "#dick">>Tiny.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Small">><<set $activeSlave.dick = 2,$activeSlave.clit = 0>><<replace "#dick">>Small.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Normal">><<set $activeSlave.dick = 3,$activeSlave.clit = 0>><<replace "#dick">>Normal.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Large">><<set $activeSlave.dick = 4,$activeSlave.clit = 0>><<replace "#dick">>Large.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Massive">><<set $activeSlave.dick = 5,$activeSlave.clit = 0>><<replace "#dick">>Massive.<</replace>><<StartingGirlsCost>><</click>>
		<<if $activeSlave.dick > 0>>

		''Foreskin:''

		<<if $activeSlave.foreskin == 0>>None.
		<<elseif $activeSlave.foreskin == 1>>Tiny.
		<<elseif $activeSlave.foreskin is 2>>Small.
		<<elseif $activeSlave.foreskin is 3>>Normal.
		<<elseif $activeSlave.foreskin is 4>>Large.
		<<else>>Massive.<</if>>

		<<if $seeCircumcision == 1>><<click "Circumcised">><<set $activeSlave.foreskin = 0>><<replace "#foreskin">>None.<</replace>><<StartingGirlsCost>><</click>> |<</if>>
		<<click "Tiny">><<set $activeSlave.foreskin = 1>><<replace "#foreskin">>Tiny.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Small">><<set $activeSlave.foreskin = 2>><<replace "#foreskin">>Small.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Normal">><<set $activeSlave.foreskin = 3>><<replace "#foreskin">>Normal.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Large">><<set $activeSlave.foreskin = 4>><<replace "#foreskin">>Large.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Massive">><<set $activeSlave.foreskin = 5>><<replace "#foreskin">>Massive.<</replace>><<StartingGirlsCost>><</click>>

		''Testicles:''

		<<if $activeSlave.balls == 0>>None.
		<<elseif $activeSlave.balls == 1>>Vestigial.
		<<elseif $activeSlave.balls is 2>>Small.
		<<elseif $activeSlave.balls is 3>>Normal.
		<<elseif $activeSlave.balls is 4>>Large.
		<<else>>Massive.<</if>>

		<<click "No testicles">><<set $activeSlave.balls = 0,$activeSlave.pubertyXY = 0,$activeSlave.pubertyAgeXY = $potencyAge>><<replace "#balls">>None.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Vestigial">><<set $activeSlave.balls = 1>><<replace "#balls">>Vestigial.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Small">><<set $activeSlave.balls = 2>><<replace "#balls">>Small.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Normal">><<set $activeSlave.balls = 3>><<replace "#balls">>Normal.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Large">><<set $activeSlave.balls = 4>><<replace "#balls">>Large.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Massive">><<set $activeSlave.balls = 5>><<replace "#balls">>Massive.<</replace>><<StartingGirlsCost>><</click>>

		''Puberty:''<<textbox "$activeSlave.pubertyAgeXY" $activeSlave.pubertyAgeXY "Starting Girls">>
		<<if $activeSlave.balls > 0>>

		''Ballsack:''

		<<if $activeSlave.scrotum == 0>>None.
		<<elseif $activeSlave.scrotum == 1>>Tiny.
		<<elseif $activeSlave.scrotum is 2>>Small.
		<<elseif $activeSlave.scrotum is 3>>Normal.
		<<elseif $activeSlave.scrotum is 4>>Large.
		<<else>>Massive.<</if>>

		<<click "None">><<set $activeSlave.scrotum = 0>><<replace "#scrotum">>None.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Tiny">><<set $activeSlave.scrotum = 1>><<replace "#scrotum">>Tiny.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Small">><<set $activeSlave.scrotum = 2>><<replace "#scrotum">>Small.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Normal">><<set $activeSlave.scrotum = 3>><<replace "#scrotum">>Normal.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Large">><<set $activeSlave.scrotum = 4>><<replace "#scrotum">>Large.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Massive">><<set $activeSlave.scrotum = 5>><<replace "#scrotum">>Massive.<</replace>><<StartingGirlsCost>><</click>>

''Puberty:''

		<<if $activeSlave.pubertyXY == 1>>Postpubescent.
		<<else>>Prepubescent.
		<</if>>

		<<click "Postpubescent">><<set $activeSlave.pubertyXY = 1>><<replace "#Mpub">>Postpubescent.<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Prepubescent">><<set $activeSlave.pubertyXY = 0,$activeSlave.pubertyAgeXY = $potencyAge>><<replace "#Mpub">>Prepubescent.<</replace>><<StartingGirlsCost>><</click>>
		<</if>>
		<</if>>
		<</if>>
	<</replace>>

	<<replace "#analSkillsBlock">>
		<<if $activeSlave.anus == 0>>
			//Anal virgins cannot be given anal skills//
		<<else>>
			''Anal sex:''

			<<if $activeSlave.analSkill <= 10>>Unskilled.
			<<elseif $activeSlave.analSkill <= 30>>@@color:cyan;Basic.@@
			<<elseif $activeSlave.analSkill <= 60>>@@color:cyan;Skilled.@@
			<<else>>@@color:cyan;Expert.@@
			<</if>>

			<<if $activeSlave.anus < 3>><<click "Unskilled">><<set $activeSlave.analSkill = 0>><<replace "#analSkill">>Unskilled.<</replace>><<StartingGirlsCost>><</click>> |<</if>>
			<<click "Basic">><<set $activeSlave.analSkill = 15>><<replace "#analSkill">>@@color:cyan;Basic.@@<</replace>><<StartingGirlsCost>><</click>> |
			<<click "Skilled">><<set $activeSlave.analSkill = 35>><<replace "#analSkill">>@@color:cyan;Skilled.@@<</replace>><<StartingGirlsCost>><</click>> |
			<<click "Expert">><<set $activeSlave.analSkill = 65>><<replace "#analSkill">>@@color:cyan;Expert.@@<</replace>><<StartingGirlsCost>><</click>>
		<</if>>
	<</replace>>

	<<replace "#oralSkill">>
		<<if $activeSlave.oralSkill <= 10>>Unskilled.
		<<elseif $activeSlave.oralSkill <= 30>>@@color:cyan;Basic.@@
		<<elseif $activeSlave.oralSkill <= 60>>@@color:cyan;Skilled.@@
		<<else>>@@color:cyan;Expert.@@
		<</if>>
	<</replace>>

	<<replace "#vaginalSkillsBlock">>
		<<if $activeSlave.vagina == 0>>
			//Virgins cannot be given vaginal skills//
		<<elseif $activeSlave.vagina is -1>>
			//Must have a vagina to have vaginal skills//
		<<else>>
			''Vaginal sex:''

			<<if $activeSlave.vaginalSkill <= 10>>Unskilled.
			<<elseif $activeSlave.vaginalSkill <= 30>>@@color:cyan;Basic.@@
			<<elseif $activeSlave.vaginalSkill <= 60>>@@color:cyan;Skilled.@@
			<<else>>@@color:cyan;Expert.@@
			<</if>>

			<<if $activeSlave.vagina < 3>><<click "Unskilled">><<set $activeSlave.vaginalSkill = 0>><<replace "#vaginalSkill">>Unskilled.<</replace>><<StartingGirlsCost>><</click>> |<</if>>
			<<click "Basic">><<set $activeSlave.vaginalSkill = 15>><<replace "#vaginalSkill">>@@color:cyan;Basic.@@<</replace>><<StartingGirlsCost>><</click>> |
			<<click "Skilled">><<set $activeSlave.vaginalSkill = 35>><<replace "#vaginalSkill">>@@color:cyan;Skilled.@@<</replace>><<StartingGirlsCost>><</click>> |
			<<click "Expert">><<set $activeSlave.vaginalSkill = 65>><<replace "#vaginalSkill">>@@color:cyan;Expert.@@<</replace>><<StartingGirlsCost>><</click>>
		<</if>>
	<</replace>>

	<<replace "#whoreSkill">>
		<<if $activeSlave.whoreSkill <= 10>>Unskilled.
		<<elseif $activeSlave.whoreSkill <= 30>>@@color:cyan;Basic.@@
		<<elseif $activeSlave.whoreSkill <= 60>>@@color:cyan;Skilled.@@
		<<else>>@@color:cyan;Expert.@@
		<</if>>
	<</replace>>

	<<replace "#entertainSkill">>
		<<if $activeSlave.entertainSkill <= 10>>Unskilled.
		<<elseif $activeSlave.entertainSkill <= 30>>@@color:cyan;Basic.@@
		<<elseif $activeSlave.entertainSkill <= 60>>@@color:cyan;Skilled.@@
		<<else>>@@color:cyan;Expert.@@
		<</if>>
	<</replace>>

	<<replace "#combatSkill">>
		<<if $activeSlave.combatSkill == 0>>Unskilled.
		<<else>>@@color:cyan;Skilled.@@
		<</if>>
	<</replace>>

	<<replace "#intelligence">>
		<<if $activeSlave.intelligence is 3>>@@color:deepskyblue;Brilliant.@@
		<<elseif $activeSlave.intelligence is 2>>@@color:deepskyblue;Very smart.@@
		<<elseif $activeSlave.intelligence == 1>>@@color:deepskyblue;Smart.@@
		<<elseif $activeSlave.intelligence == 0>>Average.
		<<elseif $activeSlave.intelligence is -1>>@@color:orangered;Stupid.@@
		<<elseif $activeSlave.intelligence is -2>>@@color:orangered;Very stupid.@@
		<<else>>@@color:orangered;Moronic.@@
		<</if>>
	<</replace>>

	<<replace "#intelligenceImplant">>
		<<if $activeSlave.intelligenceImplant == 1>>@@color:deepskyblue;Educated.@@
		<<else>>Uneducated.
		<</if>>
	<</replace>>

	<<if $activeSlave.fetishKnown == 1>>
		<<ToggleFetish 1>>
	<<else>>
		<<ToggleFetish 0>>
	<</if>>

	<<if $activeSlave.attrKnown == 1>>
		<<ToggleSexuality 1>>
	<<else>>
		<<ToggleSexuality 0>>
	<</if>>

	<<replace "#behavioralFlaw">>
		<<if $activeSlave.behavioralFlaw is "none">>
		//$activeSlave.behavioralFlaw.//
		<<else>>
			@@color:red;$activeSlave.behavioralFlaw.@@
		<</if>>
	<</replace>>

	<<replace "#sexualFlaw">>
		<<if $activeSlave.sexualFlaw is "none">>
			//$activeSlave.sexualFlaw.//
		<<else>>
			@@color:red;$activeSlave.sexualFlaw.@@
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<StartingGirlsAnalSkill>>
%/
<<widget "StartingGirlsAnalSkill">>
	<<replace "#analSkillsBlock">>
		<<if $activeSlave.anus == 0>>
		//Anal virgins cannot be given anal skills//
		<<else>>
		''Anal sex:''

		<<if $activeSlave.analSkill <= 10>>Unskilled.
		<<elseif $activeSlave.analSkill <= 30>>@@color:cyan;Basic.@@
		<<elseif $activeSlave.analSkill <= 60>>@@color:cyan;Skilled.@@
		<<else>>@@color:cyan;Expert.@@
		<</if>>

		<<if $activeSlave.anus < 3>><<click "Unskilled">><<set $activeSlave.analSkill = 0>><<replace "#analSkill">>Unskilled.<</replace>><<StartingGirlsCost>><</click>> |<</if>>
		<<click "Basic">><<set $activeSlave.analSkill = 15>><<replace "#analSkill">>@@color:cyan;Basic.@@<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Skilled">><<set $activeSlave.analSkill = 35>><<replace "#analSkill">>@@color:cyan;Skilled.@@<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Expert">><<set $activeSlave.analSkill = 65>><<replace "#analSkill">>@@color:cyan;Expert.@@<</replace>><<StartingGirlsCost>><</click>>
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<StartingGirlsVaginalSkill>>
%/
<<widget "StartingGirlsVaginalSkill">>
	<<replace "#vaginalSkillsBlock">>
		<<if $activeSlave.vagina == 0>>
		//Virgins cannot be given vaginal skills//
		<<elseif $activeSlave.vagina is -1>>
		//Must have a vagina to have vaginal skills//
		<<else>>
		''Vaginal sex:''

		<<if $activeSlave.vaginalSkill <= 10>>Unskilled.
		<<elseif $activeSlave.vaginalSkill <= 30>>@@color:cyan;Basic.@@
		<<elseif $activeSlave.vaginalSkill <= 60>>@@color:cyan;Skilled.@@
		<<else>>@@color:cyan;Expert.@@
		<</if>>

		<<if $activeSlave.anus < 3>><<click "Unskilled">><<set $activeSlave.vaginalSkill = 0>><<replace "#vaginalSkill">>Unskilled.<</replace>><<StartingGirlsCost>><</click>> |<</if>>
		<<click "Basic">><<set $activeSlave.vaginalSkill = 15>><<replace "#vaginalSkill">>@@color:cyan;Basic.@@<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Skilled">><<set $activeSlave.vaginalSkill = 35>><<replace "#vaginalSkill">>@@color:cyan;Skilled.@@<</replace>><<StartingGirlsCost>><</click>> |
		<<click "Expert">><<set $activeSlave.vaginalSkill = 65>><<replace "#vaginalSkill">>@@color:cyan;Expert.@@<</replace>><<StartingGirlsCost>><</click>>
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<SaleDescription>>
%/
<<widget "SaleDescription">>
	<<replace #slaveinfo>>
		<<set $saleDescription = 1>>
		<<display "Long Slave Description">>
		<<set $saleDescription = 0>>
	<</replace>>
<</widget>>

/%
 Call as <<StartingGirlsCost>>
%/
<<widget "StartingGirlsCost">>

<<replace "#cost">>
	<<slaveCost $activeSlave>>
	¤<<print $slaveCost>>.
<</replace>>
<<replace "#finalize">>
<<if $cash >= $slaveCost>>
	<<if $PC.career != "engineer">>

		<<click "Add this slave">>
			<<set $returnTo = "Commit Starting Girl", $createRelatedSlave = 0, $applyCareerBonus = 1, $careerBonusApplied = 0>>
			<<set $activeSlave.actualAge to Number($activeSlave.actualAge)>>
			<<set $activeSlave.devotion = Number($activeSlave.devotion)>>
			<<set $activeSlave.trust = Number($activeSlave.trust)>>
			<<if $activeSlave.indenture >= 0>>
				<<set $activeSlave.indenture = Math.clamp($activeSlave.indenture, 26, 208)>>
			<</if>>
			<<set $activeSlave.height = Math.clamp($activeSlave.height, 85, 274)>>
			<<set $activeSlave.boobs = Math.clamp($activeSlave.boobs, 0, 10000)>>
			<<set $activeSlave.boobs = Number($activeSlave.boobs)>>
			<<set $activeSlave.boobs = Math.trunc($activeSlave.boobs/50)*50>>
			<<set $slaveWithoutBonuses = $activeSlave>>
			<<goto "RG AS Dump">>
		<</click>>
		//This will apply your @@color:springgreen;career bonus@@ to her:
		<<if $PC.career is "capitalist">>
			one free level of @@color:cyan;prostitution skill.@@
		<<elseif $PC.career is "mercenary">>
			@@color:mediumaquamarine;+2 trust.@@
		<<elseif $PC.career is "slaver">>
			@@color:hotpink;+2 devotion.@@
		<<elseif $PC.career is "medicine">>
			free @@color:lime;basic implants.@@
		<<elseif $PC.career is "celebrity">>
			one free level of @@color:cyan;entertainment skill.@@
		<<elseif $PC.career is "gang">>
			@@color:green;+5 health@@ and a free level of @@color:cyan;combat skill@@
		<<elseif $PC.career is "escort">>
			two free levels of @@color:cyan;sex skills@@, one free level of @@color:cyan;prostitution skill@@, and one free level of @@color:cyan;entertainment skill.@@
		<<elseif $PC.career is "servant">>
			@@color:mediumaquamarine;+1 trust@@ and @@color:hotpink;+1 devotion.@@
		<<else>>
			two free levels of @@color:cyan;sex skills.@@
		<</if>>//

		<<click "Add slave without career bonus">>
			<<set $returnTo = "Commit Starting Girl", $createRelatedSlave = 0, $applyCareerBonus = 0, $careerBonusApplied = 0>>
			<<set $activeSlave.actualAge to Number($activeSlave.actualAge)>>
			<<set $activeSlave.devotion = Number($activeSlave.devotion)>>
			<<set $activeSlave.trust = Number($activeSlave.trust)>>
			<<if $activeSlave.indenture >= 0>>
				<<set $activeSlave.indenture = Math.clamp($activeSlave.indenture, 26, 208)>>
			<</if>>
			<<set $activeSlave.height = Math.clamp($activeSlave.height, 85, 274)>>
			<<set $activeSlave.boobs = Math.clamp($activeSlave.boobs, 0, 10000)>>
			<<set $activeSlave.boobs = Number($activeSlave.boobs)>>
			<<set $activeSlave.boobs = Math.trunc($activeSlave.boobs/50)*50>>
			<<set $slaveWithoutBonuses = $activeSlave>>
			<<goto "RG AS Dump">>
		<</click>>
	<<else>>

		<<click "Add slave">>
			<<set $returnTo = "Commit Starting Girl", $createRelatedSlave = 0, $applyCareerBonus = 0, $careerBonusApplied = 0>>
			<<set $activeSlave.actualAge to Number($activeSlave.actualAge)>>
			<<set $activeSlave.devotion = Number($activeSlave.devotion)>>
			<<set $activeSlave.trust = Number($activeSlave.trust)>>
			<<if $activeSlave.indenture >= 0>>
				<<set $activeSlave.indenture = Math.clamp($activeSlave.indenture, 26, 208)>>
			<</if>>
			<<set $activeSlave.height = Math.clamp($activeSlave.height, 85, 274)>>
			<<set $activeSlave.boobs = Math.clamp($activeSlave.boobs, 0, 10000)>>
			<<set $activeSlave.boobs = Number($activeSlave.boobs)>>
			<<set $activeSlave.boobs = Math.trunc($activeSlave.boobs/50)*50>>
			<<set $slaveWithoutBonuses = $activeSlave>>
			<<goto "RG AS Dump">>
		<</click>>

	<</if>>
<<else>>
	//You lack the necessary funds to add this slave.//
<</if>>

    [[Discard this slave and continue to the arcology|Acquisition]]
<</replace>>
<</widget>>

/%
 Call as <<ToggleFetish 1>>
 $arg[0] is whether unknown or known.
%/
<<widget "ToggleFetish">>

<<if ($args[0] == 0)>>
	<<set $activeSlave.fetish = either("none", "none", "none", "none", "none", "none", "none", "none", "none", "none", "submissive", "cumslut", "humiliation", "buttslut", "boobs", "pregnancy", "dom", "sadist", "masochist"), $activeSlave.fetishKnown = 0>>
	<<replace "#fetishblock">>
		//Not known.//
		<<click "Known">>
			<<ToggleFetish 1>>
		<</click>>
	<</replace>>
<<else>>
	<<set $activeSlave.fetishKnown = 1>>
		<<replace "#fetishblock">>

		<<if $activeSlave.fetishKnown == 1>>
			<<if $activeSlave.fetish is "none">>
				@@color:pink;$activeSlave.fetish.@@
			<<else>>
				@@color:lightcoral;$activeSlave.fetish.@@
			<</if>>
		<<else>>
			//Not known.//
			<<click "Known">>
				<<ToggleFetish 1>>
			<</click>>
		<</if>>

		<<if $activeSlave.fetishKnown == 1>>
			<<click "Unknown">>
				<<ToggleFetish 0>>
			<<StartingGirlsCost>>
		<</click>> |
		<<click "None">>
			<<set $activeSlave.fetish = "none", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Sub">>
			<<set $activeSlave.fetish = "submissive", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Dom">>
			<<set $activeSlave.fetish = "dom", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Cumslut">>
			<<set $activeSlave.fetish = "cumslut", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Humiliation">>
			<<set $activeSlave.fetish = "humiliation", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Buttslut">>
			<<set $activeSlave.fetish = "buttslut", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Breasts">>
			<<set $activeSlave.fetish = "boobs", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Pregnancy">>
			<<set $activeSlave.fetish = "pregnancy", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Sadism">>
			<<set $activeSlave.fetish = "sadist", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>> |
		<<click "Masochism">>
			<<set $activeSlave.fetish = "masochist", $activeSlave.fetishKnown = 1>>
			<<ToggleFetish 1>>
		<</click>>

		<<if $activeSlave.fetish != "none">>

			''Fetish strength:''
			<<if $activeSlave.fetishStrength > 95>>
				@@color:lightcoral;High.@@
			<<elseif $activeSlave.fetishStrength <= 60>>
				@@color:pink;Low.@@
			<<else>>
				@@color:hotpink;Normal.@@
			<</if>>
			<<if $activeSlave.fetishStrength > 60>>
				<<click "Decrease">>
					<<ChangeFetishStrength 0>>
				<</click>>
			<</if>>
			<<if ($activeSlave.fetishStrength > 60)>>|<</if>>
			<<if $activeSlave.fetishStrength <= 95>>
				<<click "Increase">>
					<<ChangeFetishStrength 1>>
				<</click>>
			<</if>>

	<</if>>

	<</if>>
	<</replace>>
<</if>>

<</widget>>

/%
 Call as <<ChangeFetishStrength 1>>
 $arg[0] is whether increase or decreas
%/
<<widget "ChangeFetishStrength">>

<<if ($args[0] == 0)>>
	<<set $activeSlave.fetishStrength -= 5, $activeSlave.fetishKnown = 1>>
	<<replace "#fetishStrength">>
		''Fetish strength:''
		<<if $activeSlave.fetishStrength > 95>>
			@@color:lightcoral;High.@@
		<<elseif $activeSlave.fetishStrength <= 60>>
			@@color:pink;Low.@@
		<<else>>
			@@color:hotpink;Normal.@@
		<</if>>

		<<if $activeSlave.fetishStrength > 60>>
			<<click "Decrease">>
				<<ChangeFetishStrength 0>>
			<</click>>
		<</if>>
		<<if ($activeSlave.fetishStrength > 60)>>|<</if>>
		<<if $activeSlave.fetishStrength <= 95>>
			<<click "Increase">>
				<<ChangeFetishStrength 1>>
			<</click>>
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>

<<else>>
	<<set $activeSlave.fetishStrength += 5, $activeSlave.fetishKnown = 1>>
	<<replace "#fetishStrength">>
		''Fetish strength:''
		<<if $activeSlave.fetishStrength > 95>>
			@@color:lightcoral;High.@@
		<<elseif $activeSlave.fetishStrength <= 60>>
			@@color:pink;Low.@@
		<<else>>
			@@color:hotpink;Normal.@@
		<</if>>

		<<if $activeSlave.fetishStrength > 60>>
			<<click "Decrease">>
				<<ChangeFetishStrength 0>>
			<</click>>
		<</if>>
		<<if ($activeSlave.fetishStrength > 60)>>|<</if>>
		<<if $activeSlave.fetishStrength <= 95>>
			<<click "Increase">>
				<<ChangeFetishStrength 1>>
			<</click>>
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>

<</if>>

<</widget>>

/%
 Call as <<ToggleSexuality 1>>
 $arg[0] is whether unknown or known.
%/
<<widget "ToggleSexuality">>

<<if ($args[0] == 0)>>

	<<set $activeSlave.attrXX = random(0,100), $activeSlave.attrXY = random(0,100), $activeSlave.energy = random(1,90), $activeSlave.attrKnown = 0>>
	<<StartingGirlsCost>>
	<<replace "#sexuality">>
		//Not known.//

	<<click "Known">>
		<<ToggleSexuality 1>>
	<</click>>
	<</replace>>
<<else>>
	<<set $activeSlave.attrKnown = 1>>
	<<replace "#sexuality">>

	<<if $activeSlave.attrKnown == 1>>
		<<if $activeSlave.attrXY <= 5>>
			@@color:red;Disgusted by men,@@
		<<elseif $activeSlave.attrXY <= 15>>
			@@color:red;Turned off by men,@@
		<<elseif $activeSlave.attrXY <= 35>>
			@@color:red;Not attracted to men,@@
		<<elseif $activeSlave.attrXY <= 65>>
			Indifferent to men,
		<<elseif $activeSlave.attrXY <= 85>>
			@@color:green;Attracted to men,@@
		<<elseif $activeSlave.attrXY <= 95>>
			@@color:green;Aroused by men,@@
		<<else>>
			@@color:green;Passionate about men,@@
		<</if>>
	<<else>>
		//Not known.//
	<</if>>

	<<if $activeSlave.attrKnown == 1>>
		<<if $activeSlave.attrXX <= 5>>
			@@color:red;disgusted by women.@@
		<<elseif $activeSlave.attrXX <= 15>>
			@@color:red;turned off by women.@@
		<<elseif $activeSlave.attrXX <= 35>>
			@@color:red;not attracted to women.@@
		<<elseif $activeSlave.attrXX <= 65>>
			indifferent to women.
		<<elseif $activeSlave.attrXX <= 85>>
			@@color:green;attracted to women.@@
		<<elseif $activeSlave.attrXX <= 95>>
			@@color:green;aroused by women.@@
		<<else>>
			@@color:green;passionate about women.@@
		<</if>>
	<</if>>

	<<if $activeSlave.attrKnown == 1>>
	<<click "Unknown">>
		<<ToggleSexuality 0>>
	<</click>>

	XY attraction:

		<<click "Decrease">>
		<<ChangeAttr 1 0>>
		<</click>>

	|
		<<click "Increase">>
		<<ChangeAttr 1 1>>
		<</click>>

	XX attraction:

		<<click "Decrease">>
		<<ChangeAttr 0 0>>
		<</click>>

	|
		<<click "Increase">>
		<<ChangeAttr 0 1>>
		<</click>>

	''Sex drive:''

		<<if $activeSlave.energy == 100>>@@color:green;Nympho!@@
		<<elseif $activeSlave.energy > 80>>@@color:green;Sex addict.@@
		<<elseif $activeSlave.energy > 60>>@@color:green;Powerful.@@
		<<elseif $activeSlave.energy > 40>>@@color:yellow;Average.@@
		<<elseif $activeSlave.energy > 20>>@@color:red;Poor.@@
		<<else>>@@color:red;Frigid.@@<</if>>

	<<click "Nympho">>
		<<set $activeSlave.energy = 100, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:green;Nympho!@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	| <<click "Sex addict">>
		<<set $activeSlave.energy = 85, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:green;Sex addict.@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	| <<click "Powerful">>
		<<set $activeSlave.energy = 65, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:green;Powerful.@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	| <<click "Average">>
		<<set $activeSlave.energy = 45, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:yellow;Average.@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	| <<click "Poor">>
		<<set $activeSlave.energy = 25, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:red;Poor.@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	| <<click "Frigid">>
		<<set $activeSlave.energy = 5, $activeSlave.attrKnown = 1>>
		<<replace "#energy">>
			@@color:red;Frigid.@@
		<</replace>>
		<<StartingGirlsCost>>
	<</click>>
	<<else>>
		<<click "Known">>
			<<ToggleSexuality 1>>
		</click>>
	<</if>>
	<</replace>>
	<<StartingGirlsCost>>
<</if>>
<</widget>>

/%
 Call as <<ChangeAttr 1 1>>
 $arg[0] is whether XX or XY.
 $arg[1] is whether increase or decrease.
%/
<<widget "ChangeAttr">>

<<if ($args[0] == 0) && ($args[1] == 0)>>
	<<if $activeSlave.attrXX-10 >= 0>>
		<<set $activeSlave.attrXX -= 10>>
	<<else>>
		<<set $activeSlave.attrXX = 0>>
	<</if>>
	<<set $activeSlave.attrXX == Math.clamp($activeSlave.attrXX, 0, 100)>>
	<<set $activeSlave.attrKnown = 1>>
	<<replace "#attrXX">>
		<<if $activeSlave.attrXX <= 5>>
			@@color:red;disgusted by women.@@
		<<elseif $activeSlave.attrXX <= 15>>
			@@color:red;turned off by women.@@
		<<elseif $activeSlave.attrXX <= 35>>
			@@color:red;not attracted to women.@@
		<<elseif $activeSlave.attrXX <= 65>>
			indifferent to women.
		<<elseif $activeSlave.attrXX <= 85>>
			@@color:green;attracted to women.@@
		<<elseif $activeSlave.attrXX <= 95>>
			@@color:green;aroused by women.@@
		<<else>>
			@@color:green;passionate about women.@@
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>
	<<if $activeSlave.attrXX == 100>>
		<<replace "#increaseXX">>
		<</replace>>
		<<replace "#decreaseXX">>
			<<click "Decrease">>
			<<ChangeAttr 0 0>>
			<</click>>
		<</replace>>
	<<elseif $activeSlave.attrXX == 0>>
		<<replace "#decreaseXX">>

		<</replace>>
		<<replace "#increaseXX">>
			<<click "Increase">>
			<<ChangeAttr 0 1>>
			<</click>>
		<</replace>>
	<<else>>
		<<replace "#decreaseXX">>
			<<click "Decrease">>
			<<ChangeAttr 0 0>>
			<</click>>
		<</replace>>
		<<replace "#increaseXX">>
		|
			<<click "Increase">>
			<<ChangeAttr 0 1>>
			<</click>>
		<</replace>>
	<</if>>
<<elseif ($args[0] == 0) && ($args[1] == 1)>>
	<<if $activeSlave.attrXX+10 <= 100>>
		<<set $activeSlave.attrXX += 10>>
	<<else>>
		<<set $activeSlave.attrXX = 100>>
	<</if>>
	<<set $activeSlave.attrXX == Math.clamp(0, 100)>>
	<<set $activeSlave.attrKnown = 1>>
	<<replace "#attrXX">>
		<<if $activeSlave.attrXX <= 5>>
			@@color:red;disgusted by women.@@
		<<elseif $activeSlave.attrXX <= 15>>
			@@color:red;turned off by women.@@
		<<elseif $activeSlave.attrXX <= 35>>
			@@color:red;not attracted to women.@@
		<<elseif $activeSlave.attrXX <= 65>>
			indifferent to women.
		<<elseif $activeSlave.attrXX <= 85>>
			@@color:green;attracted to women.@@
		<<elseif $activeSlave.attrXX <= 95>>
			@@color:green;aroused by women.@@
		<<else>>
			@@color:green;passionate about women.@@
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>
<<if $activeSlave.attrXX == 100>>
	<<replace "#increaseXX">>
	<</replace>>
	<<replace "#decreaseXX">>
		<<click "Decrease">>
		<<ChangeAttr 0 0>>
		<</click>>
	<</replace>>
<<elseif $activeSlave.attrXX == 0>>
	<<replace "#decreaseXX">>

	<</replace>>
	<<replace "#increaseXX">>
		<<click "Increase">>
		<<ChangeAttr 0 1>>
		<</click>>
	<</replace>>
<<else>>
	<<replace "#decreaseXX">>
		<<click "Decrease">>
		<<ChangeAttr 0 0>>
		<</click>>
	<</replace>>
	<<replace "#increaseXX">>
	|
		<<click "Increase">>
		<<ChangeAttr 0 1>>
		<</click>>
	<</replace>>
<</if>>
<<elseif ($args[0] == 1) && ($args[1] == 0)>>
	<<if $activeSlave.attrXY-10 >= 0>>
		<<set $activeSlave.attrXY -= 10>>
	<<else>>
		<<set $activeSlave.attrXY = 0>>
	<</if>>

	<<set $activeSlave.attrXY == Math.clamp(0, 100)>>
	<<set $activeSlave.attrKnown = 1>>
	<<replace "#attrXY">>
		<<if $activeSlave.attrXY <= 5>>
			@@color:red;Disgusted by men,@@
		<<elseif $activeSlave.attrXY <= 15>>
			@@color:red;Turned off by men,@@
		<<elseif $activeSlave.attrXY <= 35>>
			@@color:red;Not attracted to men,@@
		<<elseif $activeSlave.attrXY <= 65>>
			Indifferent to men,
		<<elseif $activeSlave.attrXY <= 85>>
			@@color:green;Attracted to men,@@
		<<elseif $activeSlave.attrXY <= 95>>
			@@color:green;Aroused by men,@@
		<<else>>
			@@color:green;Passionate about men,@@
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>
	<<if $activeSlave.attrXY == 100>>
		<<replace "#increaseXY">>

		<</replace>>
		<<replace "#decreaseXY">>
			<<click "Decrease">>
				<<ChangeAttr 1 0>>
			<</click>>
		<</replace>>
	<<elseif $activeSlave.attrXY == 0>>
		<<replace "#decreaseXY">>

		<</replace>>
		<<replace "#increaseXY">>
			<<click "Increase">>
				<<ChangeAttr 1 1>>
			<</click>>
		<</replace>>
	<<else>>
		<<replace "#decreaseXY">>
			<<click "Decrease">>
				<<ChangeAttr 1 0>>
			<</click>>
		<</replace>>
		<<replace "#increaseXY">>
		|
			<<click "Increase">>
				<<ChangeAttr 1 1>>
			<</click>>
		<</replace>>
	<</if>>
<<elseif ($args[0] == 1) && ($args[1] == 1)>>
	<<if $activeSlave.attrXY+10 <= 100>>
		<<set $activeSlave.attrXY += 10>>
	<<else>>
		<<set $activeSlave.attrXY = 100>>
	<</if>>
	<<set $activeSlave.attrXY == Math.clamp(0, 100)>>
	<<set $activeSlave.attrKnown = 1>>
	<<replace "#attrXY">>
		<<if $activeSlave.attrXY <= 5>>
			@@color:red;Disgusted by men,@@
		<<elseif $activeSlave.attrXY <= 15>>
			@@color:red;Turned off by men,@@
		<<elseif $activeSlave.attrXY <= 35>>
			@@color:red;Not attracted to men,@@
		<<elseif $activeSlave.attrXY <= 65>>
			Indifferent to men,
		<<elseif $activeSlave.attrXY <= 85>>
			@@color:green;Attracted to men,@@
		<<elseif $activeSlave.attrXY <= 95>>
			@@color:green;Aroused by men,@@
		<<else>>
			@@color:green;Passionate about men,@@
		<</if>>
	<</replace>>
	<<StartingGirlsCost>>

	<<if $activeSlave.attrXY == 100>>
		<<replace "#increaseXY">>

		<</replace>>
		<<replace "#decreaseXY">>
			<<click "Decrease">>
			<<ChangeAttr 1 0>>
			<</click>>
		<</replace>>
	<<elseif $activeSlave.attrXY == 0>>
		<<replace "#decreaseXY">>

		<</replace>>
		<<replace "#increaseXY">>
			<<click "Increase">>
			<<ChangeAttr 1 1>>
			<</click>>
		<</replace>>
	<<else>>
		<<replace "#decreaseXY">>
			<<click "Decrease">>
			<<ChangeAttr 1 0>>
			<</click>>
		<</replace>>
		<<replace "#increaseXY">>
		|
			<<click "Increase">>
			<<ChangeAttr 1 1>>
			<</click>>
		<</replace>>
	<</if>>
<</if>>
<</widget>>

/%
 Call as <<RandomizeAttraction>>
%/
<<widget "RandomizeAttraction">>

<<set _attraction = Math.clamp($activeSlave.energy*2, 60, 180), _sexuality = random(0,100)>>
<<if $activeSlave.balls > 0>>
	<<if _sexuality > 90>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction, 0, 100)>>
		<<set _attraction -= $activeSlave.attrXY>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction, 0, 100)>>
	<<elseif _sexuality > 70>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction+random(-5,5), 0, 100)>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction+random(-5,5), 0, 100)>>
	<<else>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction, 0, 100)>>
		<<set _attraction -= $activeSlave.attrXX>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction, 0, 100)>>
	<</if>>
<<else>>
	<<if _sexuality > 90>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction, 0, 100)>>
		<<set _attraction -= $activeSlave.attrXX>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction, 0, 100)>>
	<<elseif _sexuality > 60>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction+random(-5,5), 0, 100)>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction+random(-5,5), 0, 100)>>
	<<else>>
		<<set $activeSlave.attrXY = Math.clamp(_attraction, 0, 100)>>
		<<set _attraction -= $activeSlave.attrXY>>
		<<set $activeSlave.attrXX = Math.clamp(_attraction, 0, 100)>>
	<</if>>
<</if>>
<<set $activeSlave.attrXX = Math.clamp($activeSlave.attrXX+random(-5,5), 0, 100), $activeSlave.attrXY = Math.clamp($activeSlave.attrXY+random(-5,5), 0, 100)>>

<</widget>>

/%
 Call as <<CustomSlaveAge>>
%/
<<widget "CustomSlaveAge">>
	<<replace #age>>
		<<if $customSlave.actualAge < 5>>3-4 years old.
		<<elseif $customSlave.actualAge < 7>>5-6 years old.
		<<elseif $customSlave.actualAge < 10>>7-9 years old.
		<<elseif $customSlave.actualAge < 13>>10-12 years old.
		<<elseif $customSlave.actualAge < 15>>13-14 years old.
		<<elseif $customSlave.actualAge < 18>>15-17 years old.
		<<elseif $customSlave.actualAge < 20>>18-19 years old.
		<<elseif $customSlave.actualAge < 30>>20-29 years old.
		<<elseif $customSlave.actualAge < 40>>30-39 years old.
		<<else>>40+ years old.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveHealth>>
%/
<<widget "CustomSlaveHealth">>
	<<replace #health>>
		<<if $customSlave.health == 0>>Healthy.
		<<else>>Extremely healthy.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveMuscles>>
%/
<<widget "CustomSlaveMuscles">>
	<<replace #muscles>>
		<<if $customSlave.muscles <= 5>>Normal musculature.
		<<elseif $customSlave.muscles <= 30>>Toned.
		<<else>>Ripped.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveLips>>
%/
<<widget "CustomSlaveLips">>
	<<replace #lips>>
		<<if $customSlave.lips <= 10>>Thin lips.
		<<elseif $customSlave.lips <= 20>>Normal lips.
		<<elseif $customSlave.lips <= 40>>Plush lips.
		<<elseif $customSlave.lips <= 70>>Big lips.
		<<elseif $customSlave.lips <= 95>>Huge lips.
		<<else>>Facepussy.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveHeight>>
%/
<<widget "CustomSlaveHeight">>
	<<replace #height>>
		<<if $customSlave.height < 130>>Tiny.
		<<elseif $customSlave.height < 150>>Petite.
		<<elseif $customSlave.height < 160>>Short.
		<<elseif $customSlave.height < 170>>Average height.
		<<elseif $customSlave.height < 185>>Tall.
		<<else>>Very tall.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveFace>>
%/
<<widget "CustomSlaveFace">>
	<<replace #face>>
		<<if $customSlave.face < -1>>Very unattractive face.
		<<elseif $customSlave.face is -1>>Unattractive face.
		<<elseif $customSlave.face == 0>>Average face.
		<<elseif $customSlave.face == 1>>Attractive face.
		<<elseif $customSlave.face > 1>>Very attractive face.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveRace>>
%/
<<widget "CustomSlaveRace">>
	<<replace #ethnicity>>
		<<textbox "$customSlave.race" $customSlave.race "Custom Slave">>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveSkin>>
%/
<<widget "CustomSlaveSkin">>
	<<replace #skin>>
		<<textbox "$customSlave.skin" $customSlave.skin "Custom Slave">>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveBoobs>>
%/
<<widget "CustomSlaveBoobs">>
	<<replace #boobs>>
		<<if $customSlave.boobs is 200>>Flat chest.
		<<elseif $customSlave.boobs <= 500>>Healthy breasts.
		<<else>>Big breasts.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveButt>>
%/
<<widget "CustomSlaveButt">>
	<<replace #butt>>
		<<if $customSlave.butt == 1>>Flat buttocks.
		<<elseif $customSlave.butt < 4>>Healthy buttocks.
		<<else>>Huge buttocks.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveVagina>>
%/
<<widget "CustomSlaveVagina">>
	<<replace #vagina>>
		<<if $customSlave.vagina is -1>>No vagina.
		<<elseif $customSlave.vagina == 0>>Vaginal virgin.
		<<else>>Normal vagina.
		<</if>>
		<<if $customSlave.dick > 0>>
		<<click "No vagina">>
			<<set $customSlave.vagina to -1, $customSlave.preg to -2, $customSlave.ovaries to 0>>
			<<CustomSlaveVagina>>
		<</click>>
		<<else>>//No vagina//
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveDick>>
%/
<<widget "CustomSlaveDick">>
	<<replace #dick>>
		<<if $customSlave.dick == 0>>No penis.
		<<elseif $customSlave.dick is 2>>Small penis.
		<<else>>Large penis.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveClitBalls>>
%/
<<widget "CustomSlaveClitBalls">>
	<<replace #clitballs>>
	<<if $customSlave.dick > 0>>
	<<if $customSlave.balls == 0>>No testicles.<<elseif $customSlave.balls is 3>>Small testicles.<<else>>Large testicles.<</if>>
	<<click "No testicles">>
		<<set $customSlave.balls to 0,$customSlave.clit to 0>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Small testicles">>
		<<set $customSlave.balls to 2,$customSlave.clit to 0>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Large testicles">>
		<<set $customSlave.balls to 4,$customSlave.clit to 0>>
		<<CustomSlaveClitBalls>>
	<</click>>
	<<else>>
	<<if $customSlave.clit == 0>>Normal clitoris.<<elseif $customSlave.clit == 0>>Big clitoris.<<else>>Enormous clitoris.<</if>>
	<<click "Normal clitoris">>
		<<set $customSlave.clit to 0>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Big clitoris">>
		<<set $customSlave.clit to 1>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Enormous clitoris">>
		<<set $customSlave.clit to 2>>
		<<CustomSlaveClitBalls>>
	<</click>>

	<<if $customSlave.labia == 0>>Minimal labia.<<elseif $customSlave.labia == 1>>Normal labia.<<elseif $customSlave.labia is 2>>Huge labia.<<else>>Enormous labia.<</if>>
	<<click "Minimal labia">>
		<<set $customSlave.labia to 0>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Normal labia">>
		<<set $customSlave.labia to 1>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Huge labia">>
		<<set $customSlave.labia to 2>>
		<<CustomSlaveClitBalls>>
	<</click>>
	|
	<<click "Enormous labia">>
		<<set $customSlave.labia to 3>>
		<<CustomSlaveClitBalls>>
	<</click>>
	<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveAnus>>
%/
<<widget "CustomSlaveAnus">>
	<<replace #anus>>
		<<if $customSlave.anus == 0>>Anal virgin.
		<<else>>Normal anus.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveSkills>>
%/
<<widget "CustomSlaveSkills">>
	<<replace #skills>>
		<<if $customSlave.analSkill <= 10>>Sexually unskilled.
		<<elseif $customSlave.analSkill <= 30>>Basic skills..
		<<elseif $customSlave.analSkill <= 60>>Sexually skilled.
		<<else>>Sexual expert.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveWhoreSkills>>
%/
<<widget "CustomSlaveWhoreSkills">>
	<<replace #whoreskills>>
		<<if $customSlave.whoreSkill <= 10>>Unskilled at prostitution and entertainment.
		<<elseif $customSlave.whoreSkill <= 30>>Basic prostitution and entertainment skills.
		<<elseif $customSlave.whoreSkill <= 60>>Skilled at prostitution and entertainment.
		<<else>>Prostitution and entertainment expert.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveCombatSkills>>
%/
<<widget "CustomSlaveCombatSkills">>
	<<replace #combatskills>>
		<<if $customSlave.combatSkill == 0>>Unskilled at combat.
		<<else>>Skilled at combat.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveIntelligence>>
%/
<<widget "CustomSlaveIntelligence">>
	<<replace #intelligence>>
		<<if $customSlave.intelligence >= 3>>Brilliant.
		<<elseif $customSlave.intelligence is 2>>Very smart..
		<<elseif $customSlave.intelligence == 1>>Smart.
		<<elseif $customSlave.intelligence == 0>>Average intelligence.
		<<elseif $customSlave.intelligence is -1>>Stupid.
		<<elseif $customSlave.intelligence is -2>>Very stupid.
		<<else>>Moronic.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveEducation>>
%/
<<widget "CustomSlaveEducation">>
	<<replace #education>>
		<<if $customSlave.intelligenceImplant == 1>>Educated.
		<<else>>Uneducated.
		<</if>>
	<</replace>>
<</widget>>

/%
 Call as <<CustomSlaveNationality>>
%/
<<widget "CustomSlaveNationality">>
	<<replace #nationality>>
		Nationality: $customSlave.nationality.
	<</replace>>
<</widget>>

repo_name: ThreadAnon/fc


code:
# To customize your server, make a copy of this file to `.env` and edit any
# values you want to change. Be sure to remove the `#` at the beginning of each
# line you want to modify.

# All values have reasonable defaults, so you only need to change the ones you
# want to override.

# ------------------------------------------------------------------------------
# General settings:

# The title displayed on the info page.
# SERVER_TITLE=Coom Tunnel

# Model requests allowed per minute per user.
# MODEL_RATE_LIMIT=4

# Max number of output tokens a user can request at once.
# MAX_OUTPUT_TOKENS_OPENAI=300
# MAX_OUTPUT_TOKENS_ANTHROPIC=400

# Whether to show the estimated cost of consumed tokens on the info page.
# SHOW_TOKEN_COSTS=false

# Whether to automatically check API keys for validity.
# Note: CHECK_KEYS is disabled by default in local development mode, but enabled
# by default in production mode.
# CHECK_KEYS=true

# Which model types users are allowed to access.
# ALLOWED_MODEL_FAMILIES=claude,turbo,gpt4,gpt4-32k

# URLs from which requests will be blocked.
# BLOCKED_ORIGINS=reddit.com,9gag.com
# Message to show when requests are blocked.
# BLOCK_MESSAGE="You must be over the age of majority in your country to use this service."
# Destination to redirect blocked requests to.
# BLOCK_REDIRECT="https://roblox.com/"

# Whether to reject requests containing disallowed content.
# REJECT_DISALLOWED=false
# Message to show when requests are rejected.
# REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy."

# Whether prompts should be logged to Google Sheets.
# Requires additional setup. See `docs/google-sheets.md` for more information.
# PROMPT_LOGGING=false

# The port to listen on.
# PORT=7860

# Detail level of logging. (trace | debug | info | warn | error)
# LOG_LEVEL=info

# ------------------------------------------------------------------------------
# Optional settings for user management, access control, and quota enforcement:
# See `docs/user-management.md` for more information and setup instructions.
# See `docs/user-quotas.md` to learn how to set up quotas.

# Which access control method to use. (none | proxy_token | user_token)
# GATEKEEPER=none
# Which persistence method to use. (memory | firebase_rtdb)
# GATEKEEPER_STORE=memory

# Maximum number of unique IPs a user can connect from. (0 for unlimited)
# MAX_IPS_PER_USER=0

# With user_token gatekeeper, whether to allow users to change their nickname.
# ALLOW_NICKNAME_CHANGES=true

# Default token quotas for each model family. (0 for unlimited)
# TOKEN_QUOTA_TURBO=0
# TOKEN_QUOTA_GPT4=0
# TOKEN_QUOTA_GPT4_32K=0
# TOKEN_QUOTA_CLAUDE=0

# How often to refresh token quotas. (hourly | daily)
# Leave unset to never automatically refresh quotas.
# QUOTA_REFRESH_PERIOD=daily

# ------------------------------------------------------------------------------
# Secrets and keys:
# Do not put any passwords or API keys directly in this file.
# For Huggingface, set them via the Secrets section in your Space's config UI.
# For Render, create a "secret file" called .env using the Environment tab.

# You can add multiple API keys by separating them with a comma.
OPENAI_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ANTHROPIC_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# With proxy_key gatekeeper, the password users must provide to access the API.
# PROXY_KEY=your-secret-key

# With user_token gatekeeper, the admin password used to manage users.
# ADMIN_KEY=your-very-secret-key

# With firebase_rtdb gatekeeper storage, the Firebase project credentials.
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# FIREBASE_RTDB_URL=https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.firebaseio.com

# With prompt logging, the Google Sheets credentials.
# GOOGLE_SHEETS_SPREADSHEET_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# GOOGLE_SHEETS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

repo_name: FASTER/oai

license: unknown


code:
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text

path: .gitattributes


code:
.env
.venv
.vscode
build
greeting.md
node_modules

path: .gitignore


code:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run type-check

path: .husky/pre-push


code:
# OAI Reverse Proxy

Reverse proxy server for the OpenAI and Anthropic APIs. Forwards text generation requests while rejecting administrative/billing requests. Includes optional rate limiting and prompt filtering to prevent abuse.

### Table of Contents
- [What is this?](#what-is-this)
- [Why?](#why)
- [Usage Instructions](#setup-instructions)
  - [Deploy to Huggingface (Recommended)](#deploy-to-huggingface-recommended)
  - [Deploy to Repl.it (WIP)](#deploy-to-replit-wip)
- [Local Development](#local-development)

## What is this?
If you would like to provide a friend access to an API via keys you own, you can use this to keep your keys safe while still allowing them to generate text with the API. You can also use this if you'd like to build a client-side application which uses the OpenAI or Anthropic APIs, but don't want to build your own backend. You should never embed your real API keys in a client-side application. Instead, you can have your frontend connect to this reverse proxy and forward requests to the downstream service.

This keeps your keys safe and allows you to use the rate limiting and prompt filtering features of the proxy to prevent abuse.

## Why?
OpenAI keys have full account permissions. They can revoke themselves, generate new keys, modify spend quotas, etc. **You absolutely should not share them, post them publicly, nor embed them in client-side applications as they can be easily stolen.**

This proxy only forwards text generation requests to the downstream service and rejects requests which would otherwise modify your account.

---

## Usage Instructions
If you'd like to run your own instance of this proxy, you'll need to deploy it somewhere and configure it with your API keys. A few easy options are provided below, though you can also deploy it to any other service you'd like.

### Deploy to Huggingface (Recommended)
[See here for instructions on how to deploy to a Huggingface Space.](./docs/deploy-huggingface.md)

### Deploy to Render
[See here for instructions on how to deploy to Render.com.](./docs/deploy-render.md)

## Local Development
To run the proxy locally for development or testing, install Node.js >= 18.0.0 and follow the steps below.

1. Clone the repo
2. Install dependencies with `npm install`
3. Create a `.env` file in the root of the project and add your API keys. See the [.env.example](./.env.example) file for an example.
4. Start the server in development mode with `npm run start:dev`.

You can also use `npm run start:dev:tsc` to enable project-wide type checking at the cost of slower startup times. `npm run type-check` can be used to run type checking without starting the server.


code:
FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y git
RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app
WORKDIR /app
RUN npm install
COPY Dockerfile greeting.md* .env* ./
RUN npm run build
EXPOSE 7860
ENV NODE_ENV=production
CMD [ "npm", "start" ]

path: docker/huggingface/Dockerfile


code:
# syntax = docker/dockerfile:1.2

FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y curl

# Unlike Huggingface, Render can only deploy straight from a git repo and
# doesn't allow you to create or modify arbitrary files via the web UI.
# To use a greeting file, set `GREETING_URL` to a URL that points to a raw
# text file containing your greeting, such as a GitHub Gist.

# You may need to clear the build cache if you change the greeting, otherwise
# Render will use the cached layer from the previous build.

WORKDIR /app
ARG GREETING_URL
RUN if [ -n "$GREETING_URL" ]; then \
    curl -sL "$GREETING_URL" > greeting.md; \
    fi
COPY package*.json greeting.md* ./
RUN npm install
COPY . .
RUN npm run build
RUN --mount=type=secret,id=_env,dst=/etc/secrets/.env cat /etc/secrets/.env >> .env
EXPOSE 10000
ENV NODE_ENV=production
CMD [ "npm", "start" ]

path: docker/render/Dockerfile


code:
openapi: 3.0.0
info:
  version: 1.0.0
  title: User Management API
paths:
  /admin/users:
    get:
      summary: List all users
      operationId: getUsers
      responses:
        "200":
          description: A list of users
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      $ref: "#/components/schemas/User"
                  count:
                    type: integer
                    format: int32
    post:
      summary: Create a new user
      operationId: createUser
      requestBody:
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  properties:
                    type:
                      type: string
                      enum: ["normal", "special"]
                - type: object
                  properties:
                    type:
                      type: string
                      enum: ["temporary"]
                    expiresAt:
                      type: integer
                      format: int64
                    tokenLimits:
                      $ref: "#/components/schemas/TokenCount"
      responses:
        "200":
          description: The created user's token
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
    put:
      summary: Bulk upsert users
      operationId: bulkUpsertUsers
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                users:
                  type: array
                  items:
                    $ref: "#/components/schemas/User"
      responses:
        "200":
          description: The upserted users
          content:
            application/json:
              schema:
                type: object
                properties:
                  upserted_users:
                    type: array
                    items:
                      $ref: "#/components/schemas/User"
                  count:
                    type: integer
                    format: int32
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string

  /admin/users/{token}:
    get:
      summary: Get a user by token
      operationId: getUser
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: A user
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "404":
          description: Not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
    put:
      summary: Update a user by token
      operationId: upsertUser
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/User"
      responses:
        "200":
          description: The updated user
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
    delete:
      summary: Disables the user with the given token
      description: Optionally accepts a `disabledReason` query parameter. Returns the disabled user.
      parameters:
        - in: path
          name: token
          required: true
          schema:
            type: string
          description: The token of the user to disable
        - in: query
          name: disabledReason
          required: false
          schema:
            type: string
          description: The reason for disabling the user
      responses:
        '200':
          description: The disabled user
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '404':
          description: Not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
components:
  schemas:
    TokenCount:
      type: object
      properties:
        turbo:
          type: integer
          format: int32
        gpt4:
          type: integer
          format: int32
        "gpt4-32k":
          type: integer
          format: int32
        claude:
          type: integer
          format: int32
    User:
      type: object
      properties:
        token:
          type: string
        ip:
          type: array
          items:
            type: string
        nickname:
          type: string
        type:
          type: string
          enum: ["normal", "special"]
        promptCount:
          type: integer
          format: int32
        tokenLimits:
          $ref: "#/components/schemas/TokenCount"
        tokenCounts:
          $ref: "#/components/schemas/TokenCount"
        createdAt:
          type: integer
          format: int64
        lastUsedAt:
          type: integer
          format: int64
        disabledAt:
          type: integer
          format: int64
        disabledReason:
          type: string
        expiresAt:
          type: integer
          format: int64


code:
# Deploy to Huggingface Space

This repository can be deployed to a [Huggingface Space](https://huggingface.co/spaces).  This is a free service that allows you to run a simple server in the cloud.  You can use it to safely share your OpenAI API key with a friend.

### 1. Get an API key
- Go to [OpenAI](https://openai.com/) and sign up for an account. You can use a free trial key for this as long as you provide SMS verification.
    - Claude is not publicly available yet, but if you have access to it via the [Anthropic](https://www.anthropic.com/) closed beta, you can also use that key with the proxy.

### 2. Create an empty Huggingface Space
- Go to [Huggingface](https://huggingface.co/) and sign up for an account.
- Once logged in, [create a new Space](https://huggingface.co/new-space).
- Provide a name for your Space and select "Docker" as the SDK.  Select "Blank" for the template.
- Click "Create Space" and wait for the Space to be created.

![Create Space](assets/huggingface-createspace.png)

### 3. Create an empty Dockerfile
- Once your Space is created, you'll see an option to "Create the Dockerfile in your browser".  Click that link.

![Create Dockerfile](assets/huggingface-dockerfile.png)
- Paste the following into the text editor and click "Save".
```dockerfile
FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y git
RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app
WORKDIR /app
RUN npm install
COPY Dockerfile greeting.md* .env* ./
RUN npm run build
EXPOSE 7860
ENV NODE_ENV=production
CMD [ "npm", "start" ]
```
- Click "Commit new file to `main`" to save the Dockerfile.

![Commit](assets/huggingface-savedockerfile.png)

### 4. Set your API key as a secret
- Click the Settings button in the top right corner of your repository.
- Scroll down to the `Repository Secrets` section and click `New Secret`.

![Secrets](https://files.catbox.moe/irrp2p.png)

- Enter `OPENAI_KEY` as the name and your OpenAI API key as the value.
    - For Claude, set `ANTHROPIC_KEY` instead.
    - You can use both types of keys at the same time if you want.

![New Secret](https://files.catbox.moe/ka6s1a.png)

### 5. Deploy the server
- Your server should automatically deploy when you add the secret, but if not you can select `Factory Reboot` from that same Settings menu.

### 6. Share the link
- The Service Info section below should show the URL for your server. You can share this with anyone to safely give them access to your API key.
- Your friend doesn't need any API key of their own, they just need your link.

# Optional

## Updating the server

To update your server, go to the Settings menu and select `Factory Reboot`.  This will pull the latest version of the code from GitHub and restart the server.

Note that if you just perform a regular Restart, the server will be restarted with the same code that was running before.

## Adding a greeting message

You can create a Markdown file called `greeting.md` to display a message on the Server Info page.  This is a good place to put instructions for how to use the server.

## Customizing the server

The server will be started with some default configuration, but you can override it by adding a `.env` file to your Space.  You can use Huggingface's web editor to create a new `.env` file alongside your Dockerfile. Huggingface will restart your server automatically when you save the file.

Here are some example settings:
```shell
# Requests per minute per IP address
MODEL_RATE_LIMIT=4
# Max tokens to request from OpenAI
MAX_OUTPUT_TOKENS_OPENAI=256
# Max tokens to request from Anthropic (Claude)
MAX_OUTPUT_TOKENS_ANTHROPIC=512
# Block prompts containing disallowed characters
REJECT_DISALLOWED=false
REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy."
```

See `.env.example` for a full list of available settings, or check `config.ts` for details on what each setting does.

## Restricting access to the server

If you want to restrict access to the server, you can set a `PROXY_KEY` secret.  This key will need to be passed in the Authentication header of every request to the server, just like an OpenAI API key.

Add this using the same method as the OPENAI_KEY secret above. Don't add this to your `.env` file because that file is public and anyone can see it.


code:
# Deploy to Render.com
Render.com offers a free tier that includes 750 hours of compute time per month.  This is enough to run a single proxy instance 24/7.  Instances shut down after 15 minutes without traffic but start up again automatically when a request is received.  You can use something like https://app.checklyhq.com/ to ping your proxy every 15 minutes to keep it alive.

### 1. Create account
- [Sign up for Render.com](https://render.com/) to create an account and access the dashboard.

### 2. Create a service using a Blueprint
Render allows you to deploy and auutomatically configure a repository containing a [render.yaml](../render.yaml) file using its Blueprints feature.  This is the easiest way to get started.

- Click the **Blueprints** tab at the top of the dashboard.
- Click **New Blueprint Instance**.
- Under **Public Git repository**, enter `https://gitlab.com/khanon/oai-proxy`.
  - Note that this is not the GitGud repository, but a mirror on GitLab.
- Click **Continue**.
- Under **Blueprint Name**, enter a name.
- Under **Branch**, enter `main`.
- Click **Apply**.

The service will be created according to the instructions in the `render.yaml` file.  Don't wait for it to complete as it will fail due to missing environment variables.  Instead, proceed to the next step.

### 3. Set environment variables
- Return to the **Dashboard** tab.
- Click the name of the service you just created, which may show as "Deploy failed".
- Click the **Environment** tab.
- Click **Add Secret File**.
- Under **Filename**, enter `.env`.
- Under **Contents**, enter all of your environment variables, one per line, in the format `NAME=value`.
  - For example, `OPENAI_KEY=sk-abc123`.
- Click **Save Changes**.

The service will automatically rebuild and deploy with the new environment variables.  This will take a few minutes.  The link to your deployed proxy will appear at the top of the page.

If you want to change the URL, go to the **Settings** tab of your Web Service and click the **Edit** button next to **Name**.  You can also set a custom domain, though I haven't tried this yet.

# Optional

## Updating the server

To update your server, go to the page for your Web Service and click **Manual Deploy** > **Deploy latest commit**.  This will pull the latest version of the code and redeploy the server.

_If you have trouble with this, you can also try selecting **Clear build cache & deploy** instead from the same menu._

## Adding a greeting message

To show a greeting message on the Server Info page, set the `GREETING_URL` environment variable within Render to the URL of a Markdown file.  This URL should point to a raw text file, not an HTML page. You can use a public GitHub Gist or GitLab Snippet for this.  For example: `GREETING_URL=https://gitlab.com/-/snippets/2542011/raw/main/greeting.md`.  You can change the title of the page by setting the `SERVER_TITLE` environment variable.

Don't set `GREETING_URL` in the `.env` secret file you created earlier; it must be set in Render's environment variables section for it to work correctly.

## Customizing the server

You can customize the server by editing the `.env` configuration you created earlier. Refer to [.env.example](../.env.example) for a list of all available configuration options. Further information can be found in the [config.ts](../src/config.ts) file.


code:
# Warning
**I strongly suggest against using this feature with a Google account that you care about.** Depending on the content of the prompts people submit, Google may flag the spreadsheet as containing inappropriate content. This seems to prevent you from sharing that spreadsheet _or any others on the account. This happened with my throwaway account during testing; the existing shared spreadsheet continues to work but even completely new spreadsheets are flagged and cannot be shared.

I'll be looking into alternative storage backends but you should not use this implementation with a Google account you care about, or even one remotely connected to your main accounts (as Google has a history of linking accounts together via IPs/browser fingerprinting). Use a VPN and completely isolated VM to be safe.

# Configuring Google Sheets Prompt Logging
This proxy can log incoming prompts and model responses to Google Sheets. Some configuration on the Google side is required to enable this feature. The APIs used are free, but you will need a Google account and a Google Cloud Platform project.

NOTE: Concurrency is not supported. Don't connect two instances of the server to the same spreadsheet or bad things will happen.

## Prerequisites
- A Google account
  - **USE A THROWAWAY ACCOUNT!**
- A Google Cloud Platform project

### 0. Create a Google Cloud Platform Project
_A Google Cloud Platform project is required to enable programmatic access to Google Sheets. If you already have a project, skip to the next step. You can also see the [Google Cloud Platform documentation](https://developers.google.com/workspace/guides/create-project) for more information._

- Go to the Google Cloud Platform Console and [create a new project](https://console.cloud.google.com/projectcreate).

### 1. Enable the Google Sheets API
_The Google Sheets API must be enabled for your project. You can also see the [Google Sheets API documentation](https://developers.google.com/sheets/api/quickstart/nodejs) for more information._

- Go to the [Google Sheets API page](https://console.cloud.google.com/apis/library/sheets.googleapis.com) and click **Enable**, then fill in the form to enable the Google Sheets API for your project.
<!-- TODO: Add screenshot of Enable page and describe filling out the form -->

### 2. Create a Service Account
_A service account is required to authenticate the proxy to Google Sheets._

- Once the Google Sheets API is enabled, click the **Credentials** tab on the Google Sheets API page.
- Click **Create credentials** and select **Service account**.
- Provide a name for the service account and click **Done** (the second and third steps can be skipped).

### 3. Download the Service Account Key
_Once your account is created, you'll need to download the key file and include it in the proxy's secrets configuration._

- Click the Service Account you just created in the list of service accounts for the API.
- Click the **Keys** tab and click **Add key**, then select **Create new key**.
- Select **JSON** as the key type and click **Create**.

The JSON file will be downloaded to your computer.

### 4. Set the Service Account key as a Secret
_The JSON key file must be set as a secret in the proxy's configuration. Because files cannot be included in the secrets configuration, you'll need to base64 encode the file's contents and paste the encoded string as the value of the `GOOGLE_SHEETS_KEY` secret._

- Open the JSON key file in a text editor and copy the contents.
- Visit the [base64 encode/decode tool](https://www.base64encode.org/) and paste the contents into the box, then click **Encode**.
- Copy the encoded string and paste it as the value of the `GOOGLE_SHEETS_KEY` secret in the deployment's secrets configuration.
  - **WARNING:** Don't reveal this string publically. The `.env` file is NOT private -- unless you're running the proxy locally, you should not use it to store secrets!

### 5. Create a new spreadsheet and share it with the service account
_The service account must be given permission to access the logging spreadsheet. Each service account has a unique email address, which can be found in the JSON key file; share the spreadsheet with that email address just as you would share it with another user._

- Open the JSON key file in a text editor and copy the value of the `client_email` field.
- Open the spreadsheet you want to log to, or create a new one, and click **File > Share**.
- Paste the service account's email address into the **Add people or groups** field. Ensure the service account has **Editor** permissions, then click **Done**.

### 6. Set the spreadsheet ID as a Secret
_The spreadsheet ID must be set as a secret in the proxy's configuration. The spreadsheet ID can be found in the URL of the spreadsheet. For example, the spreadsheet ID for `https://docs.google.com/spreadsheets/d/1X2Y3Z/edit#gid=0` is `1X2Y3Z`.  The ID isn't necessarily a sensitive value if you intend for the spreadsheet to be public, but it's still recommended to set it as a secret._

- Copy the spreadsheet ID and paste it as the value of the `GOOGLE_SHEETS_SPREADSHEET_ID` secret in the deployment's secrets configuration.


code:
# User Management

The proxy supports several different user management strategies. You can choose the one that best fits your needs by setting the `GATEKEEPER` environment variable.

Several of these features require you to set secrets in your environment. If using Huggingface Spaces to deploy, do not set these in your `.env` file because that file is public and anyone can see it.

## Table of Contents

- [No user management](#no-user-management-gatekeepernone)
- [Single-password authentication](#single-password-authentication-gatekeeperproxy_key)
- [Per-user authentication](#per-user-authentication-gatekeeperuser_token)
  - [Memory](#memory)
  - [Firebase Realtime Database](#firebase-realtime-database)
    - [Firebase setup instructions](#firebase-setup-instructions)

## No user management (`GATEKEEPER=none`)

This is the default mode. The proxy will not require any authentication to access the server and offers basic IP-based rate limiting and anti-abuse features.

## Single-password authentication (`GATEKEEPER=proxy_key`)

This mode allows you to set a password that must be passed in the `Authentication` header of every request to the server as a bearer token. This is useful if you want to restrict access to the server, but don't want to create a separate account for every user.

To set the password, create a `PROXY_KEY` secret in your environment.

## Per-user authentication (`GATEKEEPER=user_token`)

This mode allows you to provision separate Bearer tokens for each user. You can manage users via the /admin/users via REST or through the admin interface at `/admin`.

To begin, set `ADMIN_KEY` to a secret value. This will be used to authenticate requests to the REST API or to log in to the UI.

[You can find an OpenAPI specification for the /admin/users REST API here.](openapi-admin-users.yaml)

By default, the proxy will store user data in memory. Naturally, this means that user data will be lost when the proxy is restarted, though you can use the user import/export feature to save and restore user data manually or via a script. However, the proxy also supports persisting user data to an external data store with some additional configuration.

Below are the supported data stores and their configuration options.

### Memory

This is the default data store (`GATEKEEPER_STORE=memory`) User data will be stored in memory and will be lost when the server is restarted. You are responsible for exporting and re-importing user data after a restart.

### Firebase Realtime Database

To use Firebase Realtime Database to persist user data, set the following environment variables:

- `GATEKEEPER_STORE`: Set this to `firebase_rtdb`
- **Secret** `FIREBASE_RTDB_URL`: The URL of your Firebase Realtime Database, e.g. `https://my-project-default-rtdb.firebaseio.com`
- **Secret** `FIREBASE_KEY`: A base-64 encoded service account key for your Firebase project. Refer to the instructions below for how to create this key.

**Firebase setup instructions**

1. Go to the [Firebase console](https://console.firebase.google.com/) and click "Add project", then follow the prompts to create a new project.
2. From the **Project Overview** page, click **All products** in the left sidebar, then click **Realtime Database**.
3. Click **Create database** and choose **Start in test mode**. Click **Enable**.
   - Test mode is fine for this use case as it still requires authentication to access the database. You may wish to set up more restrictive rules if you plan to use the database for other purposes.
   - The reference URL for the database will be displayed on the page. You will need this later.
4. Click the gear icon next to **Project Overview** in the left sidebar, then click **Project settings**.
5. Click the **Service accounts** tab, then click **Generate new private key**.
6. The downloaded file contains your key. Encode it as base64 and set it as the `FIREBASE_KEY` secret in your environment.
7. Set `FIREBASE_RTDB_URL` to the reference URL of your Firebase Realtime Database, e.g. `https://my-project-default-rtdb.firebaseio.com`.
8. Set `GATEKEEPER_STORE` to `firebase_rtdb` in your environment if you haven't already.

The proxy server will attempt to connect to your Firebase Realtime Database at startup and will throw an error if it cannot connect. If you see this error, check that your `FIREBASE_RTDB_URL` and `FIREBASE_KEY` secrets are set correctly.


code:
# User Quotas

When using `user_token` authentication, you can set (model) token quotas for user.  These quotas are enforced by the proxy server and are separate from the quotas enforced by OpenAI.

You can set the default quota via environment variables. Quotas are enforced on a per-model basis, and count both prompt tokens and completion tokens. By default, all quotas are disabled.

Set the following environment variables to set the default quotas:
- `TOKEN_QUOTA_TURBO`
- `TOKEN_QUOTA_GPT4`
- `TOKEN_QUOTA_CLAUDE`

Quotas only apply to `normal`-type users; `special`-type users are exempt from quotas. You can change users' types via the REST API.

**Note that changes to these environment variables will only apply to newly created users.**  To modify existing users' quotas, use the REST API or the admin UI.

## Automatically refreshing quotas

You can use the `QUOTA_REFRESH_PERIOD` environment variable to automatically refresh users' quotas periodically.  This is useful if you want to give users a certain number of tokens per day, for example. The entire quota will be refreshed at the start of the specified period, and any tokens a user has not used will not be carried over.

Quotas for all models and users will be refreshed. If you haven't set `TOKEN_QUOTA_*` for a particular model, quotas for that model will not be refreshed (so any manually set quotas will not be overwritten).

Set the `QUOTA_REFRESH_PERIOD` environment variable to one of the following values:
- `daily` (at midnight)
- `hourly`
- leave unset to disable automatic refreshing

You can also use a cron expression, for example:
- Every 45 seconds: `"*/45 * * * * *"`
- Every 30 minutes: `"*/30 * * * *"`
- Every 6 hours: `"0 */6 * * *"`
- Every 3 days: `"0 0 */3 * *"`
- Daily, but at mid-day: `"0 12 * * *"`

Make sure to enclose the cron expression in quotation marks.

All times are in the server's local time zone. Refer to [crontab.guru](https://crontab.guru/) for more examples.


oai-reverse-proxy

license: MIT

acorn: bin/acorn

type: github

type: patreon

type: consulting

type: individual

copyfiles: copyfiles

copyup: copyfiles

type: opencollective

esbuild: bin/esbuild

type: tidelift

pbjs: bin/pbjs

pbts: bin/pbts

tsc: bin/tsc

tsserver: bin/tsserver

uglifyjs: bin/uglifyjs


description: Reverse proxy for the OpenAI API

build: tsc && copyfiles -u 1 src/**/*.ejs build

start:dev: nodemon --watch src --exec ts-node --transpile-only src/server.ts

start:watch: nodemon --require source-map-support/register build/server.js

start:replit: tsc && node build/server.js

start: node build/server.js

type-check: tsc --noEmit

prepare: husky install


code:
services:
  - type: web
    name: oai-proxy
    env: docker
    repo: https://gitlab.com/khanon/oai-proxy.git
    region: oregon
    plan: free
    branch: main
    healthCheckPath: /health
    dockerfilePath: ./docker/render/Dockerfile


code:
import { Router } from "express";
import { z } from "zod";
import * as userStore from "../../shared/users/user-store";
import { parseSort, sortBy } from "../../shared/utils";
import { UserPartialSchema, UserSchema } from "../../shared/users/schema";

const router = Router();

/**
 * Returns a list of all users, sorted by prompt count and then last used time.
 * GET /admin/users
 */
router.get("/", (req, res) => {
  const sort = parseSort(req.query.sort) || ["promptCount", "lastUsedAt"];
  const users = userStore.getUsers().sort(sortBy(sort, false));
  res.json({ users, count: users.length });
});

/**
 * Returns the user with the given token.
 * GET /admin/users/:token
 */
router.get("/:token", (req, res) => {
  const user = userStore.getUser(req.params.token);
  if (!user) {
    return res.status(404).json({ error: "Not found" });
  }
  res.json(user);
});

/**
 * Creates a new user.
 * Optionally accepts a JSON body containing `type`, and for temporary-type
 * users, `tokenLimits` and `expiresAt` fields.
 * Returns the created user's token.
 * POST /admin/users
 */
router.post("/", (req, res) => {
  const body = req.body;

  const base = z.object({
    type: UserSchema.shape.type.exclude(["temporary"]).default("normal"),
  });
  const tempUser = base
    .extend({
      type: z.literal("temporary"),
      expiresAt: UserSchema.shape.expiresAt,
      tokenLimits: UserSchema.shape.tokenLimits,
    })
    .required();

  const schema = z.union([base, tempUser]);
  const result = schema.safeParse(body);
  if (!result.success) {
    return res.status(400).json({ error: result.error });
  }

  const token = userStore.createUser({ ...result.data });
  res.json({ token });
});

/**
 * Updates the user with the given token, creating them if they don't exist.
 * Accepts a JSON body containing at least one field on the User type.
 * Returns the upserted user.
 * PUT /admin/users/:token
 */
router.put("/:token", (req, res) => {
  const result = UserPartialSchema.safeParse({
    ...req.body,
    token: req.params.token,
  });
  if (!result.success) {
    return res.status(400).json({ error: result.error });
  }
  userStore.upsertUser(result.data);
  res.json(userStore.getUser(req.params.token));
});

/**
 * Bulk-upserts users given a list of User updates.
 * Accepts a JSON body with the field `users` containing an array of updates.
 * Returns an object containing the upserted users and the number of upserts.
 * PUT /admin/users
 */
router.put("/", (req, res) => {
  const result = z.array(UserPartialSchema).safeParse(req.body.users);
  if (!result.success) {
    return res.status(400).json({ error: result.error });
  }
  const upserts = result.data.map((user) => userStore.upsertUser(user));
  res.json({ upserted_users: upserts, count: upserts.length });
});

/**
 * Disables the user with the given token. Optionally accepts a `disabledReason`
 * query parameter.
 * Returns the disabled user.
 * DELETE /admin/users/:token
 */
router.delete("/:token", (req, res) => {
  const user = userStore.getUser(req.params.token);
  const disabledReason = z
    .string()
    .optional()
    .safeParse(req.query.disabledReason);
  if (!disabledReason.success) {
    return res.status(400).json({ error: disabledReason.error });
  }
  if (!user) {
    return res.status(404).json({ error: "Not found" });
  }
  userStore.disableUser(req.params.token, disabledReason.data);
  res.json(userStore.getUser(req.params.token));
});

export { router as usersApiRouter };


code:
import { Request, Response, RequestHandler } from "express";
import { config } from "../config";

const ADMIN_KEY = config.adminKey;
const failedAttempts = new Map<string, number>();

type AuthorizeParams = { via: "cookie" | "header" };

export const authorize: ({ via }: AuthorizeParams) => RequestHandler =
  ({ via }) =>
  (req, res, next) => {
    const bearerToken = req.headers.authorization?.slice("Bearer ".length);
    const cookieToken = req.session.adminToken;
    const token = via === "cookie" ? cookieToken : bearerToken;
    const attempts = failedAttempts.get(req.ip) ?? 0;

    if (!ADMIN_KEY) {
      req.log.warn(
        { ip: req.ip },
        `Blocked admin request because no admin key is configured`
      );
      return res.status(401).json({ error: "Unauthorized" });
    }

    if (attempts > 5) {
      req.log.warn(
        { ip: req.ip, token: bearerToken },
        `Blocked admin request due to too many failed attempts`
      );
      return res.status(401).json({ error: "Too many attempts" });
    }

    if (token && token === ADMIN_KEY) {
      return next();
    }

    req.log.warn(
      { ip: req.ip, attempts, invalidToken: String(token) },
      `Attempted admin request with invalid token`
    );
    return handleFailedLogin(req, res);
  };

function handleFailedLogin(req: Request, res: Response) {
  const attempts = failedAttempts.get(req.ip) ?? 0;
  const newAttempts = attempts + 1;
  failedAttempts.set(req.ip, newAttempts);
  if (req.accepts("json", "html") === "json") {
    return res.status(401).json({ error: "Unauthorized" });
  }
  delete req.session.adminToken;
  req.session.flash = { type: "error", message: `Invalid admin key.` };
  return res.redirect("/admin/login");
}


code:
import { Router } from "express";

const loginRouter = Router();

loginRouter.get("/login", (_req, res) => {
  res.render("admin_login");
});

loginRouter.post("/login", (req, res) => {
  req.session.adminToken = req.body.token;
  res.redirect("/admin");
});

loginRouter.get("/logout", (req, res) => {
  delete req.session.adminToken;
  res.redirect("/admin/login");
});

loginRouter.get("/", (req, res) => {
  if (req.session.adminToken) {
    return res.redirect("/admin/manage");
  }
  res.redirect("/admin/login");
});

export { loginRouter };


code:
import express, { Router } from "express";
import { authorize } from "./auth";
import { HttpError } from "../shared/errors";
import { injectLocals } from "../shared/inject-locals";
import { withSession } from "../shared/with-session";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { loginRouter } from "./login";
import { usersApiRouter as apiRouter } from "./api/users";
import { usersWebRouter as webRouter } from "./web/manage";

const adminRouter = Router();

adminRouter.use(
  express.json({ limit: "20mb" }),
  express.urlencoded({ extended: true, limit: "20mb" })
);
adminRouter.use(withSession);
adminRouter.use(injectCsrfToken);

adminRouter.use("/users", authorize({ via: "header" }), apiRouter);

adminRouter.use(checkCsrfToken);
adminRouter.use(injectLocals);
adminRouter.use("/", loginRouter);
adminRouter.use("/manage", authorize({ via: "cookie" }), webRouter);

adminRouter.use(
  (
    err: Error,
    req: express.Request,
    res: express.Response,
    _next: express.NextFunction
  ) => {
    const data: any = { message: err.message, stack: err.stack };
    if (err instanceof HttpError) {
      data.status = err.status;
      res.status(err.status);
      if (req.accepts(["html", "json"]) === "json") {
        return res.json({ error: data });
      }
      return res.render("admin_error", data);
    } else if (err.name === "ForbiddenError") {
      data.status = 403;
      if (err.message === "invalid csrf token") {
        data.message =
          "Invalid CSRF token; try refreshing the previous page before submitting again.";
      }
      return res.status(403).render("admin_error", { ...data, flash: null });
    }
    res.status(500).json({ error: data });
  }
);

export { adminRouter };