@kabmo-labs/kabmo-auth 0.0.0-stage → 1.1.0

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/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@kabmo-labs/kabmo-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "description": "UI password generation, account store, session tokens and the auth gate primitives.",
6
+ "exports": {
7
+ ".": "./src/password.ts",
8
+ "./account": "./src/account.ts",
9
+ "./server/accounts": "./src/server/accounts.ts",
10
+ "./server/client-address": "./src/server/client-address.ts",
11
+ "./server/config": "./src/server/config.ts",
12
+ "./server/public-paths": "./src/server/public-paths.ts",
13
+ "./server/rate-limit": "./src/server/rate-limit.ts",
14
+ "./server/token": "./src/server/token.ts"
15
+ },
16
+ "files": [
17
+ "src"
18
+ ],
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/kabmo-labs/kabmo.git",
23
+ "directory": "packages/kabmo-auth"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "engines": {
29
+ "bun": ">=1.4.0"
30
+ },
31
+ "dependencies": {
32
+ "@kabmo-labs/kabmo-db": "1.0.0",
33
+ "@kabmo-labs/kabmo-paths": "1.0.0"
34
+ }
35
+ }
package/src/account.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /** A person who can sign in to this Kabmo instance. */
7
+ export type AccountRole = 'root' | 'member';
8
+
9
+ /** The identity facts shared by the login picker, the navbar and settings. */
10
+ export interface AccountSummary {
11
+ id: string;
12
+ name: string;
13
+ role: AccountRole;
14
+ }
15
+
16
+ /** One row in Settings → Accounts. */
17
+ export interface AccountListItem extends AccountSummary {
18
+ createdAt: string | null;
19
+ /** Workspaces this account owns. */
20
+ ownedWorkspaces: number;
21
+ /** Workspaces owned by someone else and shared with this account. */
22
+ sharedWorkspaces: number;
23
+ }
24
+
25
+ /** An account a workspace is shared with. */
26
+ export interface AccountShare {
27
+ accountId: string;
28
+ name: string;
29
+ role: AccountRole;
30
+ }
31
+
32
+ /** What `GET /api/accounts` answers. */
33
+ export interface AccountsPayload {
34
+ enabled: boolean;
35
+ currentAccountId: string;
36
+ accounts: AccountListItem[];
37
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The generated UI password, shared by the CLI (which mints one for
8
+ * `--ui-password` with no value) and anything else that needs to offer one.
9
+ *
10
+ * The alphabet deliberately omits the characters a person confuses when reading
11
+ * a password off one screen and typing it into another: `I`/`O` (against `1`/`0`)
12
+ * and `i`/`l`/`o` (against each other). What is left is 55 unambiguous
13
+ * characters, which is what makes the value safe to transcribe from a terminal
14
+ * onto a phone.
15
+ *
16
+ * `crypto.getRandomValues` rather than a `node:crypto` import: it is a global in
17
+ * both Bun and the browser, so this module stays importable from either side.
18
+ */
19
+
20
+ /** Every character a generated password may contain (55 of them). */
21
+ export const PASSWORD_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
22
+
23
+ /**
24
+ * The environment variable that configures the UI password.
25
+ *
26
+ * Lives here, in the dependency-free module, rather than beside the code that
27
+ * applies it: the guard needs to name it for the boot banner, and the guard is
28
+ * imported by that same module — naming it here is what keeps the two from
29
+ * needing a circular import.
30
+ */
31
+ export const UI_PASSWORD_ENV = 'KABMO_UI_PASSWORD';
32
+
33
+ /** The pre-rename spelling, still read so an exported password keeps working. */
34
+ export const LEGACY_UI_PASSWORD_ENV = 'OMPCHAMBER_UI_PASSWORD';
35
+
36
+ /** Length of a generated password — 16 characters is ~92 bits over this alphabet. */
37
+ export const GENERATED_PASSWORD_LENGTH = 16;
38
+
39
+ /**
40
+ * Random bytes with the modulo bias removed.
41
+ *
42
+ * `bytes[i] % alphabet.length` alone would over-represent the first
43
+ * `256 % 55 = 36` characters, since 256 is not a multiple of 55. Bytes at or
44
+ * above the largest multiple of the alphabet size are discarded and redrawn
45
+ * instead, which makes every character equally likely.
46
+ */
47
+ function unbiasedBytes(length: number, alphabetLength: number): Uint8Array {
48
+ const limit = 256 - (256 % alphabetLength);
49
+ const out = new Uint8Array(length);
50
+ const buffer = new Uint8Array(length * 2);
51
+ let filled = 0;
52
+
53
+ while (filled < length) {
54
+ crypto.getRandomValues(buffer);
55
+ for (const byte of buffer) {
56
+ if (byte >= limit) continue;
57
+ out[filled] = byte % alphabetLength;
58
+ filled += 1;
59
+ if (filled === length) break;
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** A fresh password from `PASSWORD_ALPHABET`, `length` characters long. */
66
+ export function generatePassword(length: number = GENERATED_PASSWORD_LENGTH): string {
67
+ const size = Number.isFinite(length) && length > 0 ? Math.floor(length) : GENERATED_PASSWORD_LENGTH;
68
+ const indices = unbiasedBytes(size, PASSWORD_ALPHABET.length);
69
+ let password = '';
70
+ for (const index of indices) password += PASSWORD_ALPHABET[index];
71
+ return password;
72
+ }
@@ -0,0 +1,293 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Sign-in accounts, cached for the synchronous auth gate.
8
+ *
9
+ * The root account's password never lives here: it comes from `--ui-password`
10
+ * for the running process, exactly as before. A member account stores an
11
+ * argon2id hash and a deterministic credential key, so restarting the server
12
+ * keeps its sessions and a reset invalidates only that account's cookies.
13
+ *
14
+ * The cache is on `globalThis` for the same reason the database handle is:
15
+ * `bun --hot` re-evaluates this module while the gate that reads it lives on.
16
+ */
17
+
18
+ import type { DbClient } from '@kabmo-labs/kabmo-db/client';
19
+ import { getDb } from '@kabmo-labs/kabmo-db/lifecycle';
20
+ import { deriveCredentialKey, hashPassword } from './config';
21
+ import type { AccountListItem, AccountRole, AccountSummary } from '../account';
22
+
23
+ export const ROOT_ACCOUNT_ID = 'root';
24
+ export const ROOT_DEFAULT_NAME = 'Owner';
25
+ export const MIN_ACCOUNT_NAME_LENGTH = 1;
26
+ export const MAX_ACCOUNT_NAME_LENGTH = 40;
27
+
28
+ export interface AccountRecord {
29
+ id: string;
30
+ name: string;
31
+ role: AccountRole;
32
+ passwordHash: string | null;
33
+ credentialKey: string | null;
34
+ sessionEpoch: number;
35
+ createdAt: string | null;
36
+ }
37
+
38
+ interface AccountRow {
39
+ id: string;
40
+ name: string;
41
+ role: string;
42
+ password_hash: string | null;
43
+ credential_key: string | null;
44
+ session_epoch: number;
45
+ created_at: string | null;
46
+ }
47
+
48
+ declare global {
49
+ // eslint-disable-next-line no-var
50
+ var __kabmoAccountCache: Map<string, AccountRecord> | undefined;
51
+ }
52
+
53
+ const ROOT_FALLBACK: AccountRecord = {
54
+ id: ROOT_ACCOUNT_ID,
55
+ name: ROOT_DEFAULT_NAME,
56
+ role: 'root',
57
+ passwordHash: null,
58
+ credentialKey: null,
59
+ sessionEpoch: 0,
60
+ createdAt: null,
61
+ };
62
+
63
+ function cache(): Map<string, AccountRecord> | undefined {
64
+ return globalThis.__kabmoAccountCache;
65
+ }
66
+
67
+ function toRecord(row: AccountRow): AccountRecord {
68
+ return {
69
+ id: row.id,
70
+ name: row.name,
71
+ role: row.role === 'root' ? 'root' : 'member',
72
+ passwordHash: row.password_hash,
73
+ credentialKey: row.credential_key,
74
+ sessionEpoch: Number.isFinite(row.session_epoch) ? row.session_epoch : 0,
75
+ createdAt: row.created_at,
76
+ };
77
+ }
78
+
79
+ /** Create the table and seed the one account `--ui-password` signs in as. */
80
+ export async function ensureAccountsSchema(db: DbClient): Promise<void> {
81
+ await db.exec(`
82
+ CREATE TABLE IF NOT EXISTS accounts (
83
+ id TEXT PRIMARY KEY,
84
+ name TEXT NOT NULL,
85
+ role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('root', 'member')),
86
+ password_hash TEXT,
87
+ credential_key TEXT,
88
+ session_epoch INTEGER NOT NULL DEFAULT 0,
89
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
90
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
91
+ );
92
+ `);
93
+ await db.run(
94
+ `INSERT INTO accounts (id, name, role)
95
+ VALUES (?, ?, 'root')
96
+ ON CONFLICT(id) DO NOTHING`,
97
+ [ROOT_ACCOUNT_ID, ROOT_DEFAULT_NAME],
98
+ );
99
+ }
100
+
101
+ /** Load every account into the gate's cache. Call once, before the listener. */
102
+ export async function initAccounts(): Promise<void> {
103
+ try {
104
+ const db = await getDb();
105
+ const rows = await db.all<AccountRow>('SELECT * FROM accounts');
106
+ globalThis.__kabmoAccountCache = new Map(rows.map((row) => [row.id, toRecord(row)]));
107
+ } catch {
108
+ // A database without the table leaves only the root fallback; login and
109
+ // workspace access still work for the root account.
110
+ globalThis.__kabmoAccountCache = new Map([[ROOT_ACCOUNT_ID, { ...ROOT_FALLBACK }]]);
111
+ }
112
+ }
113
+
114
+ /** Re-read after a write. The route calls this before answering. */
115
+ export async function reloadAccounts(): Promise<void> {
116
+ await initAccounts();
117
+ }
118
+
119
+ /** One account by id. Root is always present even before the first load. */
120
+ export function getAccount(id: string): AccountRecord | undefined {
121
+ const found = cache()?.get(id);
122
+ if (found) return found;
123
+ return id === ROOT_ACCOUNT_ID ? { ...ROOT_FALLBACK } : undefined;
124
+ }
125
+
126
+ /** The root account's display name. */
127
+ export function rootAccount(): AccountRecord {
128
+ return getAccount(ROOT_ACCOUNT_ID) ?? { ...ROOT_FALLBACK };
129
+ }
130
+
131
+ /** How many accounts the login picker can offer. */
132
+ export function accountCount(): number {
133
+ const size = cache()?.size ?? 0;
134
+ return Math.max(1, size);
135
+ }
136
+
137
+ /** The public identity fields, without any credential. */
138
+ export function publicAccounts(): AccountSummary[] {
139
+ const rows = [...(cache()?.values() ?? [ROOT_FALLBACK])];
140
+ return rows
141
+ .sort((left, right) => {
142
+ if (left.role !== right.role) return left.role === 'root' ? -1 : 1;
143
+ return left.name.localeCompare(right.name);
144
+ })
145
+ .map(({ id, name, role }) => ({ id, name, role }));
146
+ }
147
+
148
+ /** Settings rows, with the workspace counts the page draws. */
149
+ export async function listAccountItems(): Promise<AccountListItem[]> {
150
+ const db = await getDb();
151
+ const rows = await db.all<AccountRow & { owned_workspaces: number; shared_workspaces: number }>(`
152
+ SELECT a.*,
153
+ (SELECT COUNT(*) FROM workspace_folders f WHERE f.owner_account_id = a.id) AS owned_workspaces,
154
+ (SELECT COUNT(*) FROM workspace_folder_shares s WHERE s.account_id = a.id) AS shared_workspaces
155
+ FROM accounts a
156
+ ORDER BY CASE WHEN a.role = 'root' THEN 0 ELSE 1 END, lower(a.name) ASC
157
+ `);
158
+ return rows.map((row) => ({
159
+ id: row.id,
160
+ name: row.name,
161
+ role: row.role === 'root' ? 'root' : 'member',
162
+ createdAt: row.created_at,
163
+ ownedWorkspaces: Number(row.owned_workspaces) || 0,
164
+ sharedWorkspaces: Number(row.shared_workspaces) || 0,
165
+ }));
166
+ }
167
+
168
+ export type AccountWriteResult<T = undefined> =
169
+ | ({ ok: true } & (T extends undefined ? { value?: T } : { value: T }))
170
+ | { ok: false; code: string; error: string };
171
+
172
+ function normalizeName(value: unknown): string {
173
+ return typeof value === 'string' ? value.trim().replace(/\s+/g, ' ') : '';
174
+ }
175
+
176
+ function validateName(name: string): { ok: true } | { ok: false; code: string; error: string } {
177
+ if (name.length < MIN_ACCOUNT_NAME_LENGTH) {
178
+ return { ok: false, code: 'name_required', error: 'An account needs a name' };
179
+ }
180
+ if (name.length > MAX_ACCOUNT_NAME_LENGTH) {
181
+ return { ok: false, code: 'name_too_long', error: `Names are at most ${MAX_ACCOUNT_NAME_LENGTH} characters` };
182
+ }
183
+ if (/[\u0000-\u001f\u007f]/.test(name)) {
184
+ return { ok: false, code: 'invalid_name', error: 'The name contains a control character' };
185
+ }
186
+ return { ok: true };
187
+ }
188
+
189
+ async function nameTaken(db: DbClient, name: string, exceptId?: string): Promise<boolean> {
190
+ const row = await db.get<{ id: string }>(
191
+ 'SELECT id FROM accounts WHERE lower(name) = lower(?) AND id != ?',
192
+ [name, exceptId ?? ''],
193
+ );
194
+ return Boolean(row);
195
+ }
196
+
197
+ export async function createAccount(input: {
198
+ name: unknown;
199
+ password: unknown;
200
+ sessionSecret: string;
201
+ minPasswordLength: number;
202
+ }): Promise<AccountWriteResult<AccountListItem>> {
203
+ const name = normalizeName(input.name);
204
+ const checked = validateName(name);
205
+ if (!checked.ok) return checked;
206
+ if (typeof input.password !== 'string' || input.password.length < input.minPasswordLength) {
207
+ return {
208
+ ok: false,
209
+ code: 'password_too_short',
210
+ error: `Password must be at least ${input.minPasswordLength} characters`,
211
+ };
212
+ }
213
+ const db = await getDb();
214
+ if (await nameTaken(db, name)) {
215
+ return { ok: false, code: 'duplicate_name', error: `An account named "${name}" already exists` };
216
+ }
217
+ const id = crypto.randomUUID();
218
+ const passwordHash = await hashPassword(input.password);
219
+ const credentialKey = deriveCredentialKey(input.password, input.sessionSecret);
220
+ await db.run(
221
+ `INSERT INTO accounts (id, name, role, password_hash, credential_key)
222
+ VALUES (?, ?, 'member', ?, ?)`,
223
+ [id, name, passwordHash, credentialKey],
224
+ );
225
+ await reloadAccounts();
226
+ return {
227
+ ok: true,
228
+ value: {
229
+ id,
230
+ name,
231
+ role: 'member',
232
+ createdAt: new Date().toISOString(),
233
+ ownedWorkspaces: 0,
234
+ sharedWorkspaces: 0,
235
+ },
236
+ };
237
+ }
238
+
239
+ export async function renameAccount(id: string, rawName: unknown): Promise<AccountWriteResult<AccountSummary>> {
240
+ const account = getAccount(id);
241
+ if (!account) return { ok: false, code: 'not_found', error: 'Account not found' };
242
+ const name = normalizeName(rawName);
243
+ const checked = validateName(name);
244
+ if (!checked.ok) return checked;
245
+ const db = await getDb();
246
+ if (await nameTaken(db, name, id)) {
247
+ return { ok: false, code: 'duplicate_name', error: `An account named "${name}" already exists` };
248
+ }
249
+ await db.run('UPDATE accounts SET name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [name, id]);
250
+ await reloadAccounts();
251
+ return { ok: true, value: { id, name, role: account.role } };
252
+ }
253
+
254
+ export async function setMemberPassword(id: string, password: string, sessionSecret: string): Promise<boolean> {
255
+ const account = getAccount(id);
256
+ if (!account || account.role === 'root') return false;
257
+ const passwordHash = await hashPassword(password);
258
+ const credentialKey = deriveCredentialKey(password, sessionSecret);
259
+ const db = await getDb();
260
+ await db.run(
261
+ `UPDATE accounts
262
+ SET password_hash = ?, credential_key = ?, session_epoch = session_epoch + 1,
263
+ updated_at = CURRENT_TIMESTAMP
264
+ WHERE id = ?`,
265
+ [passwordHash, credentialKey, id],
266
+ );
267
+ await reloadAccounts();
268
+ return true;
269
+ }
270
+
271
+ /** Invalidate every cookie minted for one member without changing its password. */
272
+ export async function bumpMemberEpoch(id: string): Promise<boolean> {
273
+ const account = getAccount(id);
274
+ if (!account || account.role === 'root') return false;
275
+ const db = await getDb();
276
+ await db.run('UPDATE accounts SET session_epoch = session_epoch + 1 WHERE id = ?', [id]);
277
+ await reloadAccounts();
278
+ return true;
279
+ }
280
+
281
+ export async function deleteAccountRow(id: string): Promise<boolean> {
282
+ if (id === ROOT_ACCOUNT_ID) return false;
283
+ const db = await getDb();
284
+ const result = await db.run('DELETE FROM accounts WHERE id = ?', [id]);
285
+ await db.run('DELETE FROM workspace_folder_shares WHERE account_id = ?', [id]);
286
+ await reloadAccounts();
287
+ return result.changes > 0;
288
+ }
289
+
290
+ /** Test hook: forget the process cache. */
291
+ export function resetAccountCacheForTests(): void {
292
+ globalThis.__kabmoAccountCache = undefined;
293
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The caller's socket address, captured by the auth gate for the login route.
8
+ *
9
+ * The address is only reachable from Elysia's handler context (`server.requestIP`),
10
+ * which the ported route modules never receive — they get `{ request, params }`
11
+ * and nothing else. The gate runs before every handler and does receive it, so it
12
+ * records the address against the `Request` object and the login route reads it
13
+ * back.
14
+ *
15
+ * A `WeakMap` keyed by the `Request` is safe here specifically because the gate
16
+ * and the handler are handed the SAME object (verified on Elysia 1.4.30). It is
17
+ * also self-cleaning: the entry disappears with the request.
18
+ *
19
+ * ## Why `x-forwarded-for` is read, and only from loopback
20
+ *
21
+ * The header is caller-supplied, so a rate limit keyed on it unconditionally is
22
+ * trivially evaded — that was the original rule, and it is still right for a
23
+ * direct connection. But a tunnel breaks the other way: `cloudflared` and
24
+ * `tailscale serve` both connect to this server from `127.0.0.1`, so EVERY
25
+ * client behind a tunnel shares one socket address. Ten failed logins from an
26
+ * attacker anywhere on the internet then locked the owner out for fifteen
27
+ * minutes — a denial of service against the person the limit exists to protect.
28
+ *
29
+ * The condition is therefore the socket, not the header: the forwarded value is
30
+ * used only when the connection itself came from loopback. A remote attacker
31
+ * cannot make their own socket address loopback, and a local process that can
32
+ * forge the header already has the machine.
33
+ *
34
+ * NOTE: there is deliberately no `clientAddressFromContext(context)` here.
35
+ *
36
+ * One existed, and calling it from the auth hook made every POST arrive with an
37
+ * already-consumed body — `request.bodyUsed === true` before any handler ran, so
38
+ * the login route parsed an empty body and rejected a correct password.
39
+ *
40
+ * Measured on Bun 1.4.2 + Elysia 1.4.30: `authGate(c.request,
41
+ * clientAddressFromContext(c))` lost the body, while the identical logic written
42
+ * inline kept it, and the same held for a helper whose entire body was
43
+ * `'request' in c` — the trigger is handing this context to any function, not
44
+ * the logic inside it. `src/server/index.ts` therefore reads `server.requestIP`
45
+ * inline. This module keeps only the WeakMap half, which is reached from a plain
46
+ * `Request` and is unaffected.
47
+ */
48
+
49
+ import { UNKNOWN_CLIENT_KEY } from './rate-limit';
50
+
51
+ const addresses = new WeakMap<Request, string>();
52
+
53
+ /** Whether a socket address is this machine talking to itself. */
54
+ function isLoopback(address: string): boolean {
55
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
56
+ }
57
+
58
+ /**
59
+ * The address a rate limit should key on.
60
+ *
61
+ * Behind a tunnel the socket is loopback for every client, so the forwarded
62
+ * value is the only thing that distinguishes them. It is trusted ONLY in that
63
+ * case — see the module comment for why the socket, not the header, is the
64
+ * condition.
65
+ */
66
+ export function effectiveClientAddress(request: Request, socketAddress: string | undefined): string {
67
+ if (!socketAddress) return UNKNOWN_CLIENT_KEY;
68
+ if (!isLoopback(socketAddress)) return socketAddress;
69
+ const forwarded = request.headers.get('x-forwarded-for');
70
+ if (!forwarded) return socketAddress;
71
+ const first = forwarded.split(',')[0]?.trim();
72
+ return first || socketAddress;
73
+ }
74
+
75
+ /** Record the socket address for `request`. Called by the auth gate. */
76
+ export function rememberClientAddress(request: Request, address: string | undefined): void {
77
+ addresses.set(request, effectiveClientAddress(request, address));
78
+ }
79
+
80
+ /**
81
+ * The socket address recorded for `request`, or the shared unknown-client key.
82
+ *
83
+ * Falling back to a single shared key (rather than to per-request randomness)
84
+ * is what keeps an unidentifiable caller throttled: they draw from the small
85
+ * shared budget instead of getting a fresh one.
86
+ */
87
+ export function clientAddressFor(request: Request): string {
88
+ return addresses.get(request) ?? UNKNOWN_CLIENT_KEY;
89
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * UI-auth state for ONE run of the server.
8
+ *
9
+ * There is no stored password. A password is supplied per invocation — through
10
+ * `--ui-password` or `KABMO_UI_PASSWORD` — hashed in memory at boot, and
11
+ * forgotten when the process exits. A plain `bun run dev` therefore runs with no
12
+ * authentication, which is the default: a file on disk must not be able to
13
+ * decide that a server the user started needs a credential they never set.
14
+ *
15
+ * The only thing persisted is the SESSION SIGNING SECRET, and it holds no
16
+ * password. It is persisted for one reason: `bun run --hot` re-evaluates the
17
+ * server entry on every save, so an in-memory secret would log the user out on
18
+ * each edit — a dev loop that punishes the person using it. A file that only
19
+ * signs cookies can be shared across restarts without ever being able to enable
20
+ * authentication on its own.
21
+ */
22
+
23
+ import fs from 'fs';
24
+ import { scryptSync } from 'node:crypto';
25
+
26
+ import { getAuthPath, getDataDir } from '@kabmo-labs/kabmo-paths/paths';
27
+
28
+ /** Shape of the persisted secret file. `version` guards a future change. */
29
+ export interface AuthSecretFile {
30
+ version: 2;
31
+ /** HMAC key for session tokens. Never a password, and never sufficient to log in. */
32
+ sessionSecret: string;
33
+ updatedAt: string;
34
+ }
35
+
36
+ /** The auth state of the running process. Null means authentication is off. */
37
+ export interface ActiveAuthConfig {
38
+ /** argon2id hash of the password supplied for this run. */
39
+ passwordHash: string;
40
+ /**
41
+ * Deterministic scrypt-derived key for THIS password and THIS secret. It is
42
+ * what a session's fingerprint binds to; unlike {@link passwordHash} it is
43
+ * stable across restarts, which is what keeps a session alive through one.
44
+ */
45
+ credentialKey: string;
46
+ /** Signs session cookies; survives restarts so sessions do too. */
47
+ sessionSecret: string;
48
+ }
49
+
50
+ /**
51
+ * The stored session secret, or null when there is none.
52
+ *
53
+ * Any object carrying a non-empty `sessionSecret` is accepted, including the
54
+ * retired v1 shape — reusing it means upgrading does not sign every logged-in
55
+ * user out. The `passwordHash` that file may also carry is deliberately NOT
56
+ * read: under this design a stored hash can never enable authentication.
57
+ */
58
+ export async function readSessionSecret(): Promise<string | null> {
59
+ try {
60
+ const parsed: unknown = JSON.parse(await Bun.file(getAuthPath()).text());
61
+ if (!parsed || typeof parsed !== 'object') return null;
62
+ const secret = (parsed as Record<string, unknown>).sessionSecret;
63
+ return typeof secret === 'string' && secret.length > 0 ? secret : null;
64
+ } catch {
65
+ // Absent, unreadable or malformed all mean "no secret to reuse": a fresh one
66
+ // is generated, which is a logout rather than an error.
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Persist the session secret (temp file + rename, mode 0600). Returns false
73
+ * instead of throwing when the data directory is not writable — the run
74
+ * continues with the secret it generated, it just will not survive a restart.
75
+ */
76
+ export async function writeSessionSecret(sessionSecret: string): Promise<boolean> {
77
+ const target = getAuthPath();
78
+ const temp = `${target}.${process.pid}.tmp`;
79
+ const contents: AuthSecretFile = { version: 2, sessionSecret, updatedAt: new Date().toISOString() };
80
+ try {
81
+ fs.mkdirSync(getDataDir(), { recursive: true, mode: 0o700 });
82
+ fs.writeFileSync(temp, `${JSON.stringify(contents, null, 2)}\n`, { mode: 0o600 });
83
+ fs.renameSync(temp, target);
84
+ return true;
85
+ } catch {
86
+ try {
87
+ fs.rmSync(temp, { force: true });
88
+ } catch {
89
+ // Best-effort cleanup only.
90
+ }
91
+ return false;
92
+ }
93
+ }
94
+
95
+ /** Hash a password for this run. argon2id, ~70 ms — the brute-force floor. */
96
+ export function hashPassword(password: string): Promise<string> {
97
+ return Bun.password.hash(password, { algorithm: 'argon2id' });
98
+ }
99
+
100
+ /**
101
+ * Verify a candidate against the run's hash.
102
+ *
103
+ * `Bun.password.verify` compares in constant time and answers false for a
104
+ * malformed hash rather than throwing, so a corrupted value reads as "wrong
105
+ * password" — the outcome the user can act on.
106
+ */
107
+ export function verifyPassword(candidate: string, passwordHash: string): Promise<boolean> {
108
+ return Bun.password.verify(candidate, passwordHash);
109
+ }
110
+
111
+ /**
112
+ * The value a session's fingerprint binds to, for a password and a secret.
113
+ *
114
+ * DETERMINISTIC on purpose: the same password with the same session secret must
115
+ * produce the same key on every boot, because the fingerprint is what makes a
116
+ * token fail after a password change and the token must otherwise survive a
117
+ * restart. `passwordHash` cannot serve as that value — its argon2 salt is
118
+ * random per boot, so a restart with the SAME password minted a new hash and
119
+ * invalidated every session (measured: a token valid before a second `initAuth`
120
+ * call was rejected after it, with the persisted secret correctly reused). The
121
+ * stated point of persisting the secret — "a restart keeps its sessions" — was
122
+ * therefore not delivered at all.
123
+ *
124
+ * argon2's own `salt` option is not an alternative (verified on Bun 1.4.2: two
125
+ * hashes with the same salt still differ), so the derivation is scrypt, salted
126
+ * with the SECRET and memory-hard for the same reason the verifier is. Nothing
127
+ * is persisted: the secret comes from `auth.json` and the password from the
128
+ * command line, so a leaked cookie plus that file is what an attacker would
129
+ * need to brute-force against, exactly as before.
130
+ */
131
+ export function deriveCredentialKey(password: string, sessionSecret: string): string {
132
+ return scryptSync(password, sessionSecret, 32, { N: 1 << 14, r: 8, p: 1 }).toString('base64url');
133
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /** Paths that never require a session, because they are the way in. */
7
+
8
+ /**
9
+ * The login screen's path. One constant because three places depend on it: it
10
+ * is public (the way in), it is where an unauthenticated document request is
11
+ * sent, and it is where a signed-in visitor must NOT stay.
12
+ */
13
+ export const LOGIN_PATH = '/login';
14
+
15
+ const PUBLIC_EXACT: Record<string, true> = {
16
+ '/api/health': true,
17
+ // The native shells' own update check. Android and iOS ask these from NATIVE
18
+ // code, which carries no WebView cookie — and the button exists precisely for
19
+ // a shell too stale to load the console.
20
+ '/api/updates/android': true,
21
+ '/api/updates/ios': true,
22
+ '/api/auth/state': true,
23
+ '/api/auth/login': true,
24
+ '/api/auth/logout': true,
25
+ // A device redeeming a pairing code has no cookie yet — the one-time secret
26
+ // in the code IS its credential. Minting a code stays gated.
27
+ '/api/connect/pair/claim': true,
28
+ // The page a phone's camera opens. It carries no session and no data.
29
+ '/pair': true,
30
+ [LOGIN_PATH]: true,
31
+ '/robots.txt': true,
32
+ '/sw.js': true,
33
+ '/manifest.webmanifest': true,
34
+ '/favicon.ico': true,
35
+ '/fonts.css': true,
36
+ '/_shell': true,
37
+ };
38
+
39
+ /**
40
+ * Prefixes whose contents are the app itself: bundle, styles, fonts, icons.
41
+ *
42
+ * Each ends at a real separator. A bare `/icon` would also exempt
43
+ * `/icons-secret`, and a public prefix that matches more than it names is an
44
+ * open door that nothing reports.
45
+ */
46
+ const PUBLIC_PREFIXES = [
47
+ '/_bun/',
48
+ '/_dev-assets/',
49
+ '/fonts/',
50
+ '/static/',
51
+ '/.well-known/',
52
+ '/icon.',
53
+ '/icon-',
54
+ '/apple-touch-icon.',
55
+ '/apple-touch-icon-',
56
+ // The generated palette + icon-paint sheet is the login screen's styling.
57
+ '/theme-',
58
+ ];
59
+
60
+ /** True when `pathname` is reachable without a session. */
61
+ export function isPublicPath(pathname: string): boolean {
62
+ if (PUBLIC_EXACT[pathname]) return true;
63
+ for (const prefix of PUBLIC_PREFIXES) {
64
+ if (pathname.startsWith(prefix)) return true;
65
+ }
66
+ return false;
67
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Login throttling: a per-IP attempt budget in front of the password check.
8
+ *
9
+ * argon2id already makes one guess cost ~70 ms, but that only bounds the RATE of
10
+ * guesses — it does not stop a script from running them for a week. This bounds
11
+ * the NUMBER of failures instead: past the budget the address is locked out
12
+ * outright, and no verification runs at all.
13
+ *
14
+ * State is in-memory and therefore resets when the process restarts. That is the
15
+ * right trade for a single-user console: a persisted lockout would have to be
16
+ * cleared by hand after a restart, and the process is only reachable at all
17
+ * because someone chose to expose it.
18
+ *
19
+ * The key is the SOCKET address (`requestIP`), except when the socket is
20
+ * loopback — the case a tunnel creates. `cloudflared` and `tailscale serve`
21
+ * connect from `127.0.0.1`, so every client behind one shares a single address
22
+ * and ten failures from an attacker anywhere would lock the owner out. In that
23
+ * one case the forwarded address is used instead; see
24
+ * `effectiveClientAddress` in `client-address.ts` for why the socket, not the
25
+ * header, is the condition. A direct remote connection still keys on its own
26
+ * socket address, which a caller cannot forge.
27
+ */
28
+
29
+ /** Sliding window an attempt count is measured over. */
30
+ export const RATE_LIMIT_WINDOW_MS = 5 * 60 * 1000;
31
+
32
+ /** Failures allowed within the window before the lockout. */
33
+ export const RATE_LIMIT_MAX_ATTEMPTS = 10;
34
+
35
+ /** How long a tripped lockout lasts. */
36
+ export const RATE_LIMIT_LOCKOUT_MS = 15 * 60 * 1000;
37
+
38
+ /**
39
+ * Budget for a request whose address could not be determined. Lower than the
40
+ * per-IP budget on purpose: an unidentifiable caller cannot be distinguished
41
+ * from any other, so the budget they share must be small.
42
+ */
43
+ export const RATE_LIMIT_UNKNOWN_MAX_ATTEMPTS = 3;
44
+
45
+ /** Key used when the socket address is unavailable. */
46
+ export const UNKNOWN_CLIENT_KEY = 'unknown-client';
47
+
48
+ interface AttemptRecord {
49
+ count: number;
50
+ lastAttempt: number;
51
+ lockedUntil: number;
52
+ }
53
+
54
+ const attempts = new Map<string, AttemptRecord>();
55
+
56
+ /** Entries older than this are dropped opportunistically; see `prune`. */
57
+ const STALE_AFTER_MS = 60 * 60 * 1000;
58
+
59
+ const MAX_TRACKED_CLIENTS = 4096;
60
+
61
+ function maxAttemptsFor(key: string): number {
62
+ return key === UNKNOWN_CLIENT_KEY ? RATE_LIMIT_UNKNOWN_MAX_ATTEMPTS : RATE_LIMIT_MAX_ATTEMPTS;
63
+ }
64
+
65
+ /**
66
+ * Drop records that are neither locked nor recently touched.
67
+ *
68
+ * Runs on write rather than on a timer: a module-level interval would have to be
69
+ * unref'd and torn down, and this map is written exactly when a login fails —
70
+ * which is also the only moment it can grow.
71
+ */
72
+ function prune(now: number): void {
73
+ if (attempts.size < MAX_TRACKED_CLIENTS) return;
74
+ for (const [key, record] of attempts) {
75
+ const locked = record.lockedUntil > now;
76
+ if (!locked && now - record.lastAttempt > STALE_AFTER_MS) attempts.delete(key);
77
+ }
78
+ }
79
+
80
+ export interface RateLimitStatus {
81
+ allowed: boolean;
82
+ /** Seconds until the lockout lifts; only present when `allowed` is false. */
83
+ retryAfterSec?: number;
84
+ limit: number;
85
+ remaining: number;
86
+ }
87
+
88
+ /** Whether this key may attempt a login right now. Does not consume the budget. */
89
+ export function checkLoginRateLimit(key: string, now = Date.now()): RateLimitStatus {
90
+ const limit = maxAttemptsFor(key);
91
+ const record = attempts.get(key);
92
+
93
+ if (!record) return { allowed: true, limit, remaining: limit };
94
+
95
+ if (record.lockedUntil > now) {
96
+ return {
97
+ allowed: false,
98
+ retryAfterSec: Math.ceil((record.lockedUntil - now) / 1000),
99
+ limit,
100
+ remaining: 0,
101
+ };
102
+ }
103
+
104
+ // A lockout that has run out, or a window that has gone quiet, both start over.
105
+ if (record.lockedUntil > 0 || now - record.lastAttempt > RATE_LIMIT_WINDOW_MS) {
106
+ attempts.delete(key);
107
+ return { allowed: true, limit, remaining: limit };
108
+ }
109
+
110
+ return { allowed: true, limit, remaining: Math.max(0, limit - record.count) };
111
+ }
112
+
113
+ /**
114
+ * Record a failed attempt, tripping the lockout once the budget is spent.
115
+ * Returns the status AFTER the failure, so the caller can answer 429 immediately.
116
+ */
117
+ export function recordLoginFailure(key: string, now = Date.now()): RateLimitStatus {
118
+ const limit = maxAttemptsFor(key);
119
+ const record = attempts.get(key);
120
+
121
+ if (!record || now - record.lastAttempt > RATE_LIMIT_WINDOW_MS) {
122
+ attempts.set(key, { count: 1, lastAttempt: now, lockedUntil: 0 });
123
+ prune(now);
124
+ return { allowed: true, limit, remaining: limit - 1 };
125
+ }
126
+
127
+ const count = record.count + 1;
128
+ const lockedUntil = count >= limit ? now + RATE_LIMIT_LOCKOUT_MS : 0;
129
+ attempts.set(key, { count, lastAttempt: now, lockedUntil });
130
+ prune(now);
131
+
132
+ if (lockedUntil > 0) {
133
+ return { allowed: false, retryAfterSec: Math.ceil(RATE_LIMIT_LOCKOUT_MS / 1000), limit, remaining: 0 };
134
+ }
135
+ return { allowed: true, limit, remaining: Math.max(0, limit - count) };
136
+ }
137
+
138
+ /** Forget a key's failures — called after a successful login. */
139
+ export function clearLoginRateLimit(key: string): void {
140
+ attempts.delete(key);
141
+ }
142
+
143
+ /** Drop every record. Test seam; the process otherwise keeps them for its life. */
144
+ export function resetLoginRateLimits(): void {
145
+ attempts.clear();
146
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Session tokens and the cookie that carries them.
8
+ *
9
+ * A session is a stateless signed value — `v1.<expiresAt>.<fingerprint>.<mac>` —
10
+ * so validating one costs an HMAC and no storage. The middle segment is
11
+ * `HMAC(secret, passwordHash)`: because it is part of the signed payload, every
12
+ * token minted before a password change fails verification afterwards. Changing
13
+ * the password therefore revokes every session, with no session table to sweep.
14
+ *
15
+ * The cookie NAME carries the request port. Browsers key cookies by host and
16
+ * ignore the port (RFC 6265), so two Kabmo instances on one machine share a
17
+ * jar: without the port in the name, logging into the second silently overwrote
18
+ * the first instance's cookie. This install routinely has several ports live at
19
+ * once, so the collision is the normal case rather than an edge one.
20
+ */
21
+
22
+ import { createHmac, timingSafeEqual } from 'node:crypto';
23
+
24
+ /** Cookie base name; the resolved name appends `_<port>` when the host has one. */
25
+ export const SESSION_COOKIE_BASE = 'omp_session';
26
+
27
+ /** Default session lifetime: 12 hours. */
28
+ export const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
29
+
30
+ /** Lifetime when the user asks to be remembered on this device: 7 days. */
31
+ export const TRUSTED_DEVICE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
32
+
33
+ const TOKEN_VERSION = 'v1';
34
+ /** Member tokens carry their account id and revocation epoch. */
35
+ const ACCOUNT_TOKEN_VERSION = 'v2';
36
+
37
+ /**
38
+ * The trailing port of a `Host` authority, or null when there is none.
39
+ * Handles bracketed IPv6 (`[::1]:3000`) and plain host names.
40
+ */
41
+ function hostPort(host: string): string | null {
42
+ if (host.startsWith('[')) {
43
+ const end = host.indexOf(']');
44
+ if (end === -1) return null;
45
+ const rest = host.slice(end + 1);
46
+ return rest.startsWith(':') && /^\d+$/.test(rest.slice(1)) ? rest.slice(1) : null;
47
+ }
48
+ const match = host.match(/:(\d+)$/);
49
+ return match ? match[1] : null;
50
+ }
51
+
52
+ /**
53
+ * Cookie name for a request. `x-forwarded-host` wins when present, so an
54
+ * instance behind a reverse proxy is keyed by the port the browser used rather
55
+ * than the upstream one.
56
+ */
57
+ export function sessionCookieName(headers: Headers): string {
58
+ const forwarded = headers.get('x-forwarded-host');
59
+ const host = (forwarded ? forwarded.split(',')[0] : headers.get('host') ?? '').trim();
60
+ if (!host) return SESSION_COOKIE_BASE;
61
+ const port = hostPort(host);
62
+ if (!port) return SESSION_COOKIE_BASE;
63
+ const portNumber = Number.parseInt(port, 10);
64
+ return Number.isFinite(portNumber) && portNumber > 0 ? `${SESSION_COOKIE_BASE}_${port}` : SESSION_COOKIE_BASE;
65
+ }
66
+
67
+ /** Read the session token from a request's cookies, or null when absent. */
68
+ export function readSessionCookie(request: Request): string | null {
69
+ const header = request.headers.get('cookie');
70
+ if (!header) return null;
71
+ const name = sessionCookieName(request.headers);
72
+ for (const segment of header.split(';')) {
73
+ const index = segment.indexOf('=');
74
+ if (index === -1) continue;
75
+ if (segment.slice(0, index).trim() !== name) continue;
76
+ const value = segment.slice(index + 1).trim();
77
+ if (!value) return null;
78
+ try {
79
+ return decodeURIComponent(value);
80
+ } catch {
81
+ return value;
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * `HMAC(secret, credentialKey)` — the value that binds a session to one password.
89
+ *
90
+ * The key is what `deriveCredentialKey` produces, NOT the argon2 hash: it has to
91
+ * be reproducible from the secret and the password alone, or a session would die
92
+ * with the process that minted it.
93
+ */
94
+ export function credentialFingerprint(sessionSecret: string, credentialKey: string): string {
95
+ return createHmac('sha256', sessionSecret).update(credentialKey).digest('base64url');
96
+ }
97
+
98
+ function sign(sessionSecret: string, payload: string): string {
99
+ return createHmac('sha256', sessionSecret).update(payload).digest('base64url');
100
+ }
101
+
102
+ /** Constant-time string comparison that tolerates unequal lengths. */
103
+ function safeEqual(left: string, right: string): boolean {
104
+ const a = Buffer.from(left);
105
+ const b = Buffer.from(right);
106
+ if (a.length !== b.length) return false;
107
+ return timingSafeEqual(a, b);
108
+ }
109
+
110
+ export interface SessionIssueOptions {
111
+ sessionSecret: string;
112
+ /** A `deriveCredentialKey` result — never the argon2 hash (see the field). */
113
+ credentialKey: string;
114
+ ttlMs?: number;
115
+ /** Injected for tests; defaults to now. */
116
+ now?: number;
117
+ /**
118
+ * The account this token belongs to. Omitted (or `root` with epoch 0) keeps
119
+ * the original four-segment token, so existing root sessions survive an
120
+ * upgrade and the pre-account token contract stays byte-compatible.
121
+ */
122
+ accountId?: string;
123
+ /** Per-account revocation counter. */
124
+ epoch?: number;
125
+ }
126
+
127
+ /** Mint a session token valid for `ttlMs`. */
128
+ export function issueSessionToken({
129
+ sessionSecret,
130
+ credentialKey,
131
+ ttlMs = SESSION_TTL_MS,
132
+ now = Date.now(),
133
+ accountId,
134
+ epoch = 0,
135
+ }: SessionIssueOptions): string {
136
+ const expiresAt = now + ttlMs;
137
+ const fingerprint = credentialFingerprint(sessionSecret, credentialKey);
138
+ if (!accountId || (accountId === 'root' && epoch === 0)) {
139
+ const payload = [TOKEN_VERSION, String(expiresAt), fingerprint].join('.');
140
+ return `${payload}.${sign(sessionSecret, payload)}`;
141
+ }
142
+ const payload = [
143
+ ACCOUNT_TOKEN_VERSION,
144
+ accountId,
145
+ String(epoch),
146
+ String(expiresAt),
147
+ fingerprint,
148
+ ].join('.');
149
+ return `${payload}.${sign(sessionSecret, payload)}`;
150
+ }
151
+
152
+ interface ParsedToken {
153
+ version: string;
154
+ accountId: string;
155
+ epoch: number;
156
+ expiresAt: number;
157
+ fingerprint: string;
158
+ mac: string;
159
+ signed: string;
160
+ }
161
+
162
+ /** Parse either token shape without implying it is authentic. */
163
+ function parseToken(token: string | null | undefined): ParsedToken | null {
164
+ if (!token) return null;
165
+ const parts = token.split('.');
166
+ if (parts[0] === TOKEN_VERSION && parts.length === 4) {
167
+ return {
168
+ version: TOKEN_VERSION,
169
+ accountId: 'root',
170
+ epoch: 0,
171
+ expiresAt: Number(parts[1]),
172
+ fingerprint: parts[2],
173
+ mac: parts[3],
174
+ signed: parts.slice(0, 3).join('.'),
175
+ };
176
+ }
177
+ if (parts[0] === ACCOUNT_TOKEN_VERSION && parts.length === 6) {
178
+ return {
179
+ version: ACCOUNT_TOKEN_VERSION,
180
+ accountId: parts[1],
181
+ epoch: Number(parts[2]),
182
+ expiresAt: Number(parts[3]),
183
+ fingerprint: parts[4],
184
+ mac: parts[5],
185
+ signed: parts.slice(0, 5).join('.'),
186
+ };
187
+ }
188
+ return null;
189
+ }
190
+
191
+ /** The account a token claims to belong to, before its signature is checked. */
192
+ export function readSessionAccount(token: string | null | undefined): { accountId: string; epoch: number } | null {
193
+ const parsed = parseToken(token);
194
+ if (!parsed || !Number.isFinite(parsed.epoch)) return null;
195
+ return { accountId: parsed.accountId, epoch: parsed.epoch };
196
+ }
197
+
198
+ /**
199
+ * True when `token` was minted by this secret for the CURRENT password and has
200
+ * not expired. Every failure mode — malformed, wrong version, bad signature,
201
+ * stale fingerprint, past expiry — is a plain false.
202
+ */
203
+ export function verifySessionToken(
204
+ token: string | null | undefined,
205
+ { sessionSecret, credentialKey, now = Date.now(), accountId, epoch }: Omit<SessionIssueOptions, 'ttlMs'>,
206
+ ): boolean {
207
+ const parsed = parseToken(token);
208
+ if (!parsed) return false;
209
+ if (accountId !== undefined && parsed.accountId !== accountId) return false;
210
+ if (epoch !== undefined && parsed.epoch !== epoch) return false;
211
+ if (!safeEqual(parsed.mac, sign(sessionSecret, parsed.signed))) return false;
212
+ if (!safeEqual(parsed.fingerprint, credentialFingerprint(sessionSecret, credentialKey))) return false;
213
+ return Number.isFinite(parsed.expiresAt) && parsed.expiresAt > now;
214
+ }
215
+
216
+ /**
217
+ * Remaining lifetime of a VALID token, in ms, or null when it is unusable.
218
+ *
219
+ * Reissuing a session (after a password change, after a revocation) has to
220
+ * preserve what the user chose at the login screen. Measured: a 7-day session
221
+ * came back as `Max-Age=43200` after a revoke, because those routes minted a
222
+ * fresh token with the DEFAULT ttl — a silent downgrade from a week to 12 hours
223
+ * that the user could only discover by being signed out early.
224
+ *
225
+ * The deadline is the token's own signed `expiresAt`, so this cannot be talked
226
+ * into extending a session beyond what was issued.
227
+ */
228
+ export function sessionRemainingMs(
229
+ token: string | null | undefined,
230
+ { sessionSecret, credentialKey, now = Date.now(), accountId, epoch }: Omit<SessionIssueOptions, 'ttlMs'>,
231
+ ): number | null {
232
+ if (!verifySessionToken(token, { sessionSecret, credentialKey, now, ...(accountId ? { accountId } : {}), ...(epoch !== undefined ? { epoch } : {}) })) {
233
+ return null;
234
+ }
235
+ const parsed = parseToken(token);
236
+ if (!parsed || !Number.isFinite(parsed.expiresAt) || parsed.expiresAt <= now) return null;
237
+ return parsed.expiresAt - now;
238
+ }
239
+
240
+ /**
241
+ * `Set-Cookie` value for a session.
242
+ *
243
+ * `SameSite=Lax` rather than `Strict`: this app's own document navigations must
244
+ * keep the cookie (a Strict cookie is withheld on a top-level navigation from
245
+ * another site, which would bounce a returning user through the login screen),
246
+ * while cross-site POSTs still cannot carry it — which is the CSRF exposure that
247
+ * matters here.
248
+ *
249
+ * `Secure` is added only when the request arrived over https. Hardcoding it
250
+ * would make the cookie unsettable on the plain-http localhost this server
251
+ * normally runs on, i.e. login would appear to succeed and never stick.
252
+ */
253
+ export function sessionCookieHeader(name: string, token: string, ttlMs: number, secure: boolean): string {
254
+ const maxAge = Math.max(0, Math.floor(ttlMs / 1000));
255
+ const expires = maxAge === 0
256
+ ? 'Thu, 01 Jan 1970 00:00:00 GMT'
257
+ : new Date(Date.now() + maxAge * 1000).toUTCString();
258
+ const attributes = [
259
+ `${name}=${encodeURIComponent(token)}`,
260
+ 'Path=/',
261
+ 'HttpOnly',
262
+ 'SameSite=Lax',
263
+ `Max-Age=${maxAge}`,
264
+ `Expires=${expires}`,
265
+ ];
266
+ if (secure) attributes.push('Secure');
267
+ return attributes.join('; ');
268
+ }
269
+
270
+ /** `Set-Cookie` value that clears the session cookie. */
271
+ export function clearSessionCookieHeader(name: string, secure: boolean): string {
272
+ return sessionCookieHeader(name, '', 0, secure);
273
+ }
274
+
275
+ /** True when the request reached the server over https, directly or via a proxy. */
276
+ export function isSecureRequest(request: Request): boolean {
277
+ const forwarded = request.headers.get('x-forwarded-proto');
278
+ if (forwarded) return forwarded.split(',')[0].trim().toLowerCase() === 'https';
279
+ try {
280
+ return new URL(request.url).protocol === 'https:';
281
+ } catch {
282
+ return false;
283
+ }
284
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.