dsh-plugin-auth 0.1.2

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/README.md ADDED
@@ -0,0 +1,205 @@
1
+ # dsh-plugin-auth
2
+
3
+ Enterprise username/password authentication gate for the **dsh** (DeepSeek Harness) Web UI.
4
+
5
+ Out-of-tree plugin — **no core changes**. Once installed into the `web` profile, every page, API
6
+ route, `/plugins` asset, and WebSocket upgrade requires a logged-in session. Unauthenticated
7
+ navigations are redirected to a self-contained login page; unauthenticated API/XHR calls get `401`.
8
+ The login page uses Simplified Chinese (`zh-CN`) and follows the operating system's light/dark
9
+ preference with the same palette and control geometry as the dsh Web UI; CLI and JSON API output
10
+ remain compatible.
11
+
12
+ > The stock Web UI ships only a DNS-rebinding "browser trust fence" (`isTrustedApiRequest`), which the
13
+ > source explicitly notes **is not an authentication layer**. This plugin adds the missing gate.
14
+
15
+ ## How it works
16
+
17
+ The plugin's default export is `class AuthWebServer extends WebServer`. A bundle composition patch
18
+ (`cordis.patch.yml`) **disables** the stock `webserver` row and **inserts** a row that re-provides the
19
+ `webServer` service from this subclass — so the plugin becomes the *sole* provider and every consumer
20
+ registration flows through it:
21
+
22
+ - `register` / `registerFallback` / `registerUpgrade` are overridden to wrap each handler in an auth
23
+ gate, then delegate to `super.*`. One choke point covers the SPA fallback, `/api`, `/plugins`,
24
+ upgrades, and any route added later.
25
+ - The plugin's own `/__auth/*` surface (login page, login/logout, status) is registered with
26
+ `super.register` in the constructor, so it stays **ungated** and reachable while logged out.
27
+ - The subclass truly re-provides `webServer` (`super(ctx, 'webServer')` is inherited) and the insert row
28
+ keeps `inject: [webStartup]` and the `{host, port}` config, so downstream `web-runtime` and
29
+ `connection` rows still resolve.
30
+
31
+ ## Requirements
32
+
33
+ - Node `^22.19 || >=24` (matches dsh).
34
+ - A dsh checkout/profile where the peers resolve: `@deepseek-ai/cordis` and
35
+ `@deepseek-ai/dsh-host-webserver`. Both are in the `web` profile's dependency closure already,
36
+ and the profile's module fallback (`healProfilesModuleFallback`) links them next to the plugin.
37
+ - The plugin **deliberately does not declare these as `peerDependencies`**. It subclasses the
38
+ harness's *own* `WebServer` (the `webServer`-service provider) and must share the harness's exact
39
+ `WebServer` **and** `cordis` module instances. Declaring `"*"` peers makes pnpm fetch a stale
40
+ published copy from the registry, install it inside the plugin's dependency closure, and *shadow*
41
+ the profile fallback — the subclass then extends the wrong build (an older one that provides
42
+ `httpServer`, not `webServer`, bound to a different `cordis`), so boot fails with every web
43
+ consumer "pending (waiting for service: webServer)". Leaving the peers undeclared lets Node's
44
+ parent-walk resolve them to the fallback — the same instances the loader uses.
45
+
46
+
47
+ ## Install from npm
48
+
49
+ The public npm package is the recommended installation path once a release is published. dsh forwards
50
+ the package spec to pnpm and automatically adds the package to the profile layer list because this package
51
+ declares `dsh.bundle`:
52
+
53
+ ```bash
54
+ # install the exact release into the web profile
55
+ dsh plugin --profile web add -w dsh-plugin-auth@0.1.2
56
+
57
+ # create the first admin before first boot (writes $DSH_HOME/auth/users.json)
58
+ dsh plugin --profile web exec dsh-auth add-user admin
59
+
60
+ # confirm the auth-webserver layer resolved and the stock webserver is disabled
61
+ dsh --profile web --dump-config
62
+ ```
63
+
64
+ `dsh-plugin-auth` deliberately has no `peerDependencies`: the dsh profile supplies the exact
65
+ `@deepseek-ai/cordis` and `@deepseek-ai/dsh-host-webserver` instances required by the subclass.
66
+
67
+ ## Install from a tarball
68
+
69
+ Use a tarball for local development or when the package is not available from a registry. The tarball's
70
+ realpath lands inside the profile tree, which lets its peer imports resolve through the profile module
71
+ fallback; a `link:` to an external directory would put the realpath outside the tree and fail to resolve:
72
+
73
+ ```bash
74
+ # from the plugin directory
75
+ npm pack # → dsh-plugin-auth-<version>.tgz
76
+
77
+ # create the first admin BEFORE first boot (writes $DSH_HOME/auth/users.json)
78
+ node bin/dsh-auth.js add-user admin
79
+
80
+ # install into the web profile.
81
+ # -w is REQUIRED: a dsh profile is a pnpm workspace root (packages: - .), and
82
+ # adding a dependency to a workspace root without -w fails ERR_PNPM_ADDING_TO_ROOT.
83
+ pnpm dsh plugin --profile web add -w ./dsh-plugin-auth-<version>.tgz
84
+ ```
85
+
86
+ ### Pre-flight (go / no-go)
87
+
88
+ Before starting the server, confirm the composition resolved and the peer imports work:
89
+
90
+ ```bash
91
+ dsh --profile web --dump-config
92
+ ```
93
+
94
+ The dump must show the `webserver` row with `disabled: true` and exactly one inserted `auth-webserver`
95
+ row — with no "module resolution failed" errors. A resolution failure here fails loud; fix the install
96
+ (use a tarball, not a directory link) before booting.
97
+
98
+ ### Start
99
+
100
+ ```bash
101
+ pnpm dsh web # binds 127.0.0.1:3080 by default
102
+ pnpm dsh web --port 8080 # if 3080 is taken (e.g. a stale dsh still running)
103
+ ```
104
+
105
+ Open `http://127.0.0.1:3080` → you are redirected to `/__auth/login`. After signing in you reach the
106
+ app; `/api` and `/plugins` work as normal.
107
+
108
+ > If boot fails with `EADDRINUSE ... 127.0.0.1:3080`, another process (often a stale `dsh web` from a
109
+ > previous run) already holds the port. Stop it, or start on a different `--port`. This is a distinct
110
+ > failure from the composition error below — it means the gate *did* activate and tried to bind.
111
+
112
+
113
+ ## CLI: `dsh-auth`
114
+
115
+ Credentials live in `$DSH_HOME/auth/users.json` (atomic write, mode `0600` where POSIX modes apply) and
116
+ are managed **offline** — never through the Web settings UI. Passwords are read from the TTY with echo
117
+ masked, or from bootstrap env vars for non-interactive provisioning.
118
+
119
+ ```
120
+ dsh-auth add-user <username> Create a user (prompts for a password).
121
+ dsh-auth passwd <username> Change a user's password.
122
+ dsh-auth list List users (with disabled flag + last-updated).
123
+ dsh-auth remove <username> Delete a user.
124
+ dsh-auth disable <username> Disable a user (keeps the record; blocks login).
125
+ dsh-auth enable <username> Re-enable a disabled user.
126
+ ```
127
+
128
+ Environment:
129
+
130
+ - `DSH_HOME` — auth data root (default `~/.dsh`); data in `$DSH_HOME/auth`.
131
+ - `DSH_AUTH_BOOTSTRAP_USER` — username for non-interactive `add-user`.
132
+ - `DSH_AUTH_BOOTSTRAP_PASSWORD` — password for non-interactive `add-user` / `passwd`.
133
+
134
+ Passwords must be at least 12 characters and include at least 3 of: lowercase, uppercase, digit, symbol.
135
+
136
+ ## Configuration (`$DSH_HOME/auth/config.json`, optional)
137
+
138
+ All keys are optional; out-of-range or wrong-typed values silently fall back to the secure default, so a
139
+ malformed file can never weaken the gate past sane bounds.
140
+
141
+ | Key | Default | Meaning |
142
+ | --- | --- | --- |
143
+ | `sessionAbsoluteTtlMs` | `43200000` (12h) | Hard session lifetime cap. |
144
+ | `sessionIdleTtlMs` | `7200000` (2h) | Sliding idle window. |
145
+ | `sweepIntervalMs` | `300000` (5m) | Background expired-session sweep cadence. |
146
+ | `lockoutThreshold` | `5` | Consecutive failures (per username+IP) before lockout. |
147
+ | `lockoutBaseMs` | `30000` | First lockout duration. |
148
+ | `lockoutMaxMs` | `900000` (15m) | Exponential-backoff cap. |
149
+ | `lockoutWindowMs` | `900000` (15m) | Idle time after which the failure counter resets. |
150
+ | `minPasswordLength` | `12` | Minimum password length (floor 8). |
151
+ | `secure` | `false` | `true` behind TLS: sets `Secure` + `__Host-` cookie, forces `Path=/`. |
152
+ | `sameSite` | `"Strict"` | Cookie `SameSite` (`Strict` or `Lax`). |
153
+ | `cookiePath` | `"/"` | Cookie `Path`. |
154
+ | `trustedOrigins` | `[]` | Extra `Origin` values accepted on state-changing POSTs. |
155
+ | `scrypt` | `{N:16384,r:8,p:1,keylen:64,maxmem:64MiB}` | Password hashing cost. |
156
+
157
+ > **Behind a TLS reverse proxy**, set `"secure": true` so the session cookie gets `Secure` and the
158
+ > `__Host-` prefix. On plain loopback HTTP the cookie cannot be `Secure` (browsers would drop it).
159
+
160
+ ## Security notes
161
+
162
+ - **Passwords:** scrypt with a per-user random salt, self-describing cost params, constant-time compare.
163
+ Unknown/disabled users are verified against a fixed dummy record so there is no timing/enumeration
164
+ oracle.
165
+ - **Sessions:** 256-bit random tokens, `HttpOnly; SameSite=Strict; Path=/` cookies, absolute + sliding
166
+ expiry, login-time token rotation (anti-fixation), logout revocation, background sweep.
167
+ - **Brute force:** per-(username, IP) lockout with exponential backoff; a legit user on another IP is
168
+ unaffected by an attacker's failures.
169
+ - **CSRF:** state-changing POSTs require a same-origin `Origin`/`Referer` (or a `trustedOrigins` entry);
170
+ default-deny when both are absent. This backs up `SameSite=Strict`.
171
+ - **Open redirect:** the post-login `next` target is reduced to a safe single-slash local path.
172
+ - **Audit:** login success/failure/lockout/logout are logged via `ctx.logger` with username + IP (never
173
+ the password).
174
+
175
+ ## Scope & tradeoffs (by design)
176
+
177
+ - Local username/password only — no SSO, no 2FA.
178
+ - Sessions are **in-memory**: a dsh restart requires everyone to log in again.
179
+ - No separate CSRF token — `SameSite=Strict` + Origin check is the chosen defense.
180
+ - `src/paths.js` is **self-contained** (it re-implements the `$DSH_HOME` → `~/.dsh` resolution rather
181
+ than importing `@deepseek-ai/dsh-home-paths`). This keeps the offline CLI working without the harness
182
+ on the module path and removes that package from the runtime peer set; only
183
+ `@deepseek-ai/dsh-host-webserver` is imported at runtime.
184
+
185
+ ## Composition ordering caveat
186
+
187
+ This bundle disables the stock `webserver` row. Any *later* composition layer (the profile's own
188
+ `cordis.patch.yml`, `$DSH_HOME/cordis.patch.yml`, or `--patch`) that flips `webserver` back to
189
+ `disabled: false` would create two providers of `webServer` and boot fails **loud** (duplicate service),
190
+ not silently. Don't re-enable the stock row while this plugin is installed.
191
+
192
+ ## Development / tests
193
+
194
+ ```bash
195
+ node --test
196
+ ```
197
+
198
+ The unit suites (policy, passwords, sessions, lockout, gate, login-page, users) are pure and run
199
+ standalone. `tests/integration.test.js` needs the runtime peers (`@deepseek-ai/cordis`,
200
+ `@deepseek-ai/dsh-host-webserver`); when they are not installed it **skips** with a reason. Run it inside
201
+ a built harness checkout to exercise the real subclass over HTTP.
202
+
203
+ ## License
204
+
205
+ MIT
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ /**
4
+ * dsh-auth — offline credential management for dsh-plugin-auth.
5
+ *
6
+ * Commands: add-user, passwd, list, remove, disable, enable.
7
+ * Writes $DSH_HOME/auth/users.json (atomic, mode 0600). Passwords are read from
8
+ * the TTY with echo masked, or from DSH_AUTH_BOOTSTRAP_USER/PASSWORD for
9
+ * non-interactive provisioning. Credentials never touch the Web settings UI.
10
+ */
11
+
12
+ import process from 'node:process'
13
+ import { readFileSync } from 'node:fs'
14
+ import { createInterface } from 'node:readline'
15
+ import { createUserStore } from '../src/users.js'
16
+ import { hashPassword, assessPasswordStrength } from '../src/passwords.js'
17
+ import { resolvePolicy } from '../src/policy.js'
18
+ import { usersFile, configFile } from '../src/paths.js'
19
+
20
+ const CTRL_C = String.fromCharCode(3)
21
+ const CTRL_D = String.fromCharCode(4)
22
+ const DEL = String.fromCharCode(127)
23
+
24
+ function loadPolicy() {
25
+ try {
26
+ return resolvePolicy(JSON.parse(readFileSync(configFile(), 'utf8')))
27
+ } catch {
28
+ return resolvePolicy({})
29
+ }
30
+ }
31
+
32
+ /** Read one visible line (used for the username). */
33
+ function prompt(query) {
34
+ return new Promise((resolve) => {
35
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
36
+ rl.question(query, (ans) => {
37
+ rl.close()
38
+ resolve(ans.trim())
39
+ })
40
+ })
41
+ }
42
+
43
+ /** Read one line with echo masked (raw mode on a TTY; plain read otherwise). */
44
+ function promptHidden(query) {
45
+ return new Promise((resolve) => {
46
+ const { stdin, stdout } = process
47
+ stdout.write(query)
48
+ const wasRaw = Boolean(stdin.isRaw)
49
+ if (stdin.isTTY) stdin.setRawMode(true)
50
+ stdin.resume()
51
+ let input = ''
52
+ const onData = (buf) => {
53
+ for (const ch of buf.toString('utf8')) {
54
+ if (ch === '\n' || ch === '\r' || ch === CTRL_D) {
55
+ if (stdin.isTTY) stdin.setRawMode(wasRaw)
56
+ stdin.pause()
57
+ stdin.removeListener('data', onData)
58
+ stdout.write('\n')
59
+ resolve(input)
60
+ return
61
+ } else if (ch === CTRL_C) {
62
+ if (stdin.isTTY) stdin.setRawMode(wasRaw)
63
+ stdout.write('\n')
64
+ process.exit(130)
65
+ } else if (ch === DEL || ch === '\b') {
66
+ input = input.slice(0, -1)
67
+ } else if (ch >= ' ') {
68
+ input += ch
69
+ }
70
+ }
71
+ }
72
+ stdin.on('data', onData)
73
+ })
74
+ }
75
+
76
+ function fail(message) {
77
+ console.error(`dsh-auth: ${message}`)
78
+ process.exit(1)
79
+ }
80
+
81
+ /** Resolve and validate a new password from the TTY (or bootstrap env). */
82
+ async function readNewPassword(policy) {
83
+ const bootstrap = process.env.DSH_AUTH_BOOTSTRAP_PASSWORD
84
+ let pw
85
+ if (bootstrap) {
86
+ pw = bootstrap
87
+ } else {
88
+ pw = await promptHidden('Password: ')
89
+ const confirm = await promptHidden('Confirm password: ')
90
+ if (pw !== confirm) fail('passwords do not match')
91
+ }
92
+ const strength = assessPasswordStrength(pw, { minLength: policy.minPasswordLength })
93
+ if (!strength.ok) fail(strength.reason)
94
+ return pw
95
+ }
96
+ const USAGE = `Usage: dsh-auth <command> [username]
97
+
98
+ Commands:
99
+ add-user <username> Create a user (prompts for a password).
100
+ passwd <username> Change a user's password.
101
+ list List users.
102
+ remove <username> Delete a user.
103
+ disable <username> Disable a user (keeps the record; blocks login).
104
+ enable <username> Re-enable a disabled user.
105
+
106
+ Environment:
107
+ DSH_HOME Auth data root (default ~/.dsh); data in $DSH_HOME/auth.
108
+ DSH_AUTH_BOOTSTRAP_USER Username for non-interactive add-user.
109
+ DSH_AUTH_BOOTSTRAP_PASSWORD Password for non-interactive add-user/passwd.
110
+ `
111
+
112
+ async function main() {
113
+ const [cmd, argUser] = process.argv.slice(2)
114
+ const store = createUserStore({ path: usersFile() })
115
+ const policy = loadPolicy()
116
+
117
+ switch (cmd) {
118
+ case 'add-user': {
119
+ const username = (argUser || process.env.DSH_AUTH_BOOTSTRAP_USER || '').trim() || (await prompt('Username: '))
120
+ if (!username) fail('username required')
121
+ if (await store.getUser(username)) fail(`user "${username}" already exists (use passwd to change it)`)
122
+ const password = await readNewPassword(policy)
123
+ const record = await hashPassword(password, policy.scrypt)
124
+ await store.upsertUser(username, { password: record, disabled: false })
125
+ console.log(`Created user "${username}" in ${usersFile()}`)
126
+ break
127
+ }
128
+ case 'passwd': {
129
+ const username = (argUser || '').trim()
130
+ if (!username) fail('username required')
131
+ if (!(await store.getUser(username))) fail(`no such user "${username}"`)
132
+ const password = await readNewPassword(policy)
133
+ const record = await hashPassword(password, policy.scrypt)
134
+ await store.upsertUser(username, { password: record })
135
+ console.log(`Updated password for "${username}"`)
136
+ break
137
+ }
138
+ case 'list': {
139
+ const users = await store.listUsers()
140
+ if (users.length === 0) {
141
+ console.log(`No users yet (${usersFile()})`)
142
+ break
143
+ }
144
+ users.sort((a, b) => a.username.localeCompare(b.username))
145
+ for (const u of users) {
146
+ const when = u.updatedAt ? new Date(u.updatedAt).toISOString() : '-'
147
+ console.log(`${u.disabled ? '[disabled] ' : ''}${u.username}\t${when}`)
148
+ }
149
+ break
150
+ }
151
+ case 'remove': {
152
+ const username = (argUser || '').trim()
153
+ if (!username) fail('username required')
154
+ const ok = await store.removeUser(username)
155
+ if (!ok) fail(`no such user "${username}"`)
156
+ console.log(`Removed "${username}"`)
157
+ break
158
+ }
159
+ case 'disable':
160
+ case 'enable': {
161
+ const username = (argUser || '').trim()
162
+ if (!username) fail('username required')
163
+ const ok = await store.setDisabled(username, cmd === 'disable')
164
+ if (!ok) fail(`no such user "${username}"`)
165
+ console.log(`${cmd === 'disable' ? 'Disabled' : 'Enabled'} "${username}"`)
166
+ break
167
+ }
168
+ case undefined:
169
+ case '-h':
170
+ case '--help':
171
+ process.stdout.write(USAGE)
172
+ break
173
+ default:
174
+ process.stderr.write(USAGE)
175
+ process.exit(2)
176
+ }
177
+ }
178
+
179
+ main().catch((err) => fail(err?.message || String(err)))
@@ -0,0 +1,26 @@
1
+ # dsh-plugin-auth composition patch.
2
+ #
3
+ # Applied as a bundle layer AFTER @deepseek-ai/dsh-web-app. It makes this plugin
4
+ # the SOLE provider of the `webServer` service by:
5
+ # 1. disabling the stock webserver row (no fiber, no provide), and
6
+ # 2. inserting an auth-webserver row that RE-PROVIDES `webServer` via a
7
+ # subclass of the stock WebServer (src/index.js default export).
8
+ #
9
+ # Hard contract (do not drop): the insert row MUST keep `inject: [webStartup]`
10
+ # and the {host,port} config. Downstream rows — web-runtime (@deepseek-ai/dsh-web-app)
11
+ # and connection — depend on `webServer` being provided and bound; a row that
12
+ # fails to re-provide it leaves them PENDING and boot fails loud.
13
+ #
14
+ # The row `name` is the installed package name and must resolve as a module
15
+ # specifier from the profile (install via tarball; see README "Install").
16
+
17
+ - id: webserver
18
+ disabled: true
19
+
20
+ - insert:
21
+ - id: auth-webserver
22
+ name: dsh-plugin-auth
23
+ inject: [webStartup]
24
+ config:
25
+ host: !!js ctx.webStartup.host ?? '127.0.0.1'
26
+ port: !!js ctx.webStartup.port ?? 3080
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "dsh-plugin-auth",
3
+ "version": "0.1.2",
4
+ "description": "Enterprise username/password authentication gate for the dsh Web UI. Out-of-tree plugin — no core changes; requires login before any page or API is reachable.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "bin": {
13
+ "dsh-auth": "./bin/dsh-auth.js"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "bin",
18
+ "cordis.patch.yml",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": "^22.19 || >=24"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test"
26
+ },
27
+ "dsh": {
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ }
31
+ }
32
+ }
package/src/gate.js ADDED
@@ -0,0 +1,127 @@
1
+ // @ts-check
2
+ /**
3
+ * The authentication gate: cookie parsing, the allow/deny decision tree, POST
4
+ * same-origin validation, and session-cookie serialization. Pure module (no
5
+ * peer imports) — it operates on plain {method, url, headers} request shapes and
6
+ * node:http-style response objects, so it is fully unit-testable with fakes.
7
+ */
8
+
9
+ import { cookieName } from './policy.js'
10
+ import { sanitizeNext } from './login-page.js'
11
+
12
+ /**
13
+ * Parse a Cookie header into a name→value map.
14
+ * @param {unknown} header
15
+ * @returns {Record<string, string>}
16
+ */
17
+ export function parseCookies(header) {
18
+ /** @type {Record<string, string>} */
19
+ const out = {}
20
+ if (typeof header !== 'string') return out
21
+ for (const part of header.split(';')) {
22
+ const eq = part.indexOf('=')
23
+ if (eq < 0) continue
24
+ const key = part.slice(0, eq).trim()
25
+ if (!key) continue
26
+ let val = part.slice(eq + 1).trim()
27
+ if (val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1)
28
+ try {
29
+ out[key] = decodeURIComponent(val)
30
+ } catch {
31
+ out[key] = val
32
+ }
33
+ }
34
+ return out
35
+ }
36
+
37
+ /** Read the session token from the request cookies. */
38
+ export function readSessionToken(req, policy) {
39
+ const cookies = parseCookies(req.headers?.['cookie'])
40
+ return cookies[cookieName(policy)]
41
+ }
42
+
43
+ /**
44
+ * Resolve the session for a request.
45
+ * @returns {{authenticated: boolean, token?: string, session?: import('./sessions.js').SessionRecord}}
46
+ */
47
+ export function evaluate(req, sessions, policy) {
48
+ const token = readSessionToken(req, policy)
49
+ if (!token) return { authenticated: false }
50
+ const session = sessions.validate(token)
51
+ if (!session) return { authenticated: false, token }
52
+ return { authenticated: true, token, session }
53
+ }
54
+
55
+ /** A navigation-type GET/HEAD wants an HTML page, so denial should redirect. */
56
+ export function isNavigationGet(req) {
57
+ const method = (req.method || 'GET').toUpperCase()
58
+ if (method !== 'GET' && method !== 'HEAD') return false
59
+ const mode = req.headers?.['sec-fetch-mode']
60
+ if (typeof mode === 'string' && mode.length) return mode === 'navigate'
61
+ const accept = String(req.headers?.['accept'] || '')
62
+ return accept.includes('text/html')
63
+ }
64
+
65
+ /**
66
+ * Deny an unauthenticated HTTP request: 302 to the login page for navigations
67
+ * (preserving the target as ?next), 401 JSON for everything else (API/XHR/POST).
68
+ */
69
+ export function deny(req, res, policy) {
70
+ if (isNavigationGet(req)) {
71
+ const next = sanitizeNext(req.url)
72
+ const location = `/__auth/login?next=${encodeURIComponent(next)}`
73
+ res.writeHead(302, { Location: location, 'Cache-Control': 'no-store' })
74
+ res.end()
75
+ return
76
+ }
77
+ const body = JSON.stringify({ error: 'unauthenticated', login: '/__auth/login' })
78
+ res.writeHead(401, {
79
+ 'content-type': 'application/json; charset=utf-8',
80
+ 'Cache-Control': 'no-store',
81
+ 'WWW-Authenticate': 'Session realm="dsh"',
82
+ })
83
+ res.end(body)
84
+ }
85
+
86
+ /**
87
+ * Same-origin check for state-changing POSTs. Requires Origin (or, failing
88
+ * that, Referer) to match the request Host, or to be in policy.trustedOrigins.
89
+ * Absent both headers, it denies (default-deny). This backs up SameSite=Strict.
90
+ */
91
+ export function isSameOrigin(req, policy) {
92
+ const host = req.headers?.['host']
93
+ const origin = req.headers?.['origin']
94
+ if (typeof origin === 'string' && origin.length) {
95
+ if (Array.isArray(policy.trustedOrigins) && policy.trustedOrigins.includes(origin)) return true
96
+ try {
97
+ if (host && new URL(origin).host === host) return true
98
+ } catch {
99
+ /* malformed Origin → fall through to deny */
100
+ }
101
+ return false
102
+ }
103
+ const referer = req.headers?.['referer']
104
+ if (typeof referer === 'string' && referer.length) {
105
+ try {
106
+ if (host && new URL(referer).host === host) return true
107
+ } catch {
108
+ /* malformed Referer → deny */
109
+ }
110
+ return false
111
+ }
112
+ return false
113
+ }
114
+
115
+ /** Serialize the Set-Cookie value that establishes a session. */
116
+ export function serializeSessionCookie(token, policy) {
117
+ const parts = [`${cookieName(policy)}=${token}`, `Path=${policy.cookiePath}`, 'HttpOnly', `SameSite=${policy.sameSite}`]
118
+ if (policy.secure) parts.push('Secure')
119
+ return parts.join('; ')
120
+ }
121
+
122
+ /** Serialize the Set-Cookie value that clears the session cookie. */
123
+ export function serializeClearCookie(policy) {
124
+ const parts = [`${cookieName(policy)}=`, `Path=${policy.cookiePath}`, 'HttpOnly', `SameSite=${policy.sameSite}`, 'Max-Age=0']
125
+ if (policy.secure) parts.push('Secure')
126
+ return parts.join('; ')
127
+ }