Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Context pack

Issue #2632, draft PR #2640. Base b0eb079575968e843b781579673c9fe2ae250e07.
Implementation and regression tests complete. Tests failed on main (10 failures) and pass after the fix (20/20). Scoped check/lint/fmt, quality:gate, release:preflight, docs:accuracy and JSR audit pass.
Full package doc lint reports 47 diagnostics in unchanged surfaces; form entrypoint has zero.
Next: independent IMPL-EVAL, resolve findings, update body evidence, ready-for-review transition, verify required head checks and review-thread gate.
No merge, auto-merge, status:ready-merge or publication. Keep public artifacts free of operator paths and session IDs.

Independent IMPL-EVAL PASS: https://github.com/rickylabs/netscript/pull/2640#issuecomment-6922841910. Evaluator independently reproduced 10 failures before the reader change and 20/20 focused plus 315/315 Fresh source tests after it. Full doc-lint diagnostic distribution matches the base exactly. Refreshed the one-line public reference summary as requested. Source implementation is unchanged since evaluation. CI path policy will run scaffold/static/runtime and Fresh browser tiers after ready_for_review despite local CLI E2E being outside this parser fix's gate selection.

CI quality follow-up regenerated the prose carrier for the changed reference sentence. Only the Fresh reference page and derived llms-full change after decoding. Corpus freshness and release preflight pass under pinned Deno 2.9.7. Push refreshes CI; final head checks still need verification.

Required CI also checks the MCP export-surface corpus generated from JSDoc. Refreshed the generated carrier with the canonical tool; final head CI remains pending.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Drift

- Environment: rtk and rg are unavailable; use direct commands and focused find/grep.
- Commands already execute as the node user. Deno 2.9.5 does not accept `deno task --user`; agentic:matrix succeeds as node without that flag.
- The owner selected the existing Sol xhigh implementation session; the simple row's low implementation default does not replace that session.
- Full package doc-lint reports 47 diagnostics in unchanged public surfaces; the changed form entrypoint passes. No broad documentation refactor is included in the parser fix.
140 changes: 140 additions & 0 deletions .llm/runs/fix-fresh-malformed-csrf-cookie--issue-2632/evaluate.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions .llm/runs/fix-fresh-malformed-csrf-cookie--issue-2632/plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Plan

Fix malformed Cookie handling in the existing form CSRF reader only. Preserve `readCsrfToken(request): string | undefined`; a Cookie parser SyntaxError maps to undefined, other exceptions propagate.

LOCKED: use the existing missing-token path for POST rejection and GET renewal. Do not weaken token verification or change response status conventions.
Open decisions: none. Risk: swallowing unrelated failures; catch SyntaxError specifically.
Archetype 4 + frontend overlay; AP-1/AP-14/AP-25 in scope. No new layers, ports or architectural debt.
Slices: (1) bootstrap plan, (2) failing reader and GET/POST regression tests, reader correction and scoped gates, (3) separate-session evaluation and review handoff.
Gates: structured test/check/lint/fmt; quality:scan and arch:check; JSR audit and doc lint; release:preflight; docs:accuracy. CLI E2E N/A: no scaffold, Aspire helper or runtime wiring changes. Server-rendered form seam tests exercise route output; no visual behavior changes.
Deferred: all other milestone issues and the excluded saga transports.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Research

Read issue #2632 in full after fetching origin. Current main matches its evidence baseline.
`readCsrfToken` directly calls `getCookies`; POST reads it before the CSRF opt-out and the GET loader reads it when generating the form state.
The existing `string | undefined` contract already represents a missing token. No export or dependency changes are needed.
Archetype 4 (builder) with frontend overlay. Current doctrine verdict for fresh: Keep; existing route documentation debt is outside this fix.
JSR surface review: unchanged explicit return type, named exports and package export map; no new slow types.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Implementation lane

Issue: #2632. Branch: `fix/fresh-malformed-csrf-cookie`. Base: `origin/main` at b0eb079575968e843b781579673c9fe2ae250e07.
Generator: Codex, gpt-6.1-sol, xhigh; owner-selected existing implementation session.
Workload tier: simple; role: implementation. IMPL-EVAL matrix: minimax_m3/provider_default, fallback deepseek_v4_flash/provider_default, separate session and vendor family required.
Evaluator route will be recorded when launched. No sign-off is claimed by the implementation lane.
Operator paths and session identities are omitted under the owner's public-repository restriction.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Worklog

## Design

