#!/bin/sh
# /share to the artifact publisher, on a pseudo-terminal against a fake publisher (fake_server; the
# real one and a real token are never used): the overlay names the destination and sends nothing
# before the yes, the request is a POST of the page with the token as a bearer, a large page goes up
# as a blob first, a refused token is explained without the token, and auto falls back to the
# gist unless a token is stored and artifactsUrl is set.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-share.XXXXXX")
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/ws" "$T/home" "$T/bin"
export HOME="$T/home" ANTHROPIC_API_KEY=pic-share-test-key PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline
export T PIC_NO_NATIVE_CLIPBOARD=1
# a developer's own publisher token and address must never reach a test
unset PIC_TEST_PASSPHRASE HTML_PUBLISHER_TOKEN HTML_PUBLISHER_URL
TOKEN="pubtok-$$-7c1e9"
cat > "$T/bin/gh" <<'GH'
#!/bin/sh
printf '%s\n' "$*" >> "$GH_LOG.args"
cat > "$GH_LOG.stdin"
echo https://gist.example/secret123
GH
chmod +x "$T/bin/gh"
export GH_LOG="$T/gh" PATH="$T/bin:$PATH"
printf '{"id":"abc123","tip":"t","viewerUrl":"https://pub.example/v/abc123"}' > "$T/pub.json"
printf '{"error":"Unauthorized"}' > "$T/denied.json"

serve() { # SPEC...: a fresh fake publisher, its port in $PORT, requests in $T/log
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 120 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "server"; sleep 0.05; done
    PORT=$(cat "$T/port")
}
serve "status:201:$T/pub.json"
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
    "$PORT" > "$T/models.json"
pic() { "$PIC" --db "$T/j" --workspace "$T/ws" "$@"; }
drive() { # NAME: run pic's terminal with the script on stdin
    name=$1
    shift
    "$DRIVE" "$T/$name.tx" 100 24 "$PIC" --tui-mode regular --db "$T/j$name" --workspace "$T/ws" --model fake/m "$@" ||
        fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -8)"
}
cat > "$T/pi.jsonl" <<'JSONL'
{"type":"session","version":3,"id":"abc","timestamp":"2026-01-01T00:00:00.000Z","cwd":"/x"}
{"type":"message","id":"m1","parentId":null,"message":{"role":"user","content":"What is 2 + 2?"}}
{"type":"message","id":"m2","parentId":"m1","message":{"role":"assistant","content":[{"type":"text","text":"It is 4, said the answer."}]}}
JSONL
# a page over 256 KB: one answer of about 490 KB
awk 'BEGIN {
    s = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789 "
    for (i = 0; i < 12; i++) s = s s
    printf "{\"type\":\"session\",\"version\":3,\"id\":\"big\",\"timestamp\":\"2026-01-01T00:00:00.000Z\",\"cwd\":\"/x\"}\n"
    printf "{\"type\":\"message\",\"id\":\"m1\",\"parentId\":null,\"message\":{\"role\":\"user\",\"content\":\"hi\"}}\n"
    printf "{\"type\":\"message\",\"id\":\"m2\",\"parentId\":\"m1\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"%s\"}]}}\n", s
}' > "$T/big.jsonl"
body() { # FILE: the index.html a request carried, decoded
    sed -n 's/.*"index.html":"\([^"]*\)".*/\1/p' "$1" | { base64 -d 2> /dev/null || base64 -D; }
}

# The token is added the way a user adds it.
printf '%s\n' "$TOKEN" | "$PIC" login artifacts > "$T/login.out" 2>&1 || { cat "$T/login.out" >&2; fail "login artifacts"; }
! grep -qF "$TOKEN" "$T/login.out" || fail "login printed the token"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null

# 1. Auto with a token and an address: the overlay names the publisher; no sends nothing.
drive no <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
expect leaves this machine for the artifact publisher
wait 200
send n
expect not shared
send \x04\x04
EOF
[ ! -e "$T/log/1.req" ] || fail "no: a request went out before the yes"
[ ! -e "$T/gh.args" ] || fail "no: gh ran"
printf 'PASS: /share names the artifact publisher and sends nothing without a yes\n'

# 2. Yes: one POST of the page, the token as a bearer.
drive yes <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
wait 200
send y
expect shared to the artifact publisher
expect https://pub.example/v/abc123
send \x04\x04
EOF
[ -s "$T/log/1.req" ] || fail "yes: no request"
[ ! -e "$T/log/2.req" ] || fail "yes: more than one request"
head -1 "$T/log/1.req" | grep -q '^POST /api/artifacts HTTP' || fail "yes: $(head -1 "$T/log/1.req")"
grep -qi "^authorization: Bearer $TOKEN" "$T/log/1.req" || fail "yes: no bearer token"
body "$T/log/1.req" | grep -q 'It is 4, said the answer' || fail "yes: the page lacks the answer"
body "$T/log/1.req" | grep -qi '<!doctype html>' || fail "yes: not an HTML page"
[ ! -e "$T/gh.args" ] || fail "yes: gh ran"
! grep -qF "$TOKEN" "$T/yes.tx" || fail "yes: the token reached the screen"
printf 'PASS: /share publishes the page with the stored token, and not through gh\n'

