codeimprint 0.5.0a35__tar.gz → 0.5.0a37__tar.gz

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.
Files changed (27) hide show
  1. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/CHANGELOG.md +50 -0
  2. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/PKG-INFO +2 -2
  3. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/README.pypi.md +1 -1
  4. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/pyproject.toml +1 -1
  5. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/__init__.py +1 -1
  6. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/cli.py +199 -58
  7. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/config.py +34 -3
  8. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/filelist.py +29 -7
  9. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/gitrepo.py +106 -4
  10. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/.gitignore +0 -0
  11. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/LICENSE +0 -0
  12. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/NOTICE +0 -0
  13. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint/__init__.py +0 -0
  14. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint/__main__.py +0 -0
  15. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/api.py +0 -0
  17. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/chainseal.py +0 -0
  18. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/imprint_file.py +0 -0
  19. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/linecount.py +0 -0
  20. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/ownership.py +0 -0
  21. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/project.py +0 -0
  22. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/receipt.py +0 -0
  23. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/records.py +0 -0
  24. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/timestamp.py +0 -0
  25. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/transparency.py +0 -0
  26. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/trust.py +0 -0
  27. {codeimprint-0.5.0a35 → codeimprint-0.5.0a37}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a37 — The default server, safe URLs, and the invite-only beta [CIM-BE-60-v1]
4
+
5
+ Client only.
6
+
7
+ - **`imprint login` signs in to https://api.codeimprint.ai** when no server is saved and none
8
+ is given, without asking for a URL. `--server` (new, an alias of `--url`, on every command)
9
+ and `CODEIMPRINT_URL` override it, as does a saved server.
10
+ - **Safe URLs.** A server typed without a scheme (`api.codeimprint.ai`) gets `https://`.
11
+ Plain `http://` is refused everywhere (login, `--url`/`--server`, `CODEIMPRINT_URL`, the saved
12
+ server) except for a server on this machine: `localhost`, `127.0.0.1`, `::1`, `*.localhost`,
13
+ and `host.docker.internal` (the Docker host, seen from a container). The old "this URL is not
14
+ HTTPS" warning is gone: such a URL is no longer accepted.
15
+ - **Invite-only beta.** A sign-in the server refuses as `invite_only` now says: "CodeImprint is
16
+ invite-only during the beta. Request early access at https://app.codeimprint.ai/signup."
17
+ and never "Sent a sign-in link". Today's engine refuses once the link is used (at the
18
+ terminal's poll); when it refuses before sending the link, the client says the same at once.
19
+ - Tests: `test_default_server.py`.
20
+
21
+ ## 0.5.0a36 — No false differences from Git's line-ending conversions [CIM-BE-59-v1]
22
+
23
+ Client only; engine unchanged (0.7.0a44).
24
+
25
+ - **`imprint check --files --worktree` compares as Git would store the files.** Git itself
26
+ hashes each working file with its clean conversion (core.autocrlf, core.eol, `.gitattributes`
27
+ text/eol/filter/ident, clean filters), via `git hash-object -w --stdin-paths` into a
28
+ temporary object folder that is deleted afterwards (the index, the repository's objects and
29
+ the working files are never written). An untouched file checked out with CRLF no longer
30
+ reads as "Changed". A file Git cannot convert is compared raw, with a warning naming it.
31
+ - **New: `--raw`** (with `--worktree`) compares the working bytes; when a compared file has a
32
+ conversion, one warning: "line-ending or filter conversion is active; raw comparison may
33
+ show false differences". The `Compared` and `Result` lines say which mode was used: "as Git
34
+ would store them" or "raw bytes". In `--format json`, `compared_as`.
35
+ - **Untracked files** are listed as "Not tracked (not in the seal)", apart from "Added"
36
+ (tracked, not in the seal), and do not count as differences; `.gitignore`, the exclude list
37
+ and `.imprint/` are respected as the seal respects them. In JSON, `untracked`.
38
+ - With `core.fileMode=false` (Windows) a tracked file's mode is taken from the index, so a
39
+ sealed executable is not reported as "another mode". A link checked out as a plain file
40
+ (`core.symlinks=false`) is compared as the link it is.
41
+ - **`imprint prove --export PATH`** writes the exact sealed bytes (Git's blob at the sealed
42
+ commit, checked against the seal first); `--force` to overwrite. When the file here is not
43
+ the sealed one, the warning says whether only the line endings differ and points to
44
+ `--export`.
45
+ - **`imprint verify-file`** still fails on any byte difference, and when only the line
46
+ endings differ it says: "differs from the sealed file only in line endings; ask the owner
47
+ for the exact sealed file (imprint prove --export)".
48
+ - Help for the three commands and the README explain that a seal covers the bytes Git stores.
49
+ - Tests: `test_line_endings.py` (autocrlf true and false; `* text=auto`, `*.bat eol=crlf`,
50
+ `-text`; a clean/smudge filter; binary files; `--raw`; the index, status and objects
51
+ unchanged; untracked against added; `prove --export` and `verify-file`; core.fileMode).
52
+
3
53
  ## 0.5.0a35 — Your own file list: check, prove, verify a file [CIM-BE-58-v1]
4
54
 
5
55
  For engine 0.7.0a44.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a35
3
+ Version: 0.5.0a37
4
4
  Summary: CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline.
5
5
  Project-URL: Homepage, https://codeimprint.ai
6
6
  Project-URL: Hub, https://app.codeimprint.ai
@@ -67,7 +67,7 @@ Windows `py -m codeimprint` works too.
67
67
  ## Get started
68
68
 
69
69
  ```bash
70
- imprint login --url https://api.codeimprint.ai # sign in (browser or e-mail link)
70
+ imprint login # sign in to https://api.codeimprint.ai (browser or e-mail link)
71
71
  imprint init # your developer key, the project and its first seal
72
72
  imprint seal . # seal the current commit
73
73
  imprint verify # check the seal offline
@@ -33,7 +33,7 @@ Windows `py -m codeimprint` works too.
33
33
  ## Get started
34
34
 
35
35
  ```bash
36
- imprint login --url https://api.codeimprint.ai # sign in (browser or e-mail link)
36
+ imprint login # sign in to https://api.codeimprint.ai (browser or e-mail link)
37
37
  imprint init # your developer key, the project and its first seal
38
38
  imprint seal . # seal the current commit
39
39
  imprint verify # check the seal offline
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  # Published on PyPI as `codeimprint`. The import package stays `codeimprint_cli` and the
7
7
  # command `imprint`.
8
8
  name = "codeimprint"
9
- version = "0.5.0a35"
9
+ version = "0.5.0a37"
10
10
  description = "CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline."
11
11
  readme = "README.pypi.md"
12
12
  license = "Apache-2.0"