Public surface: unchanged definePage().withForm(...).build() and `readCsrfToken` return type. Domain: existing optional cookie token and form result statuses. Ports/constants: none added; retain CSRF_COOKIE_NAME.
Cookie parsing is the validation boundary. Malformed headers yield no token and use existing form behavior.
Slices and gates are listed in plan.md. Contributor path: `form/validation/csrf.ts` plus its colocated tests and `define-page/tests/runtime.test.tsx`.
PLAN-EVAL: N/A — bounded parser error correction; acceptance specifies all behavior and there is no new public contract or unresolved design tradeoff.

## Evidence

Bootstrap complete; reproduction and implementation pending. Tests will be written and run before the reader changes.

## Implementation evidence

Production correction: catch only cookie parser SyntaxError; unrelated errors still propagate. No public type, export or dependency changes.

| Gate | Result |
| --- | --- |
| Structured focused tests before reader change | exit 1; 10 pass, 10 fail with Cookie parser SyntaxError (unit, GET and both POST modes) |
| Same tests after reader change | exit 0; 20 pass, 0 fail |
| Structured check (3 files; wrapper defaults to --unstable-kv) | exit 0, no diagnostics |
| Structured lint / fmt (same 3 files) | exit 0 / exit 0 |
| quality:gate (quality:scan + arch:check including deps:check) | exit 0 |
| release:preflight | exit 0 |
| docs:accuracy | exit 0 |
| JSR audit / dry-run | exit 0; existing AI directory cardinality warning and banner-only slow-type warning |
| Full export-map doc:lint | exit 1; 47 diagnostics in unchanged builder/query/route/AI/streams surfaces; form entrypoint has zero |

Raw operator paths were not retained. Targeted tests assert rendered GET status/cookie/body and POST form results without starting a server.
Reconcile: issue remains open; no new comments at implementation start. Draft PR #2640 targets main with milestone 0.0.10. Independent evaluation remains required; this is an implementation commit, not supervisor sign-off.

Independent IMPL-EVAL PASS: https://github.com/rickylabs/netscript/pull/2640#issuecomment-6922841910. Evaluator independently reproduced 10 failures before the reader change and 20/20 focused plus 315/315 Fresh source tests after it. Full doc-lint diagnostic distribution matches the base exactly. Refreshed the one-line public reference summary as requested. Source implementation is unchanged since evaluation. CI path policy will run scaffold/static/runtime and Fresh browser tiers after ready_for_review despite local CLI E2E being outside this parser fix's gate selection.

## CI corpus follow-up

Required CI quality failed because the reference wording changed the shipped prose corpus. Ran the canonical gen:agent-docs-prose with the repository-pinned Deno 2.9.7, then gen:assets-barrel. Only the prose carrier changed. Decoded before/after comparison proves the only changed page is pages/reference/fresh/index.md and its derived llms-full.txt. Freshness check reports fresh=true, stalePaths=[]; release:preflight passes. No lock changes. The shell default Deno 2.9.5 cannot build this docs pipeline due to CLI option parsing; subsequent generation uses mise exec deno@2.9.7. Implementation source remains unchanged since independent PASS.

## CI export-corpus follow-up

The next required quality run exposed the second generated consumer of the updated JSDoc: MCP export-surface corpus freshness. Ran canonical gen:mcp-export-corpus under Deno 2.9.7. Only the pre-existing generated export-corpus carrier changed; no product behavior, type, lock or command changes. The canonical freshness check is rerun before pushing. These generated documentation carriers are necessary parts of the same CSRF documentation correction.

Export-corpus check: exit 0. Row comparison proves exactly one changed surface: fresh ./form; no added or removed surfaces.

Required CI then identified the publish-assets wrapper containing the refreshed MCP corpora. Ran gen:publish-assets and check:publish-assets on Deno 2.9.7; both pass. Only packages/mcp/src/publish-assets.generated.ts changed (two embedded documentation carriers). This completes the generator dependency chain; implementation source remains unchanged.
2 changes: 1 addition & 1 deletion docs/site/reference/fresh/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ Managed forms: CSRF, intents, progressive enhancement, pagination, and Standard
| `getSubmissionHiddenInputProps` | function | `getSubmissionHiddenInputProps(submissionId: string)` | Return the hidden input props for carrying an idempotent submission id. |
| `normalizeFormValues` | function | `normalizeFormValues(rawValues: Record): Partial` | Normalize raw form values by converting empty strings to `undefined`. |
| `parseFormIntent` | function | `parseFormIntent(rawValues: Record)` | Parse an encoded form intent from raw posted values. |
| `readCsrfToken` | function | `readCsrfToken(request: Request)` | Read the current CSRF token from a request cookie header. |
| `readCsrfToken` | function | `readCsrfToken(request: Request)` | Read the current CSRF token, treating malformed cookies as a missing token. |
| `resolveFormState` | function | `resolveFormState(data: unknown, _): FormState` | Resolve form state from route handler data. |
| `resolvePagination` | function | `resolvePagination(searchParams: URLSearchParams, defaultLimit: number): PaginationInput` | Resolve pagination input from URLSearchParams. |
| `setCsrfCookie` | function | `setCsrfCookie(headers: Headers, token: string, requestUrl?: URL): void` | Set the CSRF cookie on response headers. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,3 +368,77 @@ Deno.test('definePage withForm applies collection intents before returning runti
'Expected runtime field descriptors to expose the added row',
);
});