# 3. A page over 256 KB goes up as a blob, then its pointer is committed.
serve "status:200:-" "status:201:$T/pub.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
drive blob <<EOF
expect pic fake/m
send /import $T/big.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
wait 200
send y
expect shared to the artifact publisher
send \x04\x04
EOF
head -1 "$T/log/1.req" | grep -q '^PUT /api/blobs/[0-9a-f]\{64\} HTTP' || fail "blob: $(head -1 "$T/log/1.req")"
head -1 "$T/log/2.req" | grep -q '^POST /api/artifacts HTTP' || fail "blob: second was $(head -1 "$T/log/2.req")"
body "$T/log/2.req" | grep -q '^artifact-blob 1' || fail "blob: no pointer"
sha=$(head -1 "$T/log/1.req" | sed 's/.*blobs\/\([0-9a-f]*\) .*/\1/')
body "$T/log/2.req" | grep -q "^sha256 $sha" || fail "blob: the pointer names another blob"
# the hash is the page's, by the system's tool and not pic's own
perl -0777 -pe 's/\A.*?\r\n\r\n//s' "$T/log/1.req" > "$T/page.bin"
if command -v shasum > /dev/null; then want=$(shasum -a 256 "$T/page.bin" | cut -d' ' -f1); else want=$(sha256sum "$T/page.bin" | cut -d' ' -f1); fi
[ "$sha" = "$want" ] || fail "blob: the blob is named $sha, the page hashes to $want"
body "$T/log/2.req" | grep -q "^size $(wc -c < "$T/page.bin" | tr -d ' ')\$" || fail "blob: the pointer's size is not the page's"
printf 'PASS: a page over 256 KB goes up as a blob and the artifact holds its pointer\n'

# 4. A refused token is explained, without the token.
serve "status:401:$T/denied.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
drive denied <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
wait 200
send y
expect refused the token
send \x04\x04
EOF
! grep -qF "$TOKEN" "$T/denied.tx" || fail "denied: the token reached the screen"
printf 'PASS: a refused token is said so and never shown\n'

# 5. Auto without an address, and gist chosen with a token: the gist, as before.
pic settings --unset artifactsUrl > /dev/null
drive nourl <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation as a secret GitHub gist
send n
expect not shared
send \x04\x04
EOF
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
pic settings sessionShareDestination gist > /dev/null
drive gist <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation as a secret GitHub gist
wait 200
send y
expect shared as a secret gist
send \x04\x04
EOF
[ "$(cat "$T/gh.args")" = "gist create -" ] || fail "gist: gh got $(cat "$T/gh.args" 2> /dev/null)"
printf 'PASS: auto needs a token and an address; gist keeps the gist\n'

# 6. The variable counts as a token for auto: with none stored, the publisher is still named.
pic settings --unset sessionShareDestination > /dev/null
pic logout artifacts > /dev/null
(
    export HTML_PUBLISHER_TOKEN="envtok-$$"
    drive envtok <<EOF
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
send n
expect not shared
send \x04\x04
EOF
)
printf 'PASS: HTML_PUBLISHER_TOKEN is enough for auto to choose the publisher\n'

# 7. The command /share runs: where it goes, and a page on stdin.
serve "status:201:$T/pub.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
[ "$(pic share --where)" = "gist" ] || fail "share --where: $(pic share --where)"
printf '%s\n' "$TOKEN" | "$PIC" login artifacts > /dev/null 2>&1
[ "$(pic share --where)" = "artifacts http://127.0.0.1:$PORT" ] || fail "share --where with a token: $(pic share --where)"
[ "$(printf '<!doctype html><p>cli page</p>' | pic share --yes)" = "https://pub.example/v/abc123" ] || fail "share: no link"
body "$T/log/1.req" | grep -q 'cli page' || fail "share: the page was not sent"
pic settings artifactsUrl "http://127.0.0.1:1" > /dev/null
if printf '<!doctype html>' | pic share --yes > "$T/out" 2> "$T/err"; then fail "share: an unreachable publisher succeeded"; fi
grep -q 'could not reach the publisher' "$T/err" || fail "share: $(cat "$T/err")"
! grep -qF "$TOKEN" "$T/err" || fail "share: the token reached stderr"
printf 'PASS: pic share says where /share goes, publishes stdin and reports a publisher it cannot reach\n'

