1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

feat(frontend): import pasted cookies (extension JSON, Netscape, header string) into cookie rules

This commit is contained in:
TheGeneralist 2026-10-24 23:26:39 +02:00
parent 4c85297b74
commit 80a24f0ab4
4 changed files with 575 additions and 7 deletions

View file

@ -57,6 +57,7 @@ Contributing? See the [contributor guide](../CONTRIBUTING.md) and its ecosystem
- **Text notes** — capture a plain-text or Markdown note with a title and no URL; the byte-preserving note is stored as a normal deduplicated blob and opens in the usual entry-rail preview
- **In-progress capture indicator** — running captures appear as a compact spinner row in the entries list until they finish, replacing the earlier grey skeleton block
- **Dark mode** — toggle light/dark from the topbar or auth screen, or configure System/Light/Dark under **Settings › Profile**
- **Cookie rules** — global, wildcard, or regex rules under **Settings › Cookies** inject custom cookies into capture network requests (yt-dlp, HTTP downloads, web snapshots). The input accepts native JSON, browser extension exports (Cookie-Editor, EditThisCookie), Netscape `cookies.txt`, or `Cookie:` header strings with automatic formatting and collision-safe merge on paste
## Quick Start

View file

@ -12,6 +12,7 @@ import {
} from '../api.js'
import { describeExpiry, formatTimestamp } from '../utils.js'
import { useTheme } from '../useTheme.js'
import { normalizeCookiesInput, pasteCookies } from '../cookieImport.js'
const ROLE_ADMIN = 4
const ROLE_OWNER = 8
@ -683,9 +684,9 @@ function CookiesTab() {
async function handleAdd(e) {
e.preventDefault()
// Validate JSON
try { JSON.parse(cookiesInput) } catch {
setAddMsg({ ok: false, text: 'cookies must be valid JSON, e.g. {"session": "abc"}' })
const normalized = normalizeCookiesInput(cookiesInput)
if (!normalized.ok) {
setAddMsg({ ok: false, text: normalized.error })
return
}
setAdding(true); setAddMsg(null)
@ -693,7 +694,7 @@ function CookiesTab() {
await createCookieRule(
patternKind === 'global' ? null : urlPattern.trim(),
patternKind,
cookiesInput,
normalized.json,
)
setUrlPattern('')
setCookiesInput('{}')
@ -707,6 +708,44 @@ function CookiesTab() {
}
}
function handlePasteAdd(e) {
const clip = e.clipboardData?.getData('text')
if (!clip) return
const start = e.target.selectionStart ?? 0
const end = e.target.selectionEnd ?? 0
const action = pasteCookies(cookiesInput, start, end, clip)
if (!action) return
e.preventDefault()
if (action.error) {
setAddMsg({ ok: false, text: action.error })
} else {
setCookiesInput(action.text)
setAddMsg({ ok: true, text: action.message })
}
}
function handlePasteEdit(ruleUid, e) {
const clip = e.clipboardData?.getData('text')
if (!clip) return
const current = edits[ruleUid]?.cookiesInput ?? ''
const start = e.target.selectionStart ?? 0
const end = e.target.selectionEnd ?? 0
const action = pasteCookies(current, start, end, clip)
if (!action) return
e.preventDefault()
if (action.error) {
setEdits(prev => ({
...prev,
[ruleUid]: { ...prev[ruleUid], msg: { ok: false, text: action.error } },
}))
} else {
setEdits(prev => ({
...prev,
[ruleUid]: { ...prev[ruleUid], cookiesInput: action.text, msg: { ok: true, text: action.message } },
}))
}
}
async function handleDelete(ruleUid) {
try {
await deleteCookieRule(ruleUid)
@ -733,13 +772,14 @@ function CookiesTab() {
async function saveEdit(rule) {
const edit = edits[rule.rule_uid]
try { JSON.parse(edit.cookiesInput) } catch {
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], msg: { ok: false, text: 'Invalid JSON' } } }))
const normalized = normalizeCookiesInput(edit.cookiesInput)
if (!normalized.ok) {
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], msg: { ok: false, text: normalized.error } } }))
return
}
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], saving: true, msg: null } }))
try {
await updateCookieRule(rule.rule_uid, { cookies_json: edit.cookiesInput })
await updateCookieRule(rule.rule_uid, { cookies_json: normalized.json })
cancelEdit(rule.rule_uid)
await load()
} catch (err) {
@ -785,6 +825,7 @@ function CookiesTab() {
style={{ fontFamily: 'monospace', fontSize: 12, width: '100%', minHeight: 60 }}
value={edit.cookiesInput}
onChange={ev => setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], cookiesInput: ev.target.value } }))}
onPaste={ev => handlePasteEdit(rule.rule_uid, ev)}
/>
{edit.msg && <div className={`form-msg form-msg--${edit.msg.ok ? 'ok' : 'err'}`}>{edit.msg.text}</div>}
<div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
@ -847,9 +888,13 @@ function CookiesTab() {
style={{ fontFamily: 'monospace', fontSize: 13, minHeight: 70 }}
value={cookiesInput}
onChange={e => setCookiesInput(e.target.value)}
onPaste={handlePasteAdd}
placeholder='{"SESSION": "abc123", "token": "xyz"}'
required
/>
<span className="muted" style={{ fontSize: 12, display: 'block', marginTop: 4 }}>
Paste JSON object, extension export, Netscape cookies.txt, or header string.
</span>
</div>
{addMsg && <div className={`form-msg form-msg--${addMsg.ok ? 'ok' : 'err'}`}>{addMsg.text}</div>}
<button className="btn-primary" type="submit" disabled={adding}>

View file

@ -0,0 +1,233 @@
/**
* Converts cookies pasted into Settings › Cookies into the cookie-rule format
* the server accepts: a JSON object whose values are all strings
* ({"name": "value"}).
*
* Recognised inputs:
* - archivr JSON: {"session": "abc"}
* - extension JSON: [{"name": "session", "value": "abc", "domain": …}, …]
* (Cookie-Editor / EditThisCookie export; a single such object also works)
* - Netscape: cookies.txt lines, including `#HttpOnly_` prefixed ones
* - header string: session=abc; theme=dark (optional `Cookie:` prefix)
*
* Rules are scoped by URL pattern, so domain/path/expiry/flags are dropped.
*/
const FORMAT_LABELS = {
archivr: 'archivr JSON',
extension: 'extension JSON',
netscape: 'Netscape',
header: 'header string',
}
// Same character rules as the extension session cookies (browserData.js).
const INVALID_NAME = /[\x00-\x1f\x7f ;=]/
const INVALID_VALUE = /[\x00-\x1f\x7f;]/
const NETSCAPE_HEADER = /^#\s*Netscape HTTP Cookie File/i
const HTTP_ONLY_PREFIX = '#HttpOnly_'
const BOOL_FIELD = /^(TRUE|FALSE)$/i
function fail(error) {
return { ok: false, error }
}
function checkPair(name, value) {
if (!name || INVALID_NAME.test(name)) {
return `Invalid cookie name ${JSON.stringify(name)}: names cannot be empty or contain spaces, ';' or '='.`
}
if (INVALID_VALUE.test(value)) {
return `Invalid value for cookie ${JSON.stringify(name)}: values cannot contain ';' or control characters.`
}
return null
}
function converted(format, entries) {
for (const [name, value] of entries) {
const err = checkPair(name, value)
if (err) return fail(err)
}
if (entries.length === 0) return fail(`No cookies found in ${FORMAT_LABELS[format]}.`)
return { ok: true, format, cookies: entries }
}
function isPlainObject(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v)
}
function extensionCookie(item, index) {
if (!isPlainObject(item) || typeof item.name !== 'string' || typeof item.value !== 'string') {
return { error: `Cookie #${index + 1} needs string "name" and "value" fields.` }
}
return { entry: [item.name, item.value] }
}
function parseJson(text) {
let data
try { data = JSON.parse(text) } catch {
return fail('Invalid JSON.')
}
if (Array.isArray(data)) {
const entries = []
for (let i = 0; i < data.length; i++) {
const { entry, error } = extensionCookie(data[i], i)
if (error) return fail(error)
entries.push(entry)
}
return converted('extension', entries)
}
if (!isPlainObject(data)) {
return fail('Cookies JSON must be an object like {"session": "abc"} or an extension export array.')
}
const values = Object.values(data)
if (values.every(v => typeof v === 'string')) {
// Native format: passed through as-is (the server is the authority on it).
return { ok: true, format: 'archivr', cookies: Object.entries(data) }
}
// One cookie copied out of an extension export ({"name", "value", "domain", …}).
if (typeof data.name === 'string' && typeof data.value === 'string') {
return converted('extension', [[data.name, data.value]])
}
return fail('Cookie values must all be strings, e.g. {"session": "abc"}.')
}
function netscapeFields(line) {
const tabbed = line.split('\t')
if (tabbed.length >= 7) return tabbed
// Copies out of a terminal or chat often turn tabs into spaces.
return line.trim().split(/\s+/)
}
function looksLikeNetscapeLine(line) {
const fields = netscapeFields(line)
return fields.length >= 6 && BOOL_FIELD.test(fields[1]) && BOOL_FIELD.test(fields[3])
}
function cookieLines(text) {
return text.split(/\r?\n/)
.map(line => line.trimEnd())
.filter(line => line.trim() !== '')
.map(line => line.startsWith(HTTP_ONLY_PREFIX) ? line.slice(HTTP_ONLY_PREFIX.length) : line)
.filter(line => !line.startsWith('#'))
}
function parseNetscape(text) {
const entries = []
for (const line of cookieLines(text)) {
if (!looksLikeNetscapeLine(line)) {
return fail(`Not a Netscape cookie line: ${line.slice(0, 80)}`)
}
const fields = netscapeFields(line)
const sep = fields.length === line.split('\t').length ? '\t' : ' '
entries.push([fields[5], fields.slice(6).join(sep)])
}
return converted('netscape', entries)
}
function parseHeader(text) {
const body = text.trim().replace(/^cookie:\s*/i, '')
const entries = []
for (const part of body.split(/;|\r?\n/)) {
const pair = part.trim()
if (pair === '') continue
const eq = pair.indexOf('=')
if (eq <= 0) return fail(`Expected name=value, got ${JSON.stringify(pair.slice(0, 80))}.`)
entries.push([pair.slice(0, eq).trim(), pair.slice(eq + 1).trim()])
}
return converted('header', entries)
}
/**
* Parses cookies in any supported format.
* @param {string} text
* @returns {{ok: true, format: string, cookies: Array<[string, string]>} | {ok: false, error: string}}
*/
export function parseCookies(text) {
const trimmed = (text ?? '').trim()
if (trimmed === '') return fail('No cookies found.')
if (trimmed.startsWith('{') || trimmed.startsWith('[')) return parseJson(trimmed)
const firstLine = cookieLines(trimmed)[0]
if (NETSCAPE_HEADER.test(trimmed) || (firstLine !== undefined && looksLikeNetscapeLine(firstLine))) {
return parseNetscape(trimmed)
}
return parseHeader(trimmed)
}
/**
* Merges cookie lists; `incoming` wins on a name collision.
* @returns {{cookies: Object<string, string>, added: number, replaced: number}}
*/
export function mergeCookies(base, incoming) {
const merged = new Map(base)
let added = 0
let replaced = 0
for (const [name, value] of incoming) {
if (!merged.has(name)) added++
else if (merged.get(name) !== value) replaced++
merged.set(name, value)
}
// Object.fromEntries keeps names such as "__proto__" as own properties.
return { cookies: Object.fromEntries(merged), added, replaced }
}
export function formatCookies(cookies) {
return JSON.stringify(cookies, null, 2)
}
function plural(n, word) {
return `${n} ${word}${n === 1 ? '' : 's'}`
}
/**
* Normalises a cookie-rule textarea before it is sent to the server.
* Native JSON is sent unchanged; other formats are converted.
* @returns {{ok: true, json: string} | {ok: false, error: string}}
*/
export function normalizeCookiesInput(text) {
const parsed = parseCookies(text)
if (!parsed.ok) return parsed
if (parsed.format === 'archivr') return { ok: true, json: text }
return { ok: true, json: formatCookies(Object.fromEntries(parsed.cookies)) }
}
/**
* Decides what pasting `clip` over the selection [start, end) of `current` does.
*
* Returns null when the browser's normal paste should run: the result is
* already a valid cookie object (ordinary JSON editing), or the clipboard is
* not cookies at all. Otherwise the caller prevents the paste and either
* replaces the textarea with `text` or shows `error`.
*
* @returns {null | {text: string, message: string} | {error: string}}
*/
export function pasteCookies(current, start, end, clip) {
const before = current.slice(0, start)
const after = current.slice(end)
const combined = parseCookies(before + clip + after)
if (combined.ok && combined.format === 'archivr') return null
const incoming = parseCookies(clip)
if (!incoming.ok) return null
const label = FORMAT_LABELS[incoming.format]
const count = plural(incoming.cookies.length, 'cookie')
const rest = before + after
if (rest.trim() === '') {
return {
text: formatCookies(Object.fromEntries(incoming.cookies)),
message: `Converted ${count} from ${label}.`,
}
}
const existing = parseCookies(rest)
if (!existing.ok) {
return {
error: `Clipboard has ${count} (${label}), but the existing content isn't valid cookies (${existing.error}) — fix or clear it, then paste again.`,
}
}
const { cookies, added, replaced } = mergeCookies(existing.cookies, incoming.cookies)
const message = existing.cookies.length === 0
? `Converted ${count} from ${label}.`
: `Merged ${count} from ${label}: ${added} added, ${replaced} replaced.`
return { text: formatCookies(cookies), message }
}

