Skip to content

Commit ac9b330

Browse files
committed
fix: put the cursor on the starter code when a kata opens
Opening a kata with a solution template left the cursor at the top of the buffer, so the panel showed the template's imports and helpers and the code the user came to write sat below the fold. With a long template -- the java one that routes java.util.logging to stdout runs to twenty-odd lines -- the starter was off screen entirely, and `:CW reset` was the only way to see it. The cursor now lands on the last character of the starter, found from the buffer rather than from anything remembered: - A template with content after {{starter}} no longer strands the cursor in its own suffix, and `return {{starter}};` leaves it on the user's last character rather than the semicolon. - Reopening a kata locates the starter in the file that was written, which is the visit where a long preamble hides the code most. A position remembered from the render that seeded the file describes a buffer that stopped existing after the first edit -- and was never refreshed by a language switch onto a file that already existed, so it aimed at the previous language's rows. - A cursor position restored by the user's own config is left alone when it is inside their code, and overridden when it is in the template's generated preamble -- including on the starter's own row, ahead of it. - Placement waits until the description and testcase splits have taken their space. Measured against a full-height window it left the panel scrolled somewhere the starter was not. - `:CW reset`, `:CW template on` and `:CW template off` all move to the same place. Turning the template off used to leave the window parked at a line near the end of a buffer that had just lost its preamble, so the panel showed one closing brace and nothing else. - Trailing newlines are separators, not the last thing the user wrote, and a multibyte final character gets its own first byte rather than a continuation byte. A duplicated {{starter}} now warns once per language: it renders, putting the code in the last one, while `:CW template off` refuses that shape outright -- so the buffer opened without complaint and then declined.
1 parent 0ba412e commit ac9b330

7 files changed

Lines changed: 636 additions & 65 deletions

File tree

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# Review: `feat/cookie-two-fields` (local branch, no PR)
2+
3+
**Reviewed**: 2026-08-28
4+
**Branch**: feat/cookie-two-fields → main (`7e6617e`, 1 commit)
5+
**Decision**: REQUEST CHANGES
6+
7+
## Summary
8+
9+
The feature does what it set out to do and the storage format is correctly
10+
preserved, so existing sessions are unaffected. But `set_parts` builds a
11+
cookie header and then trusts `parse` to validate it — and `parse` can
12+
succeed on a mangled string. A realistic paste mistake produces a
13+
*successful* sign-in with a garbage session id.
14+
15+
## Findings
16+
17+
### CRITICAL
18+
None.
19+
20+
### HIGH
21+
22+
**H1 — Pasting the full header into box 2 silently corrupts the session id**
23+
`lua/codewars/cache/cookie.lua:42` (`Cookie.set_parts`)
24+
25+
Box 1 tells the user a full `CSRF-TOKEN=...; _session_id=...` paste is
26+
accepted, so pasting the same clipboard content into box 2 is a natural
27+
mistake. `clean_field(value, "_session_id")` does not strip a `CSRF-TOKEN=`
28+
prefix, so the whole header survives into the built string:
29+
30+
set_parts("abc", "CSRF-TOKEN=abc; _session_id=xyz")
31+
stored: "CSRF-TOKEN=abc; _session_id=CSRF-TOKEN=abc; _session_id=xyz"
32+
parsed: csrf="abc" session="CSRF-TOKEN=abc"
33+
34+
`parse` matches `_session_id=([^;]+)` at its *first* occurrence, captures
35+
`CSRF-TOKEN=abc`, and returns no error. `Cookie.set` writes the file, the
36+
prompt logs "Sign-in successful", and every authenticated request then
37+
fails against a session id that was never a session id. The user has no way
38+
to connect the failure to what they typed.
39+
40+
Verified by executing the exact `clean_field`/build/`parse` chain.
41+
42+
**Fix**: make `set_parts` verify its own output instead of trusting `parse`
43+
— build the header, parse it back, and error if either value does not match
44+
what went in. That closes this and M1 together.
45+
46+
### MEDIUM
47+
48+
**M1 — A value containing `;` is truncated without complaint**
49+
`lua/codewars/cache/cookie.lua:32`
50+
51+
set_parts("ab;c", "xyz") -> csrf parses back as "ab"
52+
53+
`clean_field` strips only a *trailing* `;`; an interior one silently splits
54+
the value at write time. Real Codewars tokens don't contain `;`, so the
55+
likelihood is low — but it is the same silent-corruption class as H1 and the
56+
same round-trip check fixes it.
57+
58+
**M2 — The prompt flow itself is untested**
59+
`lua/codewars/command/init.lua:1034-1113`
60+
61+
`cookie_prompt` is where H1 is reachable, and nothing covers it: not the
62+
box-1 combined-paste shortcut, not the chaining, not cancellation via
63+
`on_close`, not the double-`cb` risk. The seven new tests all sit below it
64+
on `set_parts`. A test at the seam that H1 lives on would have caught H1.
65+
66+
**M3 — `command/init.lua` is 1432 lines**
67+
Grew 1404 → 1432 here. `CLAUDE.md` sets 800 as the ceiling and 200-400 as
68+
typical. Pre-existing and not this branch's fault, but the branch moved it
69+
the wrong way; the cookie prompt is a self-contained candidate for
70+
extraction.
71+
72+
### LOW
73+
74+
**L1 — Cookie file is world-readable** (pre-existing, not introduced here)
75+
`~/.cache/nvim/codewars/cookie` is `-rw-r--r--`. It holds a live session
76+
token; any local user can read it. The write path (`Cookie.set`) is
77+
untouched by this branch, so this is a separate fix, but this branch is the
78+
natural moment to raise it.
79+
80+
## Validation Results
81+
82+
| Check | Result |
83+
|---|---|
84+
| Lint (luacheck, 122 files) | Pass — 0 warnings / 0 errors |
85+
| Tests (`make test`) | Pass — 699 passing, 0 failures |
86+
| Type check | N/A (Lua) |
87+
| Build | N/A |
88+
89+
Note: green validation is exactly the problem with H1 — the seven new tests
90+
cover the paths that work and none of the ones that silently don't.
91+
92+
## Files Reviewed
93+
94+
| File | Change |
95+
|---|---|
96+
| `lua/codewars/cache/cookie.lua` | Modified — +`clean_field`, +`set_parts` |
97+
| `lua/codewars/command/init.lua` | Modified — `cookie_prompt` rewritten, +`ask_cookie_value` |
98+
| `test/codewars/cookie_parts_spec.lua` | Added — 7 cases |
99+
| `README.md` | Modified — auth section |
100+
| `CHANGELOG.md` | Modified — Unreleased entry |

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
TODOS.md
22
CLAUDE.md
3+
.claude/
34
.gstack/