# 8. Nothing is sent without a yes: stdin is the page, so a prompt on the terminal is the only other way.
serve "status:201:$T/pub.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
if printf '<!doctype html><p>piped</p>' | pic share > "$T/out" 2> "$T/err"; then fail "consent: a piped share went out with no yes"; fi
grep -q 'pass --yes' "$T/err" || fail "consent: $(cat "$T/err")"
[ ! -e "$T/log/1.req" ] || fail "consent: a request went out with no yes"
printf '<!doctype html><p>on a terminal</p>' > "$T/page.html"
cat > "$T/shareit.sh" <<'SH'
#!/bin/sh
exec "$PIC" --db "$T/jshare" --workspace "$T/ws" share < "$T/page.html"
SH
chmod +x "$T/shareit.sh"
export PIC
if "$DRIVE" "$T/ttyno.tx" 100 24 "$T/shareit.sh" > /dev/null 2>&1 << 'EOS'; then fail "consent: an n sent the page"; fi
expect (y/N)
send n\r
EOS
grep -q 'not sent' "$T/ttyno.tx" || fail "consent: n was not answered with not sent"
[ ! -e "$T/log/1.req" ] || fail "consent: a request went out after n"
"$DRIVE" "$T/ttyyes.tx" 100 24 "$T/shareit.sh" << EOS || fail "consent: y did not share: $(tail -c 300 "$T/ttyyes.tx")"
expect Send this 1 KB page to http://127.0.0.1:$PORT
send y\r
expect https://pub.example/v/abc123
EOS
body "$T/log/1.req" | grep -q 'on a terminal' || fail "consent: the page was not sent after y"
serve "status:201:$T/pub.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
[ "$(printf '<p>x</p>' | pic share --yes)" = "https://pub.example/v/abc123" ] || fail "consent: --yes"
[ -s "$T/log/1.req" ] || fail "consent: --yes sent nothing"
printf 'PASS: pic share sends nothing without a prompt answered y on the terminal or --yes\n'

# 9. Changing the publisher origin while the overlay is open refuses rather than redirecting the page.
serve "status:201:$T/pub.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
rm -f "$T/shown" "$T/changed"
(
    i=0
    while [ ! -e "$T/shown" ] && [ "$i" -lt 600 ]; do i=$((i + 1)); sleep 0.05; done
    pic settings artifactsUrl "http://127.0.0.1:1" > /dev/null
    : > "$T/changed"
) &
cpid=$!
drive pinned <<EOS
expect pic fake/m
send /import $T/pi.jsonl\r
expect imported
send /share\r
expect Share this conversation to the artifact publisher
touch $T/shown
waitfile $T/changed
send y
expect could not share
send \x04\x04
EOS
wait "$cpid" || :
[ ! -e "$T/log/1.req" ] || fail "pinned: a request went out after the publisher changed"
pic settings artifactsUrl 2>&1 | grep -q '127.0.0.1:1$' || fail "pinned: the setting did not change"
printf 'PASS: changing the publisher origin while the overlay is open refuses instead of redirecting\n'

# 10. The viewer link is shown only when it is https (or this machine) and holds no control character.
for bad in 'https://pub.example/v/a\u009bb' 'https://pub.example/v/a\u001b[2Jb' 'http://pub.example/v/a' 'https://pub.example/v/a b' 'javascript:alert(1)'; do
    printf '{"viewerUrl":"%s"}' "$bad" > "$T/badlink.json"
    serve "status:201:$T/badlink.json"
    pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
    if printf '<p>x</p>' | pic share --yes > "$T/out" 2> "$T/err"; then fail "link: shown for $bad: $(cat "$T/out")"; fi
    [ ! -s "$T/out" ] || fail "link: output for $bad"
    grep -q 'had no link' "$T/err" || fail "link $bad: $(cat "$T/err")"
done
printf '{"viewerUrl":"http://127.0.0.1:9/v/ok"}' > "$T/badlink.json"
serve "status:201:$T/badlink.json"
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
[ "$(printf '<p>x</p>' | pic share --yes)" = "http://127.0.0.1:9/v/ok" ] || fail "link: a loopback http link was refused"
printf 'PASS: a viewer link with a control character, a space or a plain http host is not shown\n'

# 11. artifactsUrl is https, or http to this machine only; the setting and the upload agree.
for bad in http://example.com "https://x y" ftp://host http://127.0.0.1.evil.com; do
    if pic settings artifactsUrl "$bad" > "$T/out" 2>&1; then fail "setting: accepted $bad"; fi
done
pic settings artifactsUrl https://pub.example > /dev/null || fail "setting: refused https"
pic settings artifactsUrl "http://localhost:8080" > /dev/null || fail "setting: refused loopback http"
printf 'PASS: artifactsUrl takes https:// or loopback http:// and nothing else\n'