for (const cookie of ['', '=x', 'a=1;=x']) {
Deno.test(`definePage withForm renews a malformed Cookie on GET: ${cookie}`, async () => {
let snapshot: RuntimeFormState<{ name?: string }> | undefined;
const route = definePage<{ requestId: string }>()
.withForm('form', () => <form />, {
schema: z.object({ name: z.string().optional() }),
mutate: () => ({ id: 1 }),
})
.withLayout((slots, { layerData }) => {
snapshot = layerData.form;
return <main>{slots.form()}</main>;
})
.build();
assert(route.handler?.GET, 'Expected GET handler');

const response = await route.handler.GET({
...createRequestContext({
req: new Request('http://localhost/dashboard/users', { headers: { cookie } }),
}),
render(body: unknown, init?: ResponseInit) {
return new Response(renderToString(body as Parameters<typeof renderToString>[0]), init);
},
});

assert(response instanceof Response && response.status === 200, 'Expected GET to render');
assert(snapshot, 'Expected form state');
const token = snapshot.csrfInputProps.value;
assert(typeof token === 'string' && token.length > 0, 'Expected a fresh token');
assert(
response.headers.get('set-cookie')?.includes(`${CSRF_COOKIE_NAME}=${token}`),
'Expected fresh token cookie',
);
assert((await response.text()).includes('<form'), 'Expected rendered form');
});

for (const csrf of [true, false]) {
Deno.test(`definePage withForm handles malformed Cookie on POST with csrf=${csrf}: ${cookie}`, async () => {
let mutateCalled = false;
const schema = z.object({ name: z.string() });
const route = definePage<{ requestId: string }>()
.withForm('form', () => <form />, {
schema,
csrf,
mutate: () => {
mutateCalled = true;
return { id: 1 };
},
})
.build();
assert(route.handler?.POST, 'Expected POST handler');
const formData = new FormData();
formData.set('name', 'Ada');
const result = await route.handler.POST(createRequestContext({
req: new Request('http://localhost/dashboard/users', {
method: 'POST',
headers: { cookie },
body: formData,
}),
}));

assert(!(result instanceof Response), 'Expected form result');
const data = result.data as FormSubmissionResult<z.input<typeof schema>, { id: number }>;
assert(mutateCalled === !csrf, 'Expected mutation only when CSRF is disabled');
assert(data.status === (csrf ? 'error' : 'success'), 'Expected CSRF rejection or success');
if (csrf) {
assert(
data.formErrors.includes('Your form session expired. Reload the page and try again.'),
'Expected existing CSRF rejection message',
);
}
});
}
}
9 changes: 9 additions & 0 deletions packages/fresh/src/application/form/validation/csrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,12 @@ Deno.test('readCsrfToken reads the token from request cookies', () => {

assertEquals(readCsrfToken(request), 'csrf-1');
});

Deno.test('readCsrfToken treats malformed Cookie headers as a missing token', () => {
for (const cookie of ['', '=x', 'a=1;=x', `${CSRF_COOKIE_NAME}=csrf-1;=x`]) {
const request = new Request('https://example.com/forms', { headers: { cookie } });

assertEquals(readCsrfToken(request), undefined, `Cookie: ${cookie}`);
}
assertEquals(readCsrfToken(new Request('https://example.com/forms')), undefined);
});
9 changes: 7 additions & 2 deletions packages/fresh/src/application/form/validation/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@ export function generateCsrfToken(): string {
return crypto.randomUUID();
}

/** Read the current CSRF token from a request cookie header. */
/** Read the current CSRF token, treating malformed cookies as a missing token. */
export function readCsrfToken(request: Request): string | undefined {
return getCookies(request.headers)[CSRF_COOKIE_NAME];
try {
return getCookies(request.headers)[CSRF_COOKIE_NAME];
} catch (error) {
if (error instanceof SyntaxError) return undefined;
throw error;
}
}

/** Verify that the submitted token matches the cookie token. */
Expand Down

Large diffs are not rendered by default.

Loading
Loading