‎CHANGELOG.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,25 @@ All notable changes to codewars.nvim are documented here.
1212
whole row out of the DevTools cookie table works. Pasting the full header
1313
into the first box still works and skips the second.
1414

15+
## [Unreleased]
16+
17+
### Fixed
18+
- Opening a kata puts the cursor on your starter code instead of at the top of
19+
your template. It follows the starter wherever the template puts it, so a
20+
template with a main guard or helpers after `{{starter}}` no longer lands you
21+
in its own suffix, and one like `return {{starter}};` leaves you on your last
22+
character rather than its semicolon. A position restored from a previous
23+
visit is kept when it is inside your code and overridden when it is in the
24+
template's boilerplate.
25+
- `:CW reset` moves the cursor to the starter, rather than leaving it wherever
26+
it was before the buffer was rewritten.
27+
28+
### Changed
29+
- A solution template carrying more than one `{{starter}}` now warns once per
30+
language. It renders — your code goes in the last one — but `:CW template
31+
off` cannot tell which is yours, so it would refuse a buffer that opened
32+
without complaint.
33+
1534
## [0.3.3] - 2026-08-26
1635

1736
### Added

‎lua/codewars-ui/kata.lua‎

Lines changed: 114 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -84,27 +84,17 @@ function Kata:retemplate(op)
8484
local templates = require("codewars.templates")
8585
local apply = op == "wrap" and templates.wrap or templates.strip
8686

87-
local text, reason_or_pos = apply(self.lang, self:_buffer_text(), self:_template_ctx())
87+
local text, reason = apply(self.lang, self:_buffer_text(), self:_template_ctx())
8888
if not text then
89-
log.info(reason_or_pos)
89+
log.info(reason)
9090
return false
9191
end
9292