# 12. HTML_PUBLISHER_URL is the address when artifactsUrl is unset, as the variable is the token's fallback.
serve "status:201:$T/pub.json"
pic settings --unset artifactsUrl > /dev/null
[ "$(pic share --where)" = "gist" ] || fail "env url: $(pic share --where)"
[ "$(HTML_PUBLISHER_URL="http://127.0.0.1:$PORT/" pic share --where)" = "artifacts http://127.0.0.1:$PORT" ] || fail "env url: --where"
[ "$(printf '<p>env</p>' | HTML_PUBLISHER_URL="http://127.0.0.1:$PORT" pic share --yes)" = "https://pub.example/v/abc123" ] || fail "env url: share"
body "$T/log/1.req" | grep -q '<p>env</p>' || fail "env url: the page did not reach the variable's address"
pic settings artifactsUrl "http://127.0.0.1:1" > /dev/null
[ "$(HTML_PUBLISHER_URL="http://127.0.0.1:$PORT" pic share --where)" = "artifacts http://127.0.0.1:1" ] || fail "env url: the setting must win"
printf 'PASS: HTML_PUBLISHER_URL is the publisher address when artifactsUrl is unset\n'

# 13. --to verifies the configured publisher origin rather than overriding it, and never sends the token elsewhere.
serve "status:201:$T/pub.json"
mkdir -p "$T/log2"
rm -f "$T/port2"
"$SERVER" "$T/port2" "$T/log2" 120 "status:201:$T/pub.json" &
spid2=$!
i=0
while [ ! -s "$T/port2" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "server2"; sleep 0.05; done
PORT2=$(cat "$T/port2")
trap 'kill "$spid2" 2>/dev/null || :; cleanup' EXIT HUP INT TERM
pic settings artifactsUrl "http://127.0.0.1:$PORT" > /dev/null
if printf '<p>x</p>' | pic share --yes --to https://other.example > "$T/out" 2> "$T/err"; then
    fail "origin: --to https://other.example succeeded"
fi
grep -q 'does not match the configured publisher' "$T/err" || fail "origin: unexpected error for https://other.example: $(cat "$T/err")"
! grep -qF "$TOKEN" "$T/err" || fail "origin: token leaked to stderr"
if printf '<p>x</p>' | pic share --yes --to "http://127.0.0.1:$PORT2" > "$T/out" 2> "$T/err"; then
    fail "origin: --to different port succeeded"
fi
grep -q 'does not match the configured publisher' "$T/err" || fail "origin: unexpected error for different port: $(cat "$T/err")"
[ ! -e "$T/log2/1.req" ] || fail "origin: request reached another origin"
if printf '<p>x</p>' | pic share --yes --to "http://localhost:$PORT" > "$T/out" 2> "$T/err"; then
    fail "origin: --to different host succeeded"
fi
grep -q 'does not match the configured publisher' "$T/err" || fail "origin: unexpected error for different host: $(cat "$T/err")"
# Same-origin --to works (including trailing slash / port normalization) and uses the configured address.
[ "$(printf '<p>same</p>' | pic share --yes --to "http://127.0.0.1:$PORT/")" = "https://pub.example/v/abc123" ] || fail "origin: same-origin --to failed"
body "$T/log/1.req" | grep -q '<p>same</p>' || fail "origin: same-origin request missing"
# With no publisher configured, --to must also refuse without sending the token.
pic settings --unset artifactsUrl > /dev/null
if printf '<p>x</p>' | pic share --yes --to "http://127.0.0.1:$PORT2" > "$T/out" 2> "$T/err"; then
    fail "origin: --to succeeded when no publisher is configured"
fi
grep -q 'no publisher address is set' "$T/err" || fail "origin: unexpected error when unconfigured: $(cat "$T/err")"
[ ! -e "$T/log2/1.req" ] || fail "origin: request sent when unconfigured"
# With HTML_PUBLISHER_URL instead of artifactsUrl, same-origin --to works and mismatched --to refuses.
[ "$(printf '<p>envsame</p>' | HTML_PUBLISHER_URL="http://127.0.0.1:$PORT" pic share --yes --to "http://127.0.0.1:$PORT")" = "https://pub.example/v/abc123" ] || fail "origin: env same-origin --to failed"
if printf '<p>x</p>' | HTML_PUBLISHER_URL="http://127.0.0.1:$PORT" pic share --yes --to https://other.example > "$T/out" 2> "$T/err"; then
    fail "origin: --to https://other.example succeeded with HTML_PUBLISHER_URL"
fi
grep -q 'does not match the configured publisher' "$T/err" || fail "origin: unexpected error with HTML_PUBLISHER_URL: $(cat "$T/err")"
kill "$spid2" 2>/dev/null && wait "$spid2" 2>/dev/null || :
spid2=
trap cleanup EXIT HUP INT TERM
printf 'PASS: --to verifies the configured publisher origin and refuses mismatched or unconfigured targets\n'
