knowless 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -15,6 +15,54 @@ Versioning is [SemVer](https://semver.org/).
15
15
  sham mail, SPF/DKIM/PTR, reverse-proxy configs for Caddy / nginx /
16
16
  Traefik). (Tracked in TASKS.md Phase 7.)
17
17
 
18
+ ## [0.1.1] — 2026-04-29
19
+
20
+ First-customer scope (the webrevival forum) review identified one
21
+ ergonomic gap and elevated three P1 hardening items to "must ship
22
+ before first real use." All five closed in this release.
23
+
24
+ ### Added
25
+
26
+ - `auth.handleFromRequest(req)` — programmatic session resolution
27
+ for in-process middleware. Returns `string | null` (handle on
28
+ valid session, null on any failure). Recommended integration
29
+ point for Express / Fastify / Hono `requireAuth` middleware. SPEC
30
+ §9.4. Closes AF-2.8.
31
+ - `cookieSecure` config option (default `true`). Operators MAY set
32
+ `false` for `http://localhost` development; the library emits a
33
+ stderr warning at startup. MUST NOT be `false` in production.
34
+ SPEC §5.4. PRD FR-30 revised. Closes AF-4.4.
35
+
36
+ ### Security
37
+
38
+ - **CSRF defense on `POST /login`.** New Origin/Referer header
39
+ validation as Step 0 of the login flow. Both headers absent →
40
+ allow (curl, programmatic). Either present → host must equal
41
+ `cookieDomain` or be a subdomain. Cross-origin / unparseable →
42
+ silent short-circuit, no DB write, no mail. Same response shape
43
+ as a legitimate hit, so the attacker's measurement learns
44
+ nothing the request shape didn't already expose. SPEC §7.3 Step
45
+ 0. Closes AF-4.3, resolves SPEC §15 Q-4.
46
+
47
+ ### Tests
48
+
49
+ - AF-4.1: concurrent token issuance under cap contention.
50
+ 10-parallel logins with `maxActiveTokensPerHandle=3` must end at
51
+ exactly 3 active rows. Pins the SPEC §4.7 BEGIN IMMEDIATE
52
+ contract.
53
+ - AF-4.2: SMTP-failure response-uniformity test. Stubs
54
+ `mailer.submit` to throw and asserts the response shape is
55
+ identical to a successful login. Pins NFR-10.
56
+ - 12 new tests total. 122 tests passing on Node 20+.
57
+
58
+ ### Notes
59
+
60
+ The published `0.1.0` does not have these. Adopters who installed
61
+ `0.1.0` should `npm update knowless` to pick up the CSRF defense
62
+ and the localhost-dev-friendly cookieSecure option.
63
+
64
+ [0.1.1]: https://github.com/hamr0/knowless/releases/tag/v0.1.1
65
+
18
66
  ## [0.1.0] — 2026-04-28
19
67
 
20
68
  First public release. Library-mode auth flow is complete and
@@ -138,5 +186,5 @@ Two primary audiences (PRD §4):
138
186
 
139
187
  Apache 2.0 with NOTICE preservation. See `LICENSE` and `NOTICE`.
140
188
 
141
- [Unreleased]: https://github.com/hamr0/knowless/compare/v0.1.0...HEAD
189
+ [Unreleased]: https://github.com/hamr0/knowless/compare/v0.1.1...HEAD
142
190
  [0.1.0]: https://github.com/hamr0/knowless/releases/tag/v0.1.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knowless",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Small, opinionated, full-stack passwordless auth for Node.js services that don't need to email their users for anything but the sign-in link.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/handlers.js CHANGED
@@ -32,6 +32,7 @@ const DEFAULTS = {
32
32
  shamRecipient: 'null@knowless.invalid',
33
33
  trustedProxies: ['127.0.0.1', '::1', '::ffff:127.0.0.1'],
34
34
  failureRedirect: null,
35
+ cookieSecure: true,
35
36
  };
36
37
 