9393
self:_set_code(text)
94-
-- Wrapping moved the user's code and left the cursor pointing into the
95-
-- template's preamble; put it at the END OF THE STARTER (wrap returns
96-
-- that position) — not EOF, which is the template's suffix when there
97-
-- is content after {{starter}}. Unconditional: the rewrite invalidated
98-
-- the old position, so the open-path guard against overriding a
99-
-- restored position does not apply here.
100-
if op == "wrap" then
101-
local pos = type(reason_or_pos) == "table" and reason_or_pos or nil
102-
if pos and self.winid and vim.api.nvim_win_is_valid(self.winid) then
103-
pcall(vim.api.nvim_win_set_cursor, self.winid, pos)
104-
else
105-
self:_cursor_to_end(true)
106-
end
107-
end
94+
-- Forced: the rewrite moved the user's code, so wherever the cursor was
95+
-- describes a buffer that no longer exists. Both directions end up at the
96+
-- same question -- where is the code now -- and the buffer answers it.
97+
self:_cursor_to_end(true)
10898
return true
10999
end
110100

@@ -146,37 +136,115 @@ function Kata:create_buffer()
146136
self:_cursor_to_end()
147137
end
148138

149-
--- Put the cursor at the end of the solution buffer.
139+
--- Where the starter sits in THIS buffer, right now.
140+
---
141+
--- Deliberately not cached from the render that seeded the file. That value is
142+
--- only produced on the first visit, and a language switch onto a file that
143+
--- already exists never refreshes it -- so a cached position outlives the
144+
--- buffer it described and then wins over looking. The buffer is the one thing
145+
--- that is always current.
146+
---@return cw.templates.Pos?
147+
function Kata:_locate_starter()
148+
local ok, pos = pcall(function()
149+
return require("codewars.templates").locate(self.lang, self:_buffer_text(), self:_template_ctx())
150+
end)
151+
-- locate() declining is ordinary and stays quiet: editing your own
152+
-- preamble is enough to stop the buffer matching the template, and the
153+
-- cursor simply falls back. An error inside it is not ordinary, and
154+
-- collapsing the two into the same silence hides it.
155+
if not ok then
156+
log.debug("kata could not locate the starter: " .. tostring(pos))
157+
return nil
158+
end
159+
return pos
160+
end
161+
162+
--- Put the cursor on the code the user came to write.
150163
---
151-
--- The top of a templated buffer is the user's own boilerplate — imports and
152-
--- helpers they already wrote. The code they opened the kata to write is at the
153-
--- bottom, so landing on line 1 means scrolling past their own preamble every
154-
--- time.
164+
--- The top of a templated buffer is their own boilerplate -- imports and
165+
--- helpers they already have. What they opened the kata to write is below it,
166+
--- so landing on line 1 means scrolling past their preamble every time.
155167
---
156-
--- Skipped unless the cursor is still on line 1. `$tabe` fires BufReadPost, so
157-
--- a restore-last-position autocmd (LazyVim and friends ship one) has already
158-
--- run by now; line 1 means nothing claimed a position, or there was none to
159-
--- restore. Moving anyway would fight the user's own config.
168+
--- A position something else already claimed is left alone. `$tabe` fires
169+
--- BufReadPost, so a restore-last-position autocmd (LazyVim and friends ship
170+
--- one) has run by now; anything other than {1, 0} means it claimed one, and
171+
--- moving would fight the user's own config. The exception is a claim inside
172+
--- the template's preamble, which is generated boilerplate rather than
173+
--- somewhere they chose to be.
160174
---
161-
--- `force` skips that guard, for callers that just REWROTE the buffer
162-
--- (`:CW template on`): the old position points into the template's
163-
--- preamble, so there is nothing worth preserving.
175+
--- `force` skips the claim check entirely, for the three callers that just
176+
--- REWROTE the buffer -- `:CW template on`, `:CW template off`, `:CW reset`.
177+
--- After a rewrite the old position describes a buffer that no longer exists.
164178
---@param force boolean?
165179
function Kata:_cursor_to_end(force)
166180
if not (self.winid and vim.api.nvim_win_is_valid(self.winid)) then
167181
return
168182
end
169183

