Specifically it comes from your SCN https://en.m.wikipedia.org/wiki/Suprachiasmatic_nucleus
The answer is it's evolved and some kind of complex cellular feedback mechanism, but Wikipedia is a bit light on details. Apparently this clock is also fanned out in some way to other parts of the brain/body which also follow a daily cycle.
https://www.sciencedirect.com/science/article/pii/B978044459...
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2735866/
Light isn't mandatory, but the SCN will synchronise to daily light patterns (eg when you travel). The SCN is also physically located close to the optic nerve. I think this is why the underlying rhythm is a slightly longer than a day, because it allows the body to reset it to 24 hours. If the period was shorter, even slightly less than 24 hours, maybe you'd have problems when the clock restarted before the day finished and the error would propagate over time (you'd keep shifting the cycle).
All definitions and measurements of time rely on counting events that are believed to happen at regular intervals. A second was defined for most of history as 1/246060 of a solar day, in other words, measuring changes in lighting.
We can tell time inaccurately by timing somewhat regular internal biological events. That pretty much follows from the definition of time as the interval between regular events (which are assumed for physical reasons to be equally spaced). The only question is which underlying events we use and how.
I've always wondered what would happen to the sleep cycles of astronauts on long space journeys. They may not have "daylight" to regulate their rhythms.
[1] https://news.harvard.edu/gazette/story/1999/07/human-biologi...