View file

@ -0,0 +1,289 @@
import { describe, expect, test } from 'bun:test'
import {
parseCookies,
mergeCookies,
formatCookies,
normalizeCookiesInput,
pasteCookies,
} from './cookieImport.js'
// User's exact prompt sample: extension JSON
const EXTENSION_JSON_SAMPLE = `[
{
"domain": "127.0.0.1",
"expirationDate": 1794836374,
"hostOnly": true,
"httpOnly": true,
"name": "session",
"path": "/",
"sameSite": "strict",
"secure": false,
"session": false,
"storeId": null,
"value": "sess_2242ce38c8c54a49b80fab32e8556b82"
}
]`
// User's exact prompt sample: Netscape format
const NETSCAPE_SAMPLE = `# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by Cookie-Editor
#HttpOnly_127.0.0.1 FALSE / FALSE 1794836374 session sess_2242ce38c8c54a49b80fab32e8556b82`
// User's exact prompt sample: header string
const HEADER_SAMPLE = 'session=sess_2242ce38c8c54a49b80fab32e8556b82'
describe('parseCookies', () => {
test('parses extension JSON array', () => {
const res = parseCookies(EXTENSION_JSON_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('extension')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses single extension cookie object', () => {
const single = JSON.parse(EXTENSION_JSON_SAMPLE)[0]
const res = parseCookies(JSON.stringify(single))
expect(res.ok).toBe(true)
expect(res.format).toBe('extension')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses Netscape cookie file with #HttpOnly_ and whitespace-separated fields', () => {
const res = parseCookies(NETSCAPE_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('netscape')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses standard tab-separated Netscape file', () => {
const tabbed = [
'# Netscape HTTP Cookie File',
'.example.com\tTRUE\t/\tFALSE\t1794836374\tsession\tsess_123',
'#HttpOnly_.example.com\tTRUE\t/\tTRUE\t1794836374\tcsrf\ttoken_456',
].join('\n')
const res = parseCookies(tabbed)
expect(res.ok).toBe(true)
expect(res.format).toBe('netscape')
expect(res.cookies).toEqual([
['session', 'sess_123'],
['csrf', 'token_456'],
])
})
test('handles CRLF line endings in Netscape file', () => {
const crlf = NETSCAPE_SAMPLE.replace(/\n/g, '\r\n')
const res = parseCookies(crlf)
expect(res.ok).toBe(true)
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses header string', () => {
const res = parseCookies(HEADER_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('header')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses header string with Cookie: prefix and multiple pairs', () => {
const res = parseCookies('Cookie: a=1; b=2=3; c="quoted"')
expect(res.ok).toBe(true)
expect(res.format).toBe('header')
expect(res.cookies).toEqual([
['a', '1'],
['b', '2=3'], // value preserves subsequent '='
['c', '"quoted"'],
])
})
test('parses multiline header strings (newline separated)', () => {
const res = parseCookies('a=1\nb=2\r\nc=3')
expect(res.ok).toBe(true)
expect(res.cookies).toEqual([['a', '1'], ['b', '2'], ['c', '3']])
})
test('identifies native archivr JSON', () => {
const res = parseCookies('{"session": "sess_2242ce38c8c54a49b80fab32e8556b82"}')
expect(res.ok).toBe(true)
expect(res.format).toBe('archivr')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses empty object as native archivr JSON', () => {
const res = parseCookies('{}')
expect(res.ok).toBe(true)
expect(res.format).toBe('archivr')
expect(res.cookies).toEqual([])
})
test('rejects empty string', () => {
expect(parseCookies('').ok).toBe(false)
expect(parseCookies(' ').ok).toBe(false)
})
test('rejects cookie name with space or semicolon', () => {
expect(parseCookies('bad name=val').ok).toBe(false)
expect(parseCookies('bad;name=val').ok).toBe(false)
})
test('rejects cookie value with control chars', () => {
expect(parseCookies('name=val\x00x').ok).toBe(false)
})
test('rejects malformed extension entry missing value', () => {
const res = parseCookies('[{"name": "foo"}]')
expect(res.ok).toBe(false)
expect(res.error).toMatch(/needs string "name" and "value"/)
})
})
describe('mergeCookies', () => {
test('merges base and incoming; incoming overwrites collision', () => {
const base = [['a', '1'], ['b', '2']]
const incoming = [['b', 'overwritten'], ['c', '3']]
const res = mergeCookies(base, incoming)
expect(res.cookies).toEqual({
a: '1',
b: 'overwritten',
c: '3',
})
expect(res.added).toBe(1)
expect(res.replaced).toBe(1)
})
test('detects unchanged values as not replaced', () => {
const base = [['a', '1']]
const incoming = [['a', '1']]
const res = mergeCookies(base, incoming)
expect(res.added).toBe(0)
expect(res.replaced).toBe(0)
})
test('preserves reserved property names like __proto__', () => {
const res = mergeCookies([], [['__proto__', 'safe']])
expect(Object.hasOwn(res.cookies, '__proto__')).toBe(true)
expect(res.cookies['__proto__']).toBe('safe')
})
})
describe('normalizeCookiesInput', () => {
test('passes native JSON string through verbatim', () => {
const native = '{\n "session": "abc"\n}'
expect(normalizeCookiesInput(native)).toEqual({ ok: true, json: native })
})
test('converts extension JSON to pretty JSON', () => {
const res = normalizeCookiesInput(EXTENSION_JSON_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('converts Netscape to pretty JSON', () => {
const res = normalizeCookiesInput(NETSCAPE_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('converts header string to pretty JSON', () => {
const res = normalizeCookiesInput(HEADER_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('returns error for invalid input', () => {
const res = normalizeCookiesInput('not a valid cookie string')
expect(res.ok).toBe(false)
})
})
describe('pasteCookies', () => {
test('returns null if entire pasted result is already valid native JSON', () => {
// Normal JSON typing/editing: pasting `"abc"` into `{"a": }`
const current = '{"a": }'
// Cursor right after the space: start = 6, end = 6
const res = pasteCookies(current, 6, 6, '"abc"')
expect(res).toBeNull()
})
test('returns null if clipboard is not cookies at all', () => {
const res = pasteCookies('{}', 0, 2, 'hello world')
expect(res).toBeNull()
})
test('converts clipboard when textarea is default empty object and selected entirely', () => {
const res = pasteCookies('{}', 0, 2, EXTENSION_JSON_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toBeUndefined()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Converted 1 cookie from extension JSON/)
})
test('converts clipboard when textarea is completely empty', () => {
const res = pasteCookies('', 0, 0, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Converted 1 cookie from header string/)
})
test('merges into existing native JSON', () => {
const current = '{\n "existing": "val"\n}'
const res = pasteCookies(current, current.length, current.length, NETSCAPE_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toBeUndefined()
expect(JSON.parse(res.text)).toEqual({
existing: 'val',
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Merged 1 cookie from Netscape: 1 added, 0 replaced/)
})
test('overwrites existing keys when pasting newer values', () => {
const current = '{\n "session": "old_value"\n}'
const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Merged 1 cookie from header string: 0 added, 1 replaced/)
})
test('merges into existing Netscape content (if user already had that in textarea)', () => {
const current = NETSCAPE_SAMPLE
const clip = 'extra=value_123'
const res = pasteCookies(current, current.length, current.length, clip)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
extra: 'value_123',
})
})
test('returns error when clipboard has cookies but remaining textarea is invalid', () => {
const current = '{"broken json: '
const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toMatch(/existing content isn't valid cookies/)
})
})