170-
-- The buffer's untouched position is {1, 0}. Testing the row alone would
171-
-- override a restore to {1, 12}, which is every bit as much a claim.
172184
local ok, pos = pcall(vim.api.nvim_win_get_cursor, self.winid)
173-
if not ok or (not force and (pos[1] ~= 1 or pos[2] ~= 0)) then
185+
if not ok then
186+
return
187+
end
188+
189+
local target = self:_locate_starter()
190+
-- Testing the row alone would override a restore to {1, 12}, which is
191+
-- every bit as much a claim as one on another line.
192+
local claimed = pos[1] ~= 1 or pos[2] ~= 0
193+
local in_preamble = target
194+
and (pos[1] < target.start_row
195+
or (pos[1] == target.start_row and pos[2] < target.start_col))
196+
if not force and claimed and not in_preamble then
174197
return
175198
end
176199

177-
local last = vim.api.nvim_buf_line_count(self.bufnr)
178-
local text = vim.api.nvim_buf_get_lines(self.bufnr, last - 1, last, false)[1] or ""
179-
pcall(vim.api.nvim_win_set_cursor, self.winid, { last, #text })
200+
local row, col
201+
if target then
202+
row, col = target.row, target.col
203+
else
204+
-- No template to measure against, so the code is the whole buffer.
205+
-- end_of applies the same rule the templated path uses: trailing blank
206+
-- lines are not the last thing the user wrote, and the column lands on
207+
-- a character rather than inside a multibyte one.
208+
row, col = require("codewars.templates").end_of(self:_buffer_text())
209+
end
210+
211+
pcall(vim.api.nvim_win_set_cursor, self.winid, { row, col })
212+
self:_show_around_cursor()
213+
end
214+
215+
--- Put the cursor back on the starter once the panels have taken their space.
216+
---
217+
--- Re-placed only when the starter can actually be found: on a buffer that no
218+
--- longer matches the template there is nothing to aim at, and whatever
219+
--- position it already had is better than a guess. The view is squared up
220+
--- either way, since the resize is what moved it.
221+
function Kata:_settle_cursor()
222+
if not (self.winid and vim.api.nvim_win_is_valid(self.winid)) then
223+
return
224+
end
225+
226+
local target = self:_locate_starter()
227+
if target and target.row then
228+
pcall(vim.api.nvim_win_set_cursor, self.winid, { target.row, target.col })
229+
end
230+
self:_show_around_cursor()
231+
end
232+
233+
--- Fill the panel with the lines leading up to the cursor.
234+
---
235+
--- Moving the cursor scrolls DOWN to reveal it, never back up. A rewrite that
236+
--- shrinks the buffer -- `:CW template off` dropping a long preamble -- leaves
237+
--- the window parked at a top line that is now near the end, so the panel
238+
--- shows the last line or two of the file and nothing else.
239+
function Kata:_show_around_cursor()
240+
if not (self.winid and vim.api.nvim_win_is_valid(self.winid)) then
241+
return
242+
end
243+
-- `zb` rather than `zz`: at the end of a buffer, centring would waste half
244+
-- the panel on the blank space past it.
245+
pcall(vim.api.nvim_win_call, self.winid, function()
246+
vim.cmd("normal! zb")
247+
end)
180248
end
181249

182250
--- Give up on this mount: no window will ever exist, so drop the one-shot
@@ -366,6 +434,15 @@ function Kata:handle_mount()
366434
if not ok then log.debug("kata on_mounted hook failed: " .. tostring(err)) end
367435
end
368436

437+
-- Last, and scheduled: create_buffer placed the cursor against a
438+
-- full-height window, and everything since -- both splits, the console
439+
-- layout, the autocmds, the caller's own hook -- has taken space from it
440+
-- or moved through it. A position measured before all that leaves the
441+
-- panel scrolled somewhere the starter is not.
442+
vim.schedule(function()
443+
self:_settle_cursor()
444+
end)
445+
369446
utils.exec_hooks("kata_enter", self)
370447
end
371448

@@ -458,6 +535,9 @@ end
458535
function Kata:reset_code()
459536
if self.bufnr and vim.api.nvim_buf_is_valid(self.bufnr) then
460537
self:_set_code(self:_starter_code())
538+
-- Forced: the rewrite moved the user's code out from under wherever
539+
-- they were standing, so the old position is not a claim on anything.
540+
self:_cursor_to_end(true)
461541
log.info("Code reset to template")
462542
end
463543
end

0 commit comments

Comments
 (0)