@@ -5,4 +5,4 @@ A thin client for a CodeImprint server: it zips a project, asks the server to se
5
5
  it, and verifies Imprint files offline. All analysis happens on the server.
6
6
  """
7
7
 
8
- __version__ = "0.5.0a35"
8
+ __version__ = "0.5.0a37"
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
  import argparse
7
7
  import getpass
8
8
  import hashlib
9
+ import io
9
10
  import json
10
11
  import os
11
12
  import secrets
@@ -556,7 +557,11 @@ def _signin(args, url: str) -> int:
556
557
  email = input("E-mail address: ").strip()
557
558
  try:
558
559
  start = client.login_start(provider, email)
559
- except (ApiError, NetworkError) as exc:
560
+ except ApiError as exc:
561
+ if exc.code == "invite_only": # refused before any link is sent
562
+ raise Abort(INVITE_ONLY) from exc
563
+ raise Abort(f"sign-in failed: {exc}") from exc
564
+ except NetworkError as exc:
560
565
  raise Abort(f"sign-in failed: {exc}") from exc
561
566
  _say(f"Code {start['user_code']} (the browser must show the same code)")
562
567
  if provider == "email":
@@ -571,6 +576,8 @@ def _signin(args, url: str) -> int:
571
576
  try:
572
577
  done = client.login_poll(start["login_id"], start["device_secret"])
573
578
  except ApiError as exc:
579
+ if exc.code == "invite_only": # a new account while the beta is invite-only
580
+ raise Abort(INVITE_ONLY) from exc
574
581
  raise Abort(f"sign-in failed: {exc.message}") from exc
575
582
  except NetworkError as exc:
576
583
  raise Abort(str(exc)) from exc
@@ -590,12 +597,18 @@ def _signin(args, url: str) -> int:
590
597
  raise Abort("the sign-in expired: run `imprint login` again")
591
598
 
592
599
 
600
+ INVITE_ONLY = ("CodeImprint is invite-only during the beta. Request early access at "
601
+ "https://app.codeimprint.ai/signup.")
602
+
603
+
593
604
  def cmd_login(args) -> int:
605
+ # 0.5.0a37: no saved server, no flag, no CODEIMPRINT_URL: CodeImprint's own, without asking.
594
606
  url = (args.url or os.environ.get("CODEIMPRINT_URL") or config.load_user_config().get("url")
595
- or (input("CodeImprint server URL: ") if not args.token_stdin else ""))
596
- url = url.strip().rstrip("/")
597
- if not url.startswith(("https://", "http://")):
598
- raise Abort("the URL must start with https:// (or http:// for a local server)")
607
+ or config.DEFAULT_URL)
608
+ try:
609
+ url = config.check_url(url)
610
+ except ValueError as exc:
611
+ raise Abort(str(exc)) from exc
599
612
  if args.cf_access:
600
613
  client_id = input("Cloudflare Access service token, Client ID: ").strip()
601
614
  client_secret = getpass.getpass("Client Secret (not shown): ").strip()
@@ -622,8 +635,6 @@ def cmd_login(args) -> int:
622
635
  _say(f"Saved {url} to {path}",
623
636
  f"Server {health.get('version', '?')}, {health.get('key_mode', '?')} key, "
624
637
  f"auth: {health.get('auth_mode', 'unknown')}")
625
- if url.startswith("http://") and "localhost" not in url and "127.0.0.1" not in url:
626
- _warn("this URL is not HTTPS: your code and token would travel unencrypted")
627
638
  return 0
628
639
 
629
640
 
@@ -3342,20 +3353,76 @@ def _seal_list(client: Client, seal: str) -> dict:
3342
3353
  raise Abort(str(exc)) from exc
3343
3354
 
3344
3355
 
3345
- def _local_entries(root: Path, worktree: bool, rev: str | None) -> tuple[dict, str]:
3346
- """(entries, what was compared): a commit of this repository (default HEAD), or the
3347
- working tree. Everything is hashed here; nothing is sent."""
3356
+ RAW_WARNING = ("line-ending or filter conversion is active; raw comparison may show false "
3357
+ "differences")
3358
+
3359
+
3360
+ def _worktree_entries(root: Path, exclude: list[str], raw: bool) -> dict:
3361
+ """The working tree of a repository: {entries, untracked, mode, converted, failed}.
3362
+
3363
+ By default each file is hashed as Git would store it (Git applies its own clean filters,
3364
+ core.autocrlf, core.eol and .gitattributes, into a temporary object folder: the index,
3365
+ the repository's objects and the working files are left as they were). With ``raw`` the
3366
+ working files' bytes are hashed as they are."""
3367
+ top, under = gitrepo.toplevel(root), gitrepo.prefix(root)
3368
+ index = gitrepo.index_entries(top, under)
3369
+ loose = gitrepo.untracked(top, under)
3370
+ file_mode = gitrepo.file_mode_tracked(top)
3371
+ entries: dict[str, list] = {}
3372
+ hashed: list[str] = []
3373
+ for path in sorted(set(index) | loose, key=filelist.path_bytes):
3374
+ if path.startswith(".imprint/") or filelist.excluded(path, exclude):
3375
+ continue
3376
+ kind, oid = index.get(path, ("regular", None))
3377
+ here = root / path
3378
+ if kind == "submodule": # its recorded commit, as in the seal
3379
+ entries[path] = ["submodule", 0, oid]
3380
+ continue
3381
+ if not os.path.lexists(here) or here.is_dir():
3382
+ continue # deleted here: "removed" if the seal has it
3383
+ if here.is_symlink() or kind == "symlink":
3384
+ entries[path] = filelist.local_file(here, kind)
3385
+ entries[path][0] = "symlink" # a link checked out as a file: its text
3386
+ continue
3387
+ if file_mode:
3388
+ mode = "executable" if here.stat().st_mode & 0o111 else "regular"
3389
+ else: # no executable bit here: the index's
3390
+ mode = kind if path in index else "regular"
3391
+ entries[path] = [mode, None, None]
3392
+ hashed.append(path)
3393
+ failed: dict[str, str] = {}
3394
+ converted = gitrepo.conversions(top, [under + p for p in hashed])
3395
+ if raw:
3396
+ for path in hashed:
3397
+ _mode, size, sha = filelist.local_file(root / path)
3398
+ entries[path][1:] = [size, sha]
3399
+ else:
3400
+ digests, failed = gitrepo.stored_digests(top, [under + p for p in hashed])
3401
+ for path in hashed:
3402
+ got = digests.get(under + path)
3403
+ if got is None: # Git could not convert it: its raw bytes
3404
+ _mode, size, sha = filelist.local_file(root / path)
3405
+ got = (sha, size)
3406
+ entries[path][1:] = [got[1], got[0]]
3407
+ return {"entries": entries, "untracked": loose, "converted": converted,
3408
+ "failed": {p.removeprefix(under): why for p, why in failed.items()},
3409
+ "mode": "raw bytes" if raw else "as Git would store them"}
3410
+
3411
+
3412
+ def _local_entries(root: Path, worktree: bool, rev: str | None,
3413
+ raw: bool = False) -> tuple[dict, str, dict]:
3414
+ """(entries, what was compared, notes): a commit of this repository (default HEAD), or
3415
+ the working tree. Everything is hashed here; nothing is sent."""
3348
3416
  exclude = list(project.load_config(root).get("exclude", [])) if root.is_dir() else []
3349
3417
  git = gitrepo.is_repo(root)
3350
- if worktree or not git:
3418
+ if worktree and git:
3419
+ found = _worktree_entries(root, exclude, raw)
3420
+ return found["entries"], "the working tree", found
3421
+ if not git: # no Git: there is nothing to convert, the bytes are all
3351
3422
  entries = {p: e for p, e in project.every_file(root).items()
3352
3423
  if not filelist.excluded(p, exclude)}
3353
- if git: # a submodule is its recorded commit, as in the seal
3354
- for f in gitrepo.ls_tree_all(gitrepo.toplevel(root), "HEAD",
3355
- gitrepo.prefix(root)):
3356
- if f["mode"] == "submodule" and not filelist.excluded(f["path"], exclude):
3357
- entries[f["path"]] = ["submodule", 0, f["blob"]]
3358
- return entries, "the working tree"
3424
+ return entries, "the folder", {"mode": "raw bytes", "untracked": set(),
3425
+ "converted": [], "failed": {}}
3359
3426
  top, commit = gitrepo.toplevel(root), gitrepo.resolve(root, rev or "HEAD")
3360
3427
  listed = [f for f in gitrepo.ls_tree_all(top, commit, gitrepo.prefix(root))
3361
3428
  if not f["path"].startswith(".imprint/")]
@@ -3364,10 +3431,12 @@ def _local_entries(root: Path, worktree: bool, rev: str | None) -> tuple[dict, s
3364
3431
  for f in listed:
3365
3432
  if f["mode"] != "submodule":
3366
3433
  f["sha256"], f["size"] = digests[f["blob"]]
3367
- return filelist.entries_of(listed, exclude), f"commit {commit[:12]}"
3434
+ return filelist.entries_of(listed, exclude), f"commit {commit[:12]}", {
3435
+ "mode": "as Git stores them", "untracked": set(), "converted": [], "failed": {}}
3368
3436
 
3369
3437
 
3370
- DIFF_LABELS = (("added", "Added", "not in the seal"),
3438
+ DIFF_LABELS = (("added", "Added", "tracked, not in the seal"),
3439
+ ("untracked", "Not tracked", "not in the seal"),
3371
3440
  ("removed", "Removed", "in the seal only"),
3372
3441
  ("changed", "Changed", "other content"),
3373
3442
  ("mode", "Mode", "same content, other mode"),
@@ -3383,23 +3452,35 @@ def cmd_check_files(args) -> int:
3383
3452
  if body.get("scheme") != filelist.SCHEME:
3384
3453
  raise Abort(f"the seal lists its files with {body.get('scheme')!r}, which this "
3385
3454
  "client does not know: upgrade it")
3455
+ if args.raw and not args.worktree:
3456
+ raise Abort("--raw compares working files: use it with --worktree")
3386
3457
  try:
3387
- local, what = _local_entries(root, args.worktree, args.commit)
3458
+ local, what, notes = _local_entries(root, args.worktree, args.commit, args.raw)
3388
3459
  except gitrepo.GitError as exc:
3389
3460
  raise Abort(f"cannot read the repository: {exc}") from exc
3390
- diff = filelist.compare(filelist.sealed_entries(body), local)
3461
+ diff = filelist.compare(filelist.sealed_entries(body), local, notes["untracked"])
3391
3462
  count = sum(len(diff[k]) for k in ("added", "removed", "changed", "mode"))
3463
+ mode = notes["mode"]
3464
+ if args.raw and notes["converted"]:
3465
+ _warn(RAW_WARNING, json_out=args.format == "json")
3466
+ for path, why in sorted(notes["failed"].items()):
3467
+ _warn(f"{path}: Git could not convert it as it would store it ({why}); compared its "
3468
+ "raw bytes", json_out=args.format == "json")
3392
3469
  if args.format == "json":
3393
- print(json.dumps({"seal": seal, "compared": what, "files": body["count"],
3394
- "same": count == 0, **diff}, indent=2))
3470
+ print(json.dumps({"seal": seal, "compared": what, "compared_as": mode,
3471
+ "files": body["count"], "same": count == 0, **diff}, indent=2))
3395
3472
  else:
3396
3473
  commit = f", commit {body['commit'][:12]}" if body.get("commit") else ""
3397
3474
  _say(f"Seal {seal} ({body['count']} files{commit})",
3398
- f"Compared {what}, hashed here (nothing was sent)")
3475
+ f"Compared {what}, {mode}, hashed here (nothing was sent)")
3399
3476
  for key, label, note in DIFF_LABELS:
3400
3477
  for path in diff[key]:
3401
3478
  _say(f"{label:<10} {path} ({note})")
3402
- _say(f"Result {'every file matches the seal' if not count else f'{count} file(s) differ'}")
3479
+ verdict = ("every file matches the seal" if not count
3480
+ else f"{count} file(s) differ")
3481
+ loose = (f"; {len(diff['untracked'])} untracked file(s), not in the seal"
3482
+ if diff["untracked"] else "")
3483
+ _say(f"Result {verdict} ({mode}){loose}")
3403
3484
  if count and _ci(): # never break a build by surprise
3404
3485
  _warn(f"{count} file(s) differ from seal {seal}")
3405
3486
  return 0
@@ -3421,19 +3502,54 @@ def cmd_prove(args) -> int:
3421
3502
  raise Abort(f"{rel} is not in seal {seal}") from exc
3422
3503
  except (ApiError, NetworkError) as exc:
3423
3504
  raise Abort(f"cannot read the seal's public record: {exc}") from exc
3505
+ exported = _export_sealed(args, root, body, rel, proof) if args.export else None
3424
3506
  out = Path(args.output or f"{Path(rel).name}.proof.json")
3425
3507
  out.write_text(json.dumps(proof, indent=1, sort_keys=True) + "\n", encoding="utf-8")
3426
3508
  _say(f"Seal {seal}", f"File {rel} ({proof['kind']}, {proof['size']:,} bytes)",
3427
3509
  f"Proof {out}",
3510
+ *([f"Exported {exported} (the exact sealed bytes: hand this file over with "
3511
+ + "the proof)"] if exported else []),
3428
3512
  "Shares this file's hash, size, mode and salt only; no other file of the seal",
3429
- f"Check imprint verify-file {rel} --proof {out}")
3430
- if target.exists() or target.is_symlink():
3513
+ f"Check imprint verify-file {exported or rel} --proof {out}")
3514
+ if not exported and (target.exists() or target.is_symlink()):
3431
3515
  here = filelist.local_file(target, proof["kind"])
3432
3516
  if here[1:] != [proof["size"], proof["ref"]]:
3433
- _warn("the file here is not the sealed one: the proof is for the sealed content")
3517
+ why = ("differs from the sealed one only in line endings" if
3518
+ filelist.line_endings_only(target, proof["size"], proof["ref"])
3519
+ else "is not the sealed one (its content differs)")
3520
+ _warn(f"the file here {why}: the proof is for the sealed content, so this copy "
3521
+ "will not verify. Use --export FILE to write the exact sealed file")
3434
3522
  return 0
3435
3523
 
3436
3524
 
3525
+ def _export_sealed(args, root: Path, body: dict, rel: str, proof: dict) -> Path:
3526
+ """`imprint prove --export`: the exact bytes Git stores for the file at the sealed
3527
+ commit, checked against the seal before they are written."""
3528
+ out = Path(args.export)
3529
+ if (out.exists() or out.is_symlink()) and not args.force:
3530
+ raise Abort(f"{out} exists: pass --force to overwrite it")
3531
+ if proof["kind"] not in ("regular", "executable"):
3532
+ raise Abort(f"{rel} is sealed as {proof['kind']}: only a file's content can be "
3533
+ "exported")
3534
+ if not body.get("commit") or not gitrepo.is_repo(root):
3535
+ raise Abort("the seal names no commit of this repository to export from")
3536
+ top = gitrepo.toplevel(root)
3537
+ try:
3538
+ data = gitrepo.blob_at(top, body["commit"], gitrepo.prefix(root) + rel)
3539
+ except gitrepo.GitError as exc:
3540
+ raise Abort(f"the sealed commit {body['commit'][:12]} is not in this repository "
3541
+ f"(fetch it first): {exc}") from exc
3542
+ sha, size = filelist.hash_stream(io.BytesIO(data).read)
3543
+ if (sha, size) != (proof["ref"], proof["size"]):
3544
+ raise Abort("the sealed commit's file is not the sealed content; nothing was written")
3545
+ if out.is_symlink():
3546
+ out.unlink()
3547
+ out.write_bytes(data)
3548
+ if proof["kind"] == "executable" and os.name != "nt":
3549
+ out.chmod(out.stat().st_mode | 0o111)
3550
+ return out
3551
+
3552
+
3437
3553
  def cmd_verify_file(args) -> int:
3438
3554
  """`imprint verify-file <file> --proof P`: no account. The seal's receipt is verified,
3439
3555
  then the file's hash, through the proof, is shown to be in the sealed list."""
@@ -3475,6 +3591,11 @@ def cmd_verify_file(args) -> int:
3475
3591
  except OSError as exc:
3476
3592
  raise Abort(f"cannot read {args.file}: {exc}") from exc
3477
3593
  problems = filelist.check_proof(proof, files, here)
3594
+ if "this file's content is not the sealed one" in problems and \
3595
+ filelist.line_endings_only(args.file, proof["size"], proof["ref"]):
3596
+ problems[problems.index("this file's content is not the sealed one")] = (
3597
+ "differs from the sealed file only in line endings; ask the owner for the "
3598
+ "exact sealed file (imprint prove --export)")
3478
3599
  name = filelist.proof_path(proof)
3479
3600
  checks.append(receipt.Check("file", receipt.FAIL if problems else receipt.PASS,
3480
3601
  "; ".join(problems) if problems else
@@ -3501,7 +3622,10 @@ def build_parser() -> argparse.ArgumentParser:
3501
3622
  sub = p.add_subparsers(dest="command", required=True)
3502
3623
 
3503
3624
  lg = sub.add_parser("login", help="sign in (browser or e-mail link), or save an API token")
3504
- lg.add_argument("--url", help="server URL, for example https://imprint.example.com")
3625
+ lg.add_argument("--url", "--server",
3626
+ help=f"server URL (default: the saved one, CODEIMPRINT_URL, else "
3627
+ f"{config.DEFAULT_URL}); https:// is added when no scheme is given, "
3628
+ "and plain http:// is only for a server on this machine")
3505
3629
  lg.add_argument("--provider", choices=["github", "gitlab", "google", "microsoft", "email"],
3506
3630
  help="sign in with this provider (default: the first one the server offers)")
3507
3631
  lg.add_argument("--email", help="your address, for --provider email")
@@ -3527,7 +3651,7 @@ def build_parser() -> argparse.ArgumentParser:
3527
3651
  "seals this repository")
3528
3652
  n.add_argument("--no-key", action="store_true", help="do not create a developer key")
3529
3653
  n.add_argument("--force", action="store_true", help="overwrite files that already exist")
3530
- n.add_argument("--url", help="server URL for creating the project (else login or "
3654
+ n.add_argument("--url", "--server", help="server URL for creating the project (else login or "
3531
3655
  "CODEIMPRINT_URL)")
3532
3656
  n.add_argument("--no-project", action="store_true",
3533
3657
  help="do not create the project and its genesis seal now")
@@ -3555,14 +3679,14 @@ def build_parser() -> argparse.ArgumentParser:
3555
3679
  ky.add_argument("--label", help="request: a name for this device, shown to whoever "
3556
3680
  "approves (default: the computer's name)")
3557
3681
  ky.add_argument("--yes", action="store_true", help="approve, retire: do not ask")
3558
- ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3682
+ ky.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3559
3683
  ky.set_defaults(func=cmd_key)
3560
3684
 
3561
3685
  pl = sub.add_parser("plan", help="your plan, its status and usage (read-only; buy or "
3562
3686
  "change it on the hub's billing page)")
3563
3687
  pl.add_argument("--org", help="an organisation you administer, by its ID")
3564
3688
  pl.add_argument("--json", action="store_true", help="the server's answer as JSON")
3565
- pl.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3689
+ pl.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3566
3690
  pl.set_defaults(func=cmd_plan)
3567
3691
 
3568
3692
  tk = sub.add_parser("token", help="CI tokens for automated builds (CODEIMPRINT_TOKEN): "
@@ -3575,7 +3699,7 @@ def build_parser() -> argparse.ArgumentParser:
3575
3699
  help="create: how long the token lasts, 1 to 365 (default 90)")
3576
3700
  tk.add_argument("--label", help="create: a name for you, for example where it is kept")
3577
3701
  tk.add_argument("--json", action="store_true", help="list: as JSON")
3578
- tk.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3702
+ tk.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3579
3703
  tk.set_defaults(func=cmd_token)
3580
3704
 
3581
3705
  pj = sub.add_parser("project", help="the project: rename it, record that its "
@@ -3596,7 +3720,7 @@ def build_parser() -> argparse.ArgumentParser:
3596
3720
  "and GitHub App connection move there")
3597
3721
  pj.add_argument("--reason", help="archive: a note for you (at most 200 characters)")
3598
3722
  pj.add_argument("--yes", action="store_true", help="archive: do not ask")
3599
- pj.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3723
+ pj.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3600
3724
  pj.set_defaults(func=cmd_project)
3601
3725
 
3602
3726
  en = sub.add_parser("engagement", help="work with a vendor or a client: create, list, show, "
@@ -3615,7 +3739,7 @@ def build_parser() -> argparse.ArgumentParser:
3615
3739
  help="end: the seal marked as handed over (default: the vendor's latest)")
3616
3740
  en.add_argument("--no-handover", action="store_true", help="end: no handover marker")
3617
3741
  en.add_argument("--json", action="store_true")
3618
- en.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3742
+ en.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3619
3743
  en.set_defaults(func=cmd_engagement)
3620
3744
 
3621
3745
  dl = sub.add_parser("deliver", help="deliver a seal: to the project's owner (engagement "
@@ -3625,12 +3749,12 @@ def build_parser() -> argparse.ArgumentParser:
3625
3749
  dl.add_argument("--to-client", action="store_true",
3626
3750
  help="vendor-led: e-mail your client a link to accept it")
3627
3751
  dl.add_argument("--engagement", help="--to-client: which engagement, when there are several")
3628
- dl.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3752
+ dl.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3629
3753
  dl.set_defaults(func=cmd_deliver)
3630
3754
 
3631
3755
  ac = sub.add_parser("accept", help="accept a seal your vendor delivered (project owner)")
3632
3756
  ac.add_argument("seal", metavar="IMP1_ID")
3633
- ac.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3757
+ ac.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3634
3758
  ac.set_defaults(func=cmd_accept)
3635
3759
 
3636
3760
  gh = sub.add_parser("github", help="the GitHub App: link this repository's project to your "
@@ -3641,7 +3765,7 @@ def build_parser() -> argparse.ArgumentParser:
3641
3765
  gh.add_argument("--project", help="your existing project to attach (default: "
3642
3766
  ".imprint/config.json, else the App's project)")
3643
3767
  gh.add_argument("--yes", action="store_true", help="sign without asking")
3644
- gh.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3768
+ gh.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3645
3769
  gh.set_defaults(func=cmd_github)
3646
3770
 
3647
3771
  s = sub.add_parser("seal", help="seal a project on the server; saves .imprint/baseline.imprint "
@@ -3651,7 +3775,7 @@ def build_parser() -> argparse.ArgumentParser:
3651
3775
  s.add_argument("--hub-url", help="hub for the verify link and badge (default: "
3652
3776
  "CODEIMPRINT_HUB_URL, else the hub the server names)")
3653
3777
  s.add_argument("-o", "--output", help="where to save the Imprint")
3654
- s.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3778
+ s.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3655
3779
  s.add_argument("--yes", action="store_true", help="do not ask before uploading (CI)")
3656
3780
  s.add_argument("--tsa-certs", metavar="FILE",
3657
3781
  help="also trust the time-stamping authorities in this PEM bundle")
@@ -3676,7 +3800,7 @@ def build_parser() -> argparse.ArgumentParser:
3676
3800
  ch = sub.add_parser("chain", help="show the project's chain (server, plus this clone's commits)")
3677
3801
  ch.add_argument("path", nargs="?", default=".")
3678
3802
  ch.add_argument("--project", help="project ID (default: .imprint/config.json)")
3679
- ch.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3803
+ ch.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3680
3804
  ch.set_defaults(func=cmd_chain)
3681
3805
 
3682
3806
  idn = sub.add_parser("identity", help="your developer key's verified identity: show, bind, "
@@ -3692,7 +3816,7 @@ def build_parser() -> argparse.ArgumentParser:
3692
3816
  idn.add_argument("--compromised-since", metavar="TIME",
3693
3817
  help="revoke --reason key-compromised: UTC time, e.g. 2026-11-01T12:00:00Z")
3694
3818
  idn.add_argument("--key", help="show: another key's fingerprint")
3695
- idn.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3819
+ idn.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3696
3820
  idn.set_defaults(func=cmd_identity)
3697
3821
 
3698
3822
  cl = sub.add_parser("claim", help="ownership claims: create, show, withdraw, add-key, "
@@ -3718,7 +3842,7 @@ def build_parser() -> argparse.ArgumentParser:
3718
3842
  cl.add_argument("--key", help="retire-key: the key's fingerprint")
3719
3843
  cl.add_argument("--project", help="project ID (default: .imprint/config.json)")
3720
3844
  cl.add_argument("--path", default=".", help="the project folder (default: .)")
3721
- cl.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3845
+ cl.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3722
3846
  cl.add_argument("--yes", action="store_true", help="do not ask before signing")
3723
3847
  cl.set_defaults(func=cmd_claim)
3724
3848
 
@@ -3734,7 +3858,7 @@ def build_parser() -> argparse.ArgumentParser:
3734
3858
  asg.add_argument("--complete", metavar="FILE", help="add your signature to a file the "
3735
3859
  "other side wrote, and submit it")
3736
3860
  asg.add_argument("-o", "--output", help="where to write a half-signed assignment")
3737
- asg.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3861
+ asg.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3738
3862
  asg.add_argument("--yes", action="store_true", help="do not ask before submitting")
3739
3863
  asg.set_defaults(func=cmd_assign)
3740
3864
 
@@ -3744,7 +3868,7 @@ def build_parser() -> argparse.ArgumentParser:
3744
3868
  own.add_argument("path", nargs="?", default=".")
3745
3869
  own.add_argument("--project", help="project ID (default: .imprint/config.json)")
3746
3870
  own.add_argument("--json", action="store_true")
3747
- own.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3871
+ own.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3748
3872
  own.set_defaults(func=cmd_ownership)
3749
3873
 
3750
3874
  og = sub.add_parser("org", help="organisations: create, show, domain, verify, disclose, join, "
@@ -3761,7 +3885,7 @@ def build_parser() -> argparse.ArgumentParser:
3761
3885
  og.add_argument("--also-sign", action="append", metavar="KEYFILE",
3762
3886
  help="join: the admin key (PEM), if you hold it")
3763
3887
  og.add_argument("-o", "--output", help="join: where to write the membership for the admin")
3764
- og.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3888
+ og.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3765
3889
  og.add_argument("--yes", action="store_true", help="do not ask before signing")
3766
3890
  og.set_defaults(func=cmd_org)
3767
3891
 
@@ -3787,7 +3911,7 @@ def build_parser() -> argparse.ArgumentParser:
3787
3911
  ct.add_argument("-o", "--output", help="where to write a half-signed record")
3788
3912
  ct.add_argument("--project", help="project ID (default: .imprint/config.json)")
3789
3913
  ct.add_argument("--path", default=".", help="the project folder (default: .)")
3790
- ct.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3914
+ ct.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3791
3915
  ct.add_argument("--yes", action="store_true", help="do not ask before submitting")
3792
3916
  ct.set_defaults(func=cmd_contributor)
3793
3917
 
@@ -3795,7 +3919,7 @@ def build_parser() -> argparse.ArgumentParser:
3795
3919
  ex.add_argument("imprint_id")
3796
3920
  ex.add_argument("path", nargs="?", default=".")
3797
3921
  ex.add_argument("-o", "--output", help="where to save it (default <ID>.full.imprint)")
3798
- ex.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3922
+ ex.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3799
3923
  ex.set_defaults(func=cmd_export)
3800
3924
 
3801
3925
 
@@ -3806,34 +3930,51 @@ def build_parser() -> argparse.ArgumentParser:
3806
3930
  help=f"exit 1 when the score reaches this value (default {DEFAULT_FAIL_ABOVE})")
3807
3931
  c.add_argument("--format", choices=["text", "json"], default="text")
3808
3932
  c.add_argument("-o", "--output", help="also write the JSON result to this file")
3809
- c.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3933
+ c.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3810
3934
  c.add_argument("--yes", action="store_true", help="do not ask before uploading (CI)")
3811
3935
  c.add_argument("--files", action="store_true",
3812
3936
  help="compare every file with a seal's file list, hashed here; nothing is "
3813
- "uploaded (engine 0.7.0a44, the seal's owner)")
3937
+ "uploaded (engine 0.7.0a44, the seal's owner). A seal covers the "
3938
+ "bytes Git stores")
3814
3939
  c.add_argument("--seal", help="with --files: the seal (default: this folder's baseline)")
3815
3940
  c.add_argument("--commit", help="with --files: the commit to compare (default HEAD)")
3816
3941
  c.add_argument("--worktree", action="store_true",
3817
- help="with --files: compare the working tree instead of a commit")
3942
+ help="with --files: compare the working tree, each file as Git would store "
3943
+ "it (line endings, .gitattributes and filters applied, as `git add` "
3944
+ "would; the index and your files are left as they are)")
3945
+ c.add_argument("--raw", action="store_true",
3946
+ help="with --worktree: compare the working files byte for byte, without "
3947
+ "Git's conversions (may show line-ending differences)")
3818
3948
  c.set_defaults(func=cmd_check)
3819
3949
 
3820
- pv = sub.add_parser("prove", help="make a proof that one file is in a seal (its owner)")
3950
+ pv = sub.add_parser("prove", help="make a proof that one file is in a seal (its owner)",
3951
+ epilog="The proof is for the sealed content: the bytes Git stores at "
3952
+ "the sealed commit. A working copy with other line endings "
3953
+ "(core.autocrlf) will not verify; --export writes the exact "
3954
+ "sealed file to hand over with the proof.")
3821
3955
  pv.add_argument("path", help="the file, as in the sealed folder")
3822
3956
  pv.add_argument("--seal", help="the seal (default: this folder's baseline)")
3823
3957
  pv.add_argument("--root", default=".", help="the sealed folder (default: here)")
3824
3958
  pv.add_argument("-o", "--output", help="where to write it (default <name>.proof.json)")
3825
- pv.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3959
+ pv.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3960
+ pv.add_argument("--export", metavar="PATH",
3961
+ help="also write the exact sealed bytes of the file (from Git, at the "
3962
+ "sealed commit) to PATH, for the other party to verify")
3963
+ pv.add_argument("--force", action="store_true", help="with --export: overwrite PATH")
3826
3964
  pv.set_defaults(func=cmd_prove)
3827
3965
 
3828
3966
  vf = sub.add_parser("verify-file", help="check that a file is in a seal, from a proof "
3829
3967
  "(no account)",
3830
- epilog="Exit codes: 0 VERIFIED; 1 NOT VERIFIED; 2 a usage or other "
3831
- "error; 3 a newer format than this client understands.")
3968
+ epilog="The file must be byte for byte the sealed one: nothing is "
3969
+ "converted (a copy with other line endings fails; ask the owner "
3970
+ "for the exact file, `imprint prove --export`). Exit codes: 0 "
3971
+ "VERIFIED; 1 NOT VERIFIED; 2 a usage or other error; 3 a newer "
3972
+ "format than this client understands.")
3832
3973
  vf.add_argument("file", help="the file to check")
3833
3974
  vf.add_argument("--proof", required=True, help="the proof (from `imprint prove`)")
3834
3975
  vf.add_argument("--keys", metavar="FILE",
3835
3976
  help="trust only these server keys (a codeimprint-keys.json)")
3836
- vf.add_argument("--url", help="the server (default: the one the proof names)")
3977
+ vf.add_argument("--url", "--server", help="the server (default: the one the proof names)")
3837
3978
  vf.add_argument("--tsa-certs", metavar="FILE",
3838
3979
  help="also trust the time-stamping authorities in this PEM bundle")
3839
3980
  vf.add_argument("--json", action="store_true")
@@ -3858,7 +3999,7 @@ def build_parser() -> argparse.ArgumentParser:
3858
3999
  v.add_argument("--online", action="store_true",
3859
4000
  help="also check the server's live log (consistency, order, registry)")
3860
4001
  v.add_argument("--project", help="where to look for receipts when given an ID")
3861
- v.add_argument("--url", help="server URL for --online")
4002
+ v.add_argument("--url", "--server", help="server URL for --online")
3862
4003
  v.add_argument("--tsa-certs", metavar="FILE",
3863
4004
  help="also trust the time-stamping authorities in this PEM bundle")
3864
4005
  v.add_argument("--opening", metavar="FILE",
@@ -3876,7 +4017,7 @@ def build_parser() -> argparse.ArgumentParser:
3876
4017
  help="save the record (and its opening, when shown to you) to verify "
3877
4018
  "offline with `imprint verify FILE`")
3878
4019
  ln.add_argument("--json", action="store_true")
3879
- ln.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
4020
+ ln.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3880
4021
  ln.set_defaults(func=cmd_lineage)
3881
4022
 
3882
4023
  ce = sub.add_parser("certificate", help="download a seal's certificate (PDF): for the "
@@ -3884,7 +4025,7 @@ def build_parser() -> argparse.ArgumentParser:
3884
4025
  ce.add_argument("seal", metavar="FINGERPRINT_ID", help="the seal's ID (IMP1-…)")
3885
4026
  ce.add_argument("-o", "--out", metavar="FILE",
3886
4027
  help="where to save it (default: certificate-<ID>.pdf in this folder)")
3887
- ce.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
4028
+ ce.add_argument("--url", "--server", help="server URL (overrides login and CODEIMPRINT_URL)")
3888
4029
  ce.set_defaults(func=cmd_certificate)
3889
4030
  return p
3890
4031
 
@@ -1,8 +1,13 @@
1
1
  # SPDX-License-Identifier: Apache-2.0
2
2
  """Where the client keeps the server URL and token, and how settings are resolved.
3
3
 
4
- Order: command-line flag, then environment (CODEIMPRINT_URL, CODEIMPRINT_TOKEN), then the
5
- user config file written by `imprint login`.
4
+ Order: command-line flag (`--url`, or its alias `--server`), then environment
5
+ (CODEIMPRINT_URL, CODEIMPRINT_TOKEN), then the user config file written by `imprint login`.
6
+ `imprint login` with none of them signs in to CodeImprint's own server, DEFAULT_URL.
7
+
8
+ A URL without a scheme gets ``https://``. Plain ``http://`` is refused except for a server on
9
+ this machine (``localhost``, ``127.0.0.1``, ``::1``, ``*.localhost``, or the Docker host from a
10
+ container, ``host.docker.internal``): a token must never travel unencrypted.
6
11
 
7
12
  A server behind **Cloudflare Access** (a development lock) also needs a service token: the
8
13
  ``CF-Access-Client-Id`` and ``CF-Access-Client-Secret`` headers. They come from
@@ -99,6 +104,32 @@ def session_expired(url: str) -> bool:
99
104
 
100
105
 
101
106
  LOOPBACK = {"localhost", "127.0.0.1", "::1"}
107
+ DEFAULT_URL = "https://api.codeimprint.ai"
108
+ LOCAL_HTTP = LOOPBACK | {"host.docker.internal"}
109
+
110
+
111
+ def local_host(host: str | None) -> bool:
112
+ """A server on this machine, where plain HTTP is allowed."""
113
+ host = (host or "").lower()
114
+ return host in LOCAL_HTTP or host.endswith(".localhost")
115
+
116
+
117
+ def check_url(text: str) -> str:
118
+ """A server URL as typed, made safe: ``https://`` added when there is no scheme, the
119
+ trailing slash removed; plain HTTP only for a server on this machine (ValueError)."""
120
+ url = (text or "").strip()
121
+ if not url:
122
+ raise ValueError("no server URL")
123
+ if "://" not in url:
124
+ url = "https://" + url
125
+ url = url.rstrip("/")
126
+ parts = urlparse(url)
127
+ if parts.scheme not in ("https", "http") or not parts.hostname:
128
+ raise ValueError(f"not a server URL: {text.strip()}")
129
+ if parts.scheme == "http" and not local_host(parts.hostname):
130
+ raise ValueError(f"plain http:// is allowed only for a server on this machine "
131
+ f"(localhost): use https://{url.split('://', 1)[1]}")
132
+ return url
102
133
 
103
134
 
104
135
  def _host(url: str | None) -> str | None:
@@ -185,4 +216,4 @@ def resolve(url_flag: str | None = None) -> Settings:
185
216
  stored = load_user_config()
186
217
  url = url_flag or os.environ.get("CODEIMPRINT_URL") or stored.get("url")
187
218
  token = os.environ.get("CODEIMPRINT_TOKEN") or stored.get("token")
188
- return Settings(url=url.rstrip("/") if url else None, token=token or None)
219
+ return Settings(url=check_url(url) if url else None, token=token or None)
@@ -176,17 +176,19 @@ def sealed_entries(body: dict) -> dict[str, list]:
176
176
  return out
177
177
 
178
178
 
179
- def compare(sealed: dict[str, list], local: dict[str, list]) -> dict[str, list[str]]:
180
- """What differs: {added, removed, changed, mode, unhashed}, each a sorted list of paths.
181
- ``mode``: the same content with another mode. ``unhashed``: files the seal lists without
182
- a hash, which cannot be compared."""
183
- out: dict[str, list[str]] = {"added": [], "removed": [], "changed": [], "mode": [],
184
- "unhashed": []}
179
+ def compare(sealed: dict[str, list], local: dict[str, list],
180
+ untracked: set[str] = frozenset()) -> dict[str, list[str]]:
181
+ """What differs: {added, untracked, removed, changed, mode, unhashed}, each a sorted
182
+ list of paths. ``added``: tracked here, not in the seal; ``untracked``: a file Git does not
183
+ track, not in the seal. ``mode``: the same content with another mode. ``unhashed``:
184
+ files the seal lists without a hash, which cannot be compared."""
185
+ out: dict[str, list[str]] = {"added": [], "untracked": [], "removed": [], "changed": [],
186
+ "mode": [], "unhashed": []}
185
187
  for path in sorted(set(sealed) | set(local), key=path_bytes):
186
188
  if path not in local:
187
189
  out["removed"].append(path)
188
190
  elif path not in sealed:
189
- out["added"].append(path)
191
+ out["untracked" if path in untracked else "added"].append(path)
190
192
  elif sealed[path][0] == "unhashed":
191
193
  out["unhashed"].append(path)
192
194
  elif sealed[path] != local[path]:
@@ -271,6 +273,26 @@ def check_proof(proof: dict, files: dict, local: list | None) -> list[str]:
271
273
  return problems
272
274
 
273
275
 
276
+ LINE_ENDINGS_MAX = 256 * 1024 * 1024
277
+
278
+
279
+ def line_endings_only(path, size: int, ref: str) -> bool:
280
+ """Whether the file at ``path`` is the sealed content (``size``, SHA-256 ``ref``) but for
281
+ its line endings (CRLF where the seal has LF, or the other way round). Only to explain a
282
+ difference: a file that differs never verifies."""
283
+ import re
284
+ from pathlib import Path
285
+
286
+ p = Path(path)
287
+ if p.is_symlink() or not p.is_file() or p.stat().st_size > LINE_ENDINGS_MAX:
288
+ return False
289
+ data = p.read_bytes()
290
+ for other in (data.replace(b"\r\n", b"\n"), re.sub(rb"(?<!\r)\n", b"\r\n", data)):
291
+ if other != data and len(other) == size and hashlib.sha256(other).hexdigest() == ref:
292
+ return True
293
+ return False
294
+
295
+
274
296
  def local_file(path, kind_hint: str | None = None) -> list:
275
297
  """[kind, size, sha256] of a file on this machine (a link: its target text)."""
276
298
  import os
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import os
12
12
  import subprocess
13
+ import tempfile
13
14
  from pathlib import Path
14
15
 
15
16
  from . import filelist
@@ -19,10 +20,11 @@ class GitError(Exception):
19
20
  """Not a Git repository, or a git command failed."""
20
21
 
21
22
 
22
- def _git(root: Path, *args: str, input: bytes | None = None) -> bytes:
23
+ def _git(root: Path, *args: str, input: bytes | None = None,
24
+ env: dict | None = None) -> bytes:
23
25
  try:
24
26
  done = subprocess.run(["git", "-C", str(root), *args], input=input, capture_output=True,
25
- check=True)
27
+ check=True, env=env)
26
28
  except FileNotFoundError as exc:
27
29
  raise GitError("git is not installed") from exc
28
30
  except subprocess.CalledProcessError as exc:
@@ -224,14 +226,15 @@ def ls_tree_all(root: Path, commit: str, under: str = "") -> list[dict]:
224
226
  return files
225
227
 
226
228
 
227
- def hash_blobs(root: Path, blob_ids: list[str]) -> dict[str, tuple[str, int]]:
229
+ def hash_blobs(root: Path, blob_ids: list[str],
230
+ env: dict | None = None) -> dict[str, tuple[str, int]]:
228
231
  """{blob ID: (SHA-256, size)} of each blob's raw bytes, read in parts through one
229
232
  `git cat-file --batch` process: a large file is never held whole."""
230
233
  out: dict[str, tuple[str, int]] = {}
231
234
  if not blob_ids:
232
235
  return out
233
236
  proc = subprocess.Popen(["git", "-C", str(root), "cat-file", "--batch"],
234
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
237
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
235
238
  try:
236
239
  for blob in blob_ids:
237
240
  proc.stdin.write(blob.encode() + b"\n")
@@ -259,6 +262,105 @@ def hash_blobs(root: Path, blob_ids: list[str]) -> dict[str, tuple[str, int]]:
259
262
  return out
260
263
 
261
264
 
265
+ # -- the working tree as Git would store it (client 0.5.0a36) --------------------------------
266
+ def _under(raw: bytes, under: str) -> str | None:
267
+ path = raw.decode("utf-8", errors="surrogateescape")
268
+ return path[len(under):] if path.startswith(under) and not path.endswith("/") else None
269
+
270
+
271
+ def index_entries(top: Path, under: str = "") -> dict[str, tuple[str, str]]:
272
+ """{path: (kind, object ID)} of the index (what is tracked), relative to ``under``."""
273
+ out = {}
274
+ for record in _git(top, "ls-files", "-s", "-z").split(b"\0"):
275
+ if not record:
276
+ continue
277
+ meta, _, raw = record.partition(b"\t")
278
+ mode, oid, _stage = meta.decode().split()
279
+ path = _under(raw, under)
280
+ if path is not None:
281
+ out[path] = (filelist.GIT_MODES.get(mode, "regular"), oid)
282
+ return out
283
+
284
+
285
+ def untracked(top: Path, under: str = "") -> set[str]:
286
+ """Files Git does not track and does not ignore (.gitignore, info/exclude)."""
287
+ out = set()
288
+ for raw in _git(top, "ls-files", "-z", "--others", "--exclude-standard").split(b"\0"):
289
+ path = _under(raw, under) if raw else None
290
+ if path is not None:
291
+ out.add(path)
292
+ return out
293
+
294
+
295
+ def file_mode_tracked(top: Path) -> bool:
296
+ """core.fileMode: whether this checkout records the executable bit (false on Windows)."""
297
+ try:
298
+ return _git(top, "config", "--bool", "core.filemode").strip() != b"false"
299
+ except GitError:
300
+ return True
301
+
302
+
303
+ def conversions(top: Path, paths: list[str]) -> list[str]:
304
+ """The paths (relative to ``top``) whose bytes Git converts between the working tree and
305
+ the repository: core.autocrlf, or a text, eol, filter, ident or working-tree-encoding
306
+ attribute."""
307
+ if not paths:
308
+ return []
309
+ try:
310
+ autocrlf = _git(top, "config", "core.autocrlf").strip().lower()
311
+ except GitError:
312
+ autocrlf = b""
313
+ if autocrlf in (b"true", b"input"):
314
+ return list(paths)
315
+ out = _git(top, "check-attr", "-z", "--stdin", "text", "eol", "filter", "ident",
316
+ "working-tree-encoding",
317
+ input=b"\0".join(p.encode("utf-8", "surrogateescape") for p in paths) + b"\0")
318
+ parts = out.split(b"\0")
319
+ active = set()
320
+ for i in range(0, len(parts) - 2, 3):
321
+ if parts[i + 2] not in (b"unspecified", b"unset"):
322
+ active.add(parts[i].decode("utf-8", "surrogateescape"))
323
+ return [p for p in paths if p in active]
324
+
325
+
326
+ def stored_digests(top: Path, paths: list[str]
327
+ ) -> tuple[dict[str, tuple[str, int]], dict[str, str]]:
328
+ """({path: (SHA-256, size)}, {path: why not}) of working files (relative to ``top``) as
329
+ Git would store them: clean filters, core.autocrlf, core.eol and .gitattributes applied,
330
+ by Git itself (`git hash-object --stdin-paths`). The objects go to a temporary folder
331
+ that is deleted afterwards; the repository's index, objects and working files are never
332
+ written."""
333
+ if not paths:
334
+ return {}, {}
335
+ real = _git(top, "rev-parse", "--git-path", "objects").decode().strip()
336
+ real = str(Path(real) if Path(real).is_absolute() else Path(top) / real)
337
+ with tempfile.TemporaryDirectory(prefix="codeimprint-objects-") as tmp:
338
+ env = {**os.environ, "GIT_OBJECT_DIRECTORY": tmp,
339
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": real}
340
+ ids: dict[str, str] = {}
341
+ failed: dict[str, str] = {}
342
+ batch = [p for p in paths if "\n" not in p]
343
+ try:
344
+ out = _git(top, "hash-object", "-w", "--stdin-paths", env=env, input="".join(
345
+ p + "\n" for p in batch).encode("utf-8", "surrogateescape")).split()
346
+ ids = {p: oid.decode() for p, oid in zip(batch, out)}
347
+ rest = [p for p in paths if p not in ids]
348
+ except GitError:
349
+ rest = list(paths)
350
+ for p in rest: # one by one: say which one failed
351
+ try:
352
+ ids[p] = _git(top, "hash-object", "-w", "--", p, env=env).decode().strip()
353
+ except GitError as exc:
354
+ failed[p] = str(exc)
355
+ digests = hash_blobs(top, sorted(set(ids.values())), env=env)
356
+ return {p: digests[oid] for p, oid in ids.items()}, failed
357
+
358
+
359
+ def blob_at(top: Path, commit: str, path: str) -> bytes:
360
+ """The bytes Git stores for ``path`` (from the top) at ``commit``."""
361
+ return _git(top, "cat-file", "blob", f"{commit}:{path}")
362
+
363
+
262
364
  def read_blobs(root: Path, blob_ids: list[str]):
263
365
  """Yield (blob ID, content) for each ID, via one `git cat-file --batch` process."""
264
366
  if not blob_ids:
File without changes
File without changes