37
38
  /**
@@ -84,6 +85,38 @@ function getCookie(req, name) {
84
85
  return null;
85
86
  }
86
87
 
88
+ /**
89
+ * Validate the request's Origin/Referer header against the cookie
90
+ * domain whitelist per SPEC §7.3 Step 0 (AF-4.3, CSRF defense).
91
+ *
92
+ * - Both headers absent → allow (curl, fetch without CORS, programmatic
93
+ * clients). Browsers always send Origin on cross-origin POST.
94
+ * - Either present → parse and require host == cookieDomain or
95
+ * .endsWith('.' + cookieDomain). Same whitelist as the next-URL
96
+ * check in §11.2.
97
+ * - Unparseable URL or non-matching host → reject.
98
+ *
99
+ * Origin is preferred when both are present (it's harder to spoof and
100
+ * more reliably set by browsers on POST).
101
+ */
102
+ function validateOrigin(req, cookieDomain) {
103
+ const origin = req.headers?.origin;
104
+ const referer = req.headers?.referer ?? req.headers?.referrer;
105
+ const candidate = origin ?? referer;
106
+ if (!candidate) return true;
107
+ if (typeof candidate !== 'string') return false;
108
+ let parsed;
109
+ try {
110
+ parsed = new URL(candidate);
111
+ } catch {
112
+ return false;
113
+ }
114
+ const host = parsed.hostname.toLowerCase();
115
+ if (!host) return false;
116
+ const dom = cookieDomain.toLowerCase();
117
+ return host === dom || host.endsWith('.' + dom);
118
+ }
119
+
87
120
  /**
88
121
  * Validate the `next` URL per SPEC §11.2.
89
122
  * @param {string|null|undefined} rawNext
@@ -147,6 +180,12 @@ export function createHandlers({ store, mailer, config }) {
147
180
 
148
181
  const trustedProxies = new Set(cfg.trustedProxies);
149
182
 
183
+ // SPEC §5.4 / FR-30: build the cookie-attribute suffix once. Secure is
184
+ // emitted by default and omitted only when cookieSecure: false (localhost
185
+ // dev). HttpOnly + SameSite=Lax are always set.
186
+ const secureAttr = cfg.cookieSecure ? '; Secure' : '';
187
+ const setCookieAttrs = `Domain=${cfg.cookieDomain}; Path=/; HttpOnly; SameSite=Lax`;
188
+
150
189
  function sameResponse(res, echoedEmail, next) {
151
190
  const html = renderLoginForm({
152
191
  loginPath: cfg.loginPath,
@@ -168,6 +207,15 @@ export function createHandlers({ store, mailer, config }) {
168
207
  }
169
208
 
170
209
  async function login(req, res) {
210
+ // Step 0 — Origin / Referer validation (SPEC §7.3 Step 0, AF-4.3).
211
+ // CSRF defense: a malicious cross-origin page autosubmitting to /login
212
+ // would otherwise trigger magic-link sends to known emails. Exempt
213
+ // from FR-6 timing equivalence per SPEC §7.3.
214
+ if (!validateOrigin(req, cfg.cookieDomain)) {
215
+ sameResponse(res, '', '');
216
+ return;
217
+ }
218
+
171
219
  let raw;
172
220
  try {
173
221
  raw = await readBody(req);
@@ -312,33 +360,42 @@ export function createHandlers({ store, mailer, config }) {
312
360
  res.statusCode = 302;
313
361
  res.setHeader(
314
362
  'Set-Cookie',
315
- `${cfg.cookieName}=${cookie}; Domain=${cfg.cookieDomain}; Path=/; Max-Age=${cfg.sessionTtlSeconds}; Secure; HttpOnly; SameSite=Lax`,
363
+ `${cfg.cookieName}=${cookie}; ${setCookieAttrs}; Max-Age=${cfg.sessionTtlSeconds}${secureAttr}`,
316
364
  );
317
365
  res.setHeader('Location', row.nextUrl ?? `${cfg.baseUrl}/`);
318
366
  res.end();
319
367
  }
320
368
 
321
- function verify(req, res) {
369
+ /**
370
+ * Programmatic session resolution per SPEC §9.4. Reads the
371
+ * configured cookie from the request, validates its signature,
372
+ * looks up the session row, and returns the handle. Returns
373
+ * null on any failure (missing/malformed cookie, signature
374
+ * mismatch, expired session, no row). Recommended integration
375
+ * point for in-process middleware. Closes AF-2.8.
376
+ *
377
+ * @param {{ headers?: { cookie?: string } }} req
378
+ * @returns {string | null}
379
+ */
380
+ function handleFromRequest(req) {
322
381
  const cookie = getCookie(req, cfg.cookieName);
323
- if (!cookie) {
324
- res.statusCode = 401;
325
- res.end();
326
- return;
327
- }
382
+ if (!cookie) return null;
328
383
  const sid = verifySessionSignature(cookie, cfg.secret);
329
- if (!sid) {
330
- res.statusCode = 401;
331
- res.end();
332
- return;
333
- }
384
+ if (!sid) return null;
334
385
  const row = store.getSession(sidHashOf(sid));
335
- if (!row || row.expiresAt <= Date.now()) {
386
+ if (!row || row.expiresAt <= Date.now()) return null;
387
+ return row.handle;
388
+ }
389
+
390
+ function verify(req, res) {
391
+ const handle = handleFromRequest(req);
392
+ if (!handle) {
336
393
  res.statusCode = 401;
337
394
  res.end();
338
395
  return;
339
396
  }
340
397
  res.statusCode = 200;
341
- res.setHeader('X-User-Handle', row.handle);
398
+ res.setHeader('X-User-Handle', handle);
342
399
  res.end();
343
400
  }
344
401
 
@@ -351,7 +408,7 @@ export function createHandlers({ store, mailer, config }) {
351
408
  res.statusCode = 200;
352
409
  res.setHeader(
353
410
  'Set-Cookie',
354
- `${cfg.cookieName}=; Domain=${cfg.cookieDomain}; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax`,
411
+ `${cfg.cookieName}=; ${setCookieAttrs}; Max-Age=0${secureAttr}`,
355
412
  );
356
413
  res.end();
357
414
  }
@@ -376,6 +433,7 @@ export function createHandlers({ store, mailer, config }) {
376
433
  verify,
377
434
  logout,
378
435
  loginForm,
436
+ handleFromRequest,
379
437
  validateNextUrl: (raw) => validateNextUrl(raw, cfg.baseUrl, cfg.cookieDomain),
380
438
  // exposed for tests
381
439
  _config: cfg,
package/src/index.js CHANGED
@@ -76,6 +76,16 @@ export function knowless(options = {}) {
76
76
  throw new Error('knowless: secret must be at least 64 hex chars (32 bytes)');
77
77
  }
78
78
 
79
+ // SPEC §5.4: cookieSecure: false is allowed only for localhost dev.
80
+ // The library can't tell whether the operator is in production, but a
81
+ // visible warning makes it harder to ship by accident.
82
+ if (options.cookieSecure === false) {
83
+ console.warn(
84
+ '[knowless] WARNING: cookieSecure is false. Session cookies will be set without the Secure flag. ' +
85
+ 'This is only safe for http://localhost development. Never deploy with cookieSecure: false.',
86
+ );
87
+ }
88
+
79
89
  const store = options.store ?? createStore(options.dbPath ?? './knowless.db');
80
90
 
81
91
  const mailer =
@@ -109,6 +119,8 @@ export function knowless(options = {}) {
109
119
  verify: handlers.verify,
110
120
  logout: handlers.logout,
111
121
  loginForm: handlers.loginForm,
122
+ /** Resolve handle from request cookie programmatically (SPEC §9.4). */
123
+ handleFromRequest: handlers.handleFromRequest,
112
124
  /** Delete a handle + all tokens + all sessions atomically (FR-37a). */
113
125
  deleteHandle: (handle) => store.deleteHandle(handle),
114
126
  /** Effective config (with defaults applied), useful for routing. */
package/src/mailer.js CHANGED
@@ -19,6 +19,22 @@ const ASCII_RE = /^[\x00-\x7f]*$/;
19
19
  * @returns {string} RFC822 message with CRLF line endings
20
20
  */
21
21
  function composeRaw({ from, to, subject, body }) {
22
+ // AF-2.1: header-injection defense in depth. normalize() upstream
23
+ // already rejects \r and \n in email addresses, but the mailer
24
+ // shouldn't trust its callers — this is the layer that emits the
25
+ // wire-format bytes, so it owns the invariant.
26
+ for (const [name, value] of [
27
+ ['from', from],
28
+ ['to', to],
29
+ ['subject', subject],
30
+ ]) {
31
+ if (typeof value !== 'string') {
32
+ throw new Error(`mailer: ${name} must be a string`);
33
+ }
34
+ if (/[\r\n]/.test(value)) {
35
+ throw new Error(`mailer: ${name} contains CR/LF — header injection blocked`);
36
+ }
37
+ }
22
38
  const fromDomain = from.includes('@') ? from.split('@').pop() : 'localhost';
23
39
  const messageId = `<${crypto.randomUUID()}@${fromDomain}>`;
24
40
  const date = new Date().toUTCString();