codeimprint 0.5.0a24__tar.gz → 0.5.0a27__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 (26) hide show
  1. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/CHANGELOG.md +55 -0
  2. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/api.py +71 -4
  6. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/chainseal.py +1 -1
  7. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/cli.py +343 -11
  8. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/receipt.py +16 -1
  9. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/.gitignore +0 -0
  10. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/LICENSE +0 -0
  11. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/NOTICE +0 -0
  12. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/README.pypi.md +0 -0
  13. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint/__init__.py +0 -0
  14. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint/__main__.py +0 -0
  15. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/config.py +0 -0
  17. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/gitrepo.py +0 -0
  18. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/imprint_file.py +0 -0
  19. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/linecount.py +0 -0
  20. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/ownership.py +0 -0
  21. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/project.py +0 -0
  22. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a24 → codeimprint-0.5.0a27}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,60 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a27 — One project per repository; archiving a duplicate [CIM-BE-40-v1]
4
+
5
+ For engine 0.7.0a32.
6
+
7
+ - **Changed: `imprint init` in a repository the CodeImprint GitHub App already seals** names
8
+ the App's project in `.imprint/config.json`, creates nothing, and says to run `imprint
9
+ github link` to seal from that machine too. (Engines before 0.7.0a32 answer as before.)
10
+ - **New: `imprint project archive [folder] [--project <ID>] [--into <project>] [--reason
11
+ <text>] [--yes]`** archives a duplicate project for the same repository after asking: its
12
+ seals, chain and pages stay; it takes no new seals. `--into` merges it into the project to
13
+ keep: its repository and GitHub App connection move there, and `.imprint/config.json` is
14
+ switched when it named the archived project. Without `--yes` and no terminal it never
15
+ confirms.
16
+ - Tests: `tests/test_repository.py`.
17
+
18
+ ## 0.5.0a26 — Engagement decisions [CIM-BE-38-v2]
19
+
20
+ For engine 0.7.0a30.
21
+
22
+ - **Changed: the takeover baseline is shown in the server's words**: "Matches the handover",
23
+ "Same content, different history" or "No shared history with the handover" (never
24
+ "differs"). `imprint seal` also shows it when the vendor's first tree was already sealed
25
+ (the existing seal is then the baseline).
26
+ - **Changed: a vendor's scoped key is found by fingerprint.** The public key list leaves it
27
+ out unless the engagement is public, so `imprint seal` (before sending anything) and
28
+ `imprint verify --online` (the "project key" check) ask for that one key. Clients before
29
+ 0.5.0a26 fail that check for seals signed by a hidden scoped key.
30
+ - `imprint deliver --to-client` shows the server's answer when it is refused: certificate
31
+ details needed (with the hub's page), not an invited account, or more than 5 e-mails in 24
32
+ hours.
33
+ - Tests: `tests/test_engagements.py`.
34
+
35
+ ## 0.5.0a25 — Working with vendors and clients [CIM-BE-38-v1]
36
+
37
+ For engine 0.7.0a29. Older engines answer the new commands with 404.
38
+
39
+ - **New: `imprint engagement`.**
40
+ - `create --vendor "<name>" [--days N]` (you own the project): an engagement and its token,
41
+ shown once, with the steps to send your vendor.
42
+ - `create --client "<name>" --email <address>` (you are the vendor).
43
+ - `list`, `show <eng_…>`, `end <eng_…> [--handover IMP1-… | --no-handover]`,
44
+ `public <eng_…> on|off`. With an engagement token, `list` shows the token's own
45
+ engagement.
46
+ - `join` (the vendor, with the engagement token in `CODEIMPRINT_TOKEN`): this machine's
47
+ developer key becomes the engagement's key, and `.imprint/config.json` names the project
48
+ and the engagement.
49
+ - **New: `imprint deliver <IMP1-…> [--note …]`**: with the engagement token, tell the project
50
+ owner a seal is delivered; with `--to-client` (signed in, vendor-led), e-mail your client a
51
+ link to accept it.
52
+ - **New: `imprint accept <IMP1-…>`**: the project owner accepts a delivered seal.
53
+ - **Changed: `imprint seal` with an engagement token** prints "Sealed by <vendor> (named by
54
+ the project owner), engagement eng_…", and for a new vendor's first seal whether it
55
+ matches the previous vendor's handover.
56
+ - README: "Working with vendors and clients". Tests: `tests/test_engagements.py`.
57
+
3
58
  ## 0.5.0a24 — Empty seals are refused; a tip to name a project [CIM-BE-37-v1]
4
59
 
5
60
  For engine 0.7.0a28. Older engines still work.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a24
3
+ Version: 0.5.0a27
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
@@ -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.0a24"
9
+ version = "0.5.0a27"
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.0a24"
8
+ __version__ = "0.5.0a27"
@@ -164,10 +164,26 @@ class Client:
164
164
  {"repository": repository, "public_key": public_key,
165
165
  "signature": signature})
166
166
 
167
- def own_projects_here(self, repository: dict) -> list[str]:
168
- """This account's own projects that live in this repository."""
169
- return self._json("POST", "/api/v1/repository/projects",
170
- {"repository": repository}).get("projects") or []
167
+ def own_projects_here(self, repository: dict) -> list[dict]:
168
+ """This account's own projects that live in this repository, as {project_id,
169
+ custody, github_app} (an engine before 0.7.0a32 gives the IDs only)."""
170
+ out = self._json("POST", "/api/v1/repository/projects", {"repository": repository})
171
+ items = out.get("items")
172
+ if isinstance(items, list):
173
+ return [i for i in items if isinstance(i, dict) and i.get("project_id")]
174
+ return [{"project_id": p} for p in out.get("projects") or []]
175
+
176
+ def archive_project(self, project: str, merge_into: str | None = None,
177
+ reason: str | None = None) -> dict:
178
+ """Step 1 of archiving (or merging) a duplicate project: what will happen, and a
179
+ confirmation for this sign-in. Nothing changes yet."""
180
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/archive",
181
+ {**({"merge_into": merge_into} if merge_into else {}),
182
+ **({"reason": reason} if reason else {})})
183
+
184
+ def archive_project_confirm(self, project: str, confirm: str) -> dict:
185
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/archive/confirm",
186
+ {"confirm": confirm})
171
187
 
172
188
  def rename_project(self, project: str, name: str, public: bool, public_key: str,
173
189
  signature: str) -> dict:
@@ -215,6 +231,51 @@ class Client:
215
231
  def revoke_token(self, token_id: str) -> dict:
216
232
  return self._json("POST", f"/api/v1/me/tokens/{quote(token_id)}/revoke", {})
217
233
 
234
+ # client–vendor engagements (engine 0.7.0a29) ------------------------------------------
235
+ def create_engagement(self, project: str, mode: str, party_name: str,
236
+ party_email: str | None = None, days: int = 90) -> dict:
237
+ body = {"mode": mode, "party_name": party_name, "days": days}
238
+ if party_email:
239
+ body["party_email"] = party_email
240
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/engagements", body)
241
+
242
+ def engagements(self, project: str | None = None) -> list[dict]:
243
+ path = (f"/api/v1/projects/{quote(project)}/engagements" if project
244
+ else "/api/v1/me/engagements")
245
+ return self._request("GET", path).get("items") or []
246
+
247
+ def engagement(self, engagement_id: str) -> dict:
248
+ return self._request("GET", f"/api/v1/engagements/{quote(engagement_id)}")
249
+
250
+ def my_engagement(self) -> dict:
251
+ """The engagement of the engagement token in use (the vendor's view)."""
252
+ return self._request("GET", "/api/v1/engagement")
253
+
254
+ def end_engagement(self, engagement_id: str, handover: str | None = None,
255
+ no_handover: bool = False) -> dict:
256
+ return self._json("POST", f"/api/v1/engagements/{quote(engagement_id)}/end",
257
+ {"handover": handover, "no_handover": no_handover})
258
+
259
+ def engagement_visibility(self, engagement_id: str, public: bool) -> dict:
260
+ return self._json("POST", f"/api/v1/engagements/{quote(engagement_id)}/visibility",
261
+ {"public": public})
262
+
263
+ def engagement_key(self, public_key: str, signature: str) -> dict:
264
+ return self._json("POST", "/api/v1/engagement/key",
265
+ {"public_key": public_key, "signature": signature})
266
+
267
+ def deliver(self, seal_id: str, note: str | None = None, to_client: bool = False,
268
+ engagement: str | None = None) -> dict:
269
+ body: dict = {"to_client": to_client}
270
+ if note:
271
+ body["note"] = note
272
+ if engagement:
273
+ body["engagement"] = engagement
274
+ return self._json("POST", f"/api/v1/seals/{quote(seal_id)}/deliver", body)
275
+
276
+ def accept(self, seal_id: str) -> dict:
277
+ return self._json("POST", f"/api/v1/seals/{quote(seal_id)}/accept", {})
278
+
218
279
  def lineage(self, record_id: str) -> dict:
219
280
  """A lineage record (LIN1): its public record and, when this account may see it,
220
281
  the opening of its commitment (engine 0.7.0a21+)."""
@@ -263,6 +324,12 @@ class Client:
263
324
  def public_project(self, project: str) -> dict:
264
325
  return self._json("GET", f"/api/v1/public/projects/{quote(project)}")
265
326
 
327
+ def public_project_key(self, project: str, fingerprint: str) -> dict:
328
+ """One key of a project by fingerprint (engine 0.7.0a30): the public key list leaves
329
+ out a vendor's scoped key unless its engagement is public."""
330
+ return self._json("GET", f"/api/v1/public/projects/{quote(project)}/keys/"
331
+ f"{quote(fingerprint)}")
332
+
266
333
  def public_chain(self, project: str, after: int | None = None) -> dict:
267
334
  query = f"?after={int(after)}" if after is not None else ""
268
335
  return self._json("GET", f"/api/v1/public/projects/{quote(project)}/chain{query}")
@@ -165,7 +165,7 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
165
165
  # earlier engines: already_sealed is the seal's ID.
166
166
  seal = resp["id"] if resp["already_sealed"] is True else resp["already_sealed"]
167
167
  return {"already": seal, "released": resp.get("already_released"),
168
- "commit": commit, "info": info}
168
+ "commit": commit, "info": info, "engagement": resp.get("engagement")}
169
169
  plan_id = resp.get("plan_id", plan_id)
170
170
  if resp.get("files") == 0: # an engine before 0.7.0a28 would seal nothing
171
171
  raise NothingToSeal(len(files), _python(files))
@@ -430,7 +430,7 @@ def _project_ready(client: Client, project_id: str, key, root: Path | None = Non
430
430
  + (MOVE_HINT if fp in active and not settled else ""))
431
431
  if keys is None:
432
432
  return ident
433
- if active and fp not in active:
433
+ if active and fp not in active and not _scoped_key(client, project_id, fp):
434
434
  raise SealFailed(
435
435
  f"developer key {fp} on this machine is not a key of project {project_id} (its "
436
436
  f"keys: {', '.join(active)}). Add this device to the project: run `imprint key "
@@ -439,6 +439,16 @@ def _project_ready(client: Client, project_id: str, key, root: Path | None = Non
439
439
  return ident
440
440
 
441
441
 
442
+ def _scoped_key(client: Client, project_id: str, fp: str) -> bool:
443
+ """A vendor's engagement key is not on the public key list (engine 0.7.0a30) unless the
444
+ engagement is public: ask for it by fingerprint."""
445
+ try:
446
+ k = client.public_project_key(project_id, fp)
447
+ except (ApiError, NetworkError):
448
+ return False
449
+ return isinstance(k, dict) and k.get("fingerprint") == fp and not k.get("valid_until")
450
+
451
+
442
452
  def _other_repository(client: Client, cfg: dict, root: Path) -> None:
443
453
  """For a machine without a developer key: refuse, with the one sentence, when this is not
444
454
  the repository the folder's project lives in. Otherwise say nothing (the caller then
@@ -850,12 +860,21 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
850
860
  except (ApiError, NetworkError):
851
861
  own = []
852
862
  if own:
853
- current["project_id"] = own[0]
863
+ found = own[0]
864
+ current["project_id"] = found["project_id"]
854
865
  cfg_path.parent.mkdir(parents=True, exist_ok=True)
855
866
  cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
856
867
  _note_home(root, ident)
857
- _say("", f"Project {own[0]} (yours: this repository already has it, so nothing was "
858
- "created; .imprint/config.json now names it)",
868
+ if found.get("custody") == "codeimprint": # the GitHub App made it (CIM-BE-40-v1)
869
+ _say("", f"Project {found['project_id']} (made by the CodeImprint GitHub App for "
870
+ "this repository, so nothing was created; .imprint/config.json now names "
871
+ "it)",
872
+ " One repository is one project. To seal it from this machine too, run",
873
+ " `imprint github link` here: your developer key joins the project and "
874
+ "authorises the App's key.")
875
+ return
876
+ _say("", f"Project {found['project_id']} (yours: this repository already has it, so "
877
+ "nothing was created; .imprint/config.json now names it)",
859
878
  " The same repository on another device is the same project. To seal from this "
860
879
  "device, run",
861
880
  " `imprint key request` here and `imprint key approve` on a device that already "
@@ -1195,11 +1214,11 @@ def _sign_record(key, document: dict, role: str) -> dict:
1195
1214
  "signature": chainseal.sign(key, records.sign_statement(document["type"], digest))}
1196
1215
 
1197
1216
 
1198
- def _ask(args, question: str) -> None:
1217
+ def _ask(args, question: str, doing: str = "signing") -> None:
1199
1218
  if args.yes:
1200
1219
  return
1201
1220
  if not sys.stdin.isatty():
1202
- raise Abort("not signing without confirmation: pass --yes")
1221
+ raise Abort(f"not {doing} without confirmation: pass --yes")
1203
1222
  if input(f"{question} [y/N] ").strip().lower() not in {"y", "yes"}:
1204
1223
  raise Abort("cancelled")
1205
1224
 
@@ -1830,6 +1849,11 @@ def _finish(args, client: Client, root: Path, result: dict, keys: list,
1830
1849
  "Timestamps")
1831
1850
  for c in stamps:
1832
1851
  _say(f" {c.status:<5} {c.name.removeprefix('timestamp').strip() or '-':<10} {c.detail}")
1852
+ eng = result.get("engagement")
1853
+ if eng: # a vendor's seal (engine 0.7.0a29)
1854
+ _say(f"Sealed by {eng['sealed_by']} ({eng['named_by']}), engagement {eng['id']}")
1855
+ if eng.get("taken_over"):
1856
+ _say(f"Baseline {_baseline_text(eng)}")
1833
1857
  _say(f"Signed {'developer key ' + signer if signer else 'not signed by you'}",
1834
1858
  f"Saved {out}",
1835
1859
  f"Receipt {rec_path}",
@@ -1951,6 +1975,9 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1951
1975
  if "already" in out:
1952
1976
  _say(f"Already sealed: {out['already']} (commit {commit[:12]}: this tree is "
1953
1977
  "already in the project's chain; no new seal, nothing logged)")
1978
+ eng = out.get("engagement") or {}
1979
+ if eng.get("taken_over"): # a new vendor's baseline is that seal
1980
+ _say(f"Baseline {_baseline_text(eng)}")
1954
1981
  continue
1955
1982
  chainseal.record(root, out["result"], commit, out["info"]["ref"])
1956
1983
  if i < len(commits) - 1:
@@ -2296,9 +2323,226 @@ def cmd_token(args) -> int:
2296
2323
  return 0
2297
2324
 
2298
2325
 
2326
+ # -- client–vendor engagements (engine 0.7.0a29) ---------------------------------------------
2327
+ ENGAGEMENT_KEY = "codeimprint.engagement-key.v1"
2328
+
2329
+
2330
+ BASELINE = {"matches": "Matches the handover",
2331
+ "same_content": "Same content, different history",
2332
+ "no_shared_history": "No shared history with the handover"}
2333
+
2334
+
2335
+ def _baseline_text(eng: dict) -> str:
2336
+ """The takeover baseline as the server words it (older servers: its result code)."""
2337
+ said = eng.get("taken_over_text") or BASELINE.get(eng.get("taken_over"),
2338
+ str(eng.get("taken_over")))
2339
+ return f"taken over from the previous vendor: {said}"
2340
+
2341
+
2342
+ def _engagement_lines(e: dict) -> list[str]:
2343
+ party = e["party"]
2344
+ who = party.get("name") or "(erased)"
2345
+ lines = [f"Engagement {e['id']} {e['status']} "
2346
+ + ("client-led" if e["mode"] == "client_led" else "vendor-led"),
2347
+ f" Project {e['project_id']}",
2348
+ f" {party['role'].capitalize():<9} {who} ({party['named_by']}"
2349
+ + (f"; confirmed by email ({party['confirmed_by_email']})"
2350
+ if party.get("confirmed_by_email") else "") + ")"]
2351
+ if party.get("email"):
2352
+ lines.append(f" Email {party['email']}")
2353
+ if e.get("token"):
2354
+ lines.append(f" Token {e['token']['id']} {e['token']['status']}, expires "
2355
+ f"{e['token']['expires_at']}")
2356
+ if e["mode"] == "client_led":
2357
+ lines.append(f" Repository {'set by the first seal' if e['home'] == 'set' else 'not set yet'}")
2358
+ lines.append(f" Public {'shown on the public seal pages' if e['public'] else 'no'}")
2359
+ lines += [f" {ev['at'][:10]} {ev['text']}" + (f" [{ev['seal']}]" if ev.get("seal") else "")
2360
+ for ev in e["events"]]
2361
+ return lines
2362
+
2363
+
2364
+ def _project_of(args) -> str | None:
2365
+ root = Path(getattr(args, "path", ".") or ".")
2366
+ cfg = project.load_config(root) if root.is_dir() else {}
2367
+ return args.project or cfg.get("project_id")
2368
+
2369
+
2370
+ def cmd_engagement(args) -> int:
2371
+ """`imprint engagement create | list | show | end | public | join`."""
2372
+ if args.action == "join":
2373
+ return _engagement_join(args)
2374
+ if args.action == "list" and config.resolve(getattr(args, "url", None)).token and \
2375
+ str(config.resolve(getattr(args, "url", None)).token).startswith(CI_TOKEN_PREFIX):
2376
+ client = _client(args)
2377
+ try:
2378
+ mine = client.my_engagement()
2379
+ except (ApiError, NetworkError) as exc:
2380
+ raise Abort(_explain(client, exc, "cannot read the engagement")) from exc
2381
+ if args.json:
2382
+ print(json.dumps(mine, indent=2))
2383
+ return 0
2384
+ _say(*_engagement_lines(mine))
2385
+ return 0
2386
+ client = _session_client(args)
2387
+ try:
2388
+ if args.action == "create":
2389
+ return _engagement_create(args, client)
2390
+ if args.action == "list":
2391
+ items = client.engagements(args.project)
2392
+ if args.json:
2393
+ print(json.dumps(items, indent=2))
2394
+ return 0
2395
+ if not items:
2396
+ _say("No engagements. Start one with `imprint engagement create --vendor "
2397
+ "<name>` (your vendor) or `--client <name> --email <address>` (your "
2398
+ "client).")
2399
+ for e in items:
2400
+ _say(*_engagement_lines(e), "")
2401
+ return 0
2402
+ if not args.target:
2403
+ raise Abort(f"name the engagement: imprint engagement {args.action} <eng_…> (see "
2404
+ "`imprint engagement list`)")
2405
+ if args.action == "show":
2406
+ e = client.engagement(args.target)
2407
+ elif args.action == "end":
2408
+ e = client.end_engagement(args.target, args.handover, args.no_handover)
2409
+ _say("Ended. Its token no longer works and the vendor's keys are retired; the "
2410
+ "history stays.")
2411
+ else:
2412
+ if args.state not in ("on", "off"):
2413
+ raise Abort("say on or off: imprint engagement public <eng_…> on")
2414
+ e = client.engagement_visibility(args.target, args.state == "on")
2415
+ except (ApiError, NetworkError) as exc:
2416
+ raise Abort(_explain(client, exc, "the engagement request failed")) from exc
2417
+ if args.json:
2418
+ print(json.dumps(e, indent=2))
2419
+ return 0
2420
+ _say(*_engagement_lines(e))
2421
+ return 0
2422
+
2423
+
2424
+ def _engagement_create(args, client: Client) -> int:
2425
+ project_id = _project_of(args)
2426
+ if not project_id:
2427
+ raise Abort("no project: run this in the project's folder, or pass --project")
2428
+ if bool(args.vendor) == bool(args.client):
2429
+ raise Abort("name one party: --vendor <name> (you own the project) or --client <name> "
2430
+ "--email <address> (you are the vendor)")
2431
+ if args.client and not args.email:
2432
+ raise Abort("--client needs --email: the client accepts deliveries through a link "
2433
+ "sent there")
2434
+ if not 1 <= args.days <= 365:
2435
+ raise Abort("--days is 1 to 365: an engagement token always expires")
2436
+ made = client.create_engagement(project_id, "client_led" if args.vendor else "vendor_led",
2437
+ args.vendor or args.client, args.email, args.days)
2438
+ _say(*_engagement_lines(made))
2439
+ if made.get("token_value"):
2440
+ _say("", f"Token {made['token_value']}",
2441
+ " Shown once: copy it now. It is not saved on this machine or shown again.",
2442
+ "", "Send the vendor these steps (and the token, in a safe way):", "",
2443
+ made.get("setup", ""))
2444
+ else:
2445
+ _say("", f"Deliver a seal with: imprint deliver <IMP1-…> --to-client "
2446
+ f"(an e-mail asks {made['party']['name']} to accept it)",
2447
+ "The e-mail names you by your certificate details (set them in the hub), else "
2448
+ "your sign-in's handle, else the project's name.")
2449
+ return 0
2450
+
2451
+
2452
+ def _engagement_join(args) -> int:
2453
+ """With an engagement token: this machine's developer key becomes the engagement's key,
2454
+ and this repository's .imprint/config.json names the project."""
2455
+ client = _client(args)
2456
+ if client.auth != "ci":
2457
+ raise Abort("set CODEIMPRINT_TOKEN to the engagement token the project owner gave you "
2458
+ "(`export CODEIMPRINT_TOKEN=cit_…`), then run this again")
2459
+ try:
2460
+ mine = client.my_engagement()
2461
+ except (ApiError, NetworkError) as exc:
2462
+ raise Abort(_explain(client, exc, "cannot read the engagement")) from exc
2463
+ root = Path(args.path)
2464
+ cfg = project.load_config(root) if root.is_dir() else {}
2465
+ if cfg.get("project_id") and cfg["project_id"] != mine["project_id"]:
2466
+ raise Abort(f"this folder is set up for project {cfg['project_id']}; the engagement "
2467
+ f"token is for project {mine['project_id']}. Join from the repository you "
2468
+ "work on for this client.")
2469
+ key = trust.load_developer_key() or trust.create_developer_key()
2470
+ pub = chainseal.public_key(key)
2471
+ statement = {"type": ENGAGEMENT_KEY, "project": mine["project_id"],
2472
+ "engagement": mine["id"], "public_key": pub}
2473
+ try:
2474
+ client.engagement_key(pub, chainseal.sign(key, statement))
2475
+ except (ApiError, NetworkError) as exc:
2476
+ raise Abort(_explain(client, exc, "cannot add your key to the engagement")) from exc
2477
+ fp = trust.fingerprint(trust.public_raw(key))
2478
+ cfg.update(version=cfg.get("version", 1), project_id=mine["project_id"], developer=fp,
2479
+ engagement=mine["id"])
2480
+ cfg.setdefault("exclude", [])
2481
+ (root / project.CONFIG_DIR).mkdir(parents=True, exist_ok=True)
2482
+ (root / project.CONFIG_DIR / project.CONFIG_FILE).write_text(
2483
+ json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
2484
+ _say(f"Joined engagement {mine['id']} as {mine['party']['name']} "
2485
+ f"({mine['party']['named_by']})",
2486
+ f"Project {mine['project_id']}"
2487
+ + (f" ({mine['project_name']})" if mine.get("project_name") else ""),
2488
+ f"Key {fp} (this machine's developer key; it seals for this engagement only)",
2489
+ f"Config {root / project.CONFIG_DIR / project.CONFIG_FILE}",
2490
+ "", "Next: `imprint seal` here. The first seal sets this repository as the "
2491
+ "engagement's; later seals must come from it.")
2492
+ return 0
2493
+
2494
+
2495
+ def cmd_deliver(args) -> int:
2496
+ """`imprint deliver IMP1-… [--note …] [--to-client]`: a vendor delivers a seal."""
2497
+ if not imprint_file.is_valid_id(args.seal):
2498
+ raise Abort(f"not a fingerprint ID (IMP1-…): {args.seal}")
2499
+ iid = imprint_file.clean_id(args.seal)
2500
+ client = _client(args, _server_from_project(Path(".")))
2501
+ if client.auth in ("none", "expired"):
2502
+ raise Abort(f"you are not signed in to {client.url}: use the engagement token "
2503
+ "(CODEIMPRINT_TOKEN) or run `imprint login`")
2504
+ try:
2505
+ out = client.deliver(iid, args.note, args.to_client, args.engagement)
2506
+ except ApiError as exc:
2507
+ if exc.status == 404:
2508
+ raise Abort(f"cannot deliver {iid}: {client.url} has no such seal, or it is not a "
2509
+ "seal of your project or engagement") from exc
2510
+ raise Abort(_explain(client, exc, f"cannot deliver {iid}")) from exc
2511
+ except NetworkError as exc:
2512
+ raise Abort(str(exc)) from exc
2513
+ _say(f"Delivered {out['text']}")
2514
+ if out.get("sent_to"):
2515
+ _say(f"Sent an acceptance link to {out['sent_to']} (it works once and expires "
2516
+ f"{out['link_expires_at'][:10]})")
2517
+ else:
2518
+ _say(" The project owner accepts it with `imprint accept "
2519
+ f"{iid}`.")
2520
+ return 0
2521
+
2522
+
2523
+ def cmd_accept(args) -> int:
2524
+ """`imprint accept IMP1-…`: the project owner accepts a seal its vendor delivered."""
2525
+ if not imprint_file.is_valid_id(args.seal):
2526
+ raise Abort(f"not a fingerprint ID (IMP1-…): {args.seal}")
2527
+ iid = imprint_file.clean_id(args.seal)
2528
+ client = _session_client(args)
2529
+ try:
2530
+ out = client.accept(iid)
2531
+ except ApiError as exc:
2532
+ if exc.status == 404:
2533
+ raise Abort(f"cannot accept {iid}: no such seal in one of your projects") from exc
2534
+ raise Abort(_explain(client, exc, f"cannot accept {iid}")) from exc
2535
+ except NetworkError as exc:
2536
+ raise Abort(str(exc)) from exc
2537
+ _say(f"Accepted {out['text']}")
2538
+ return 0
2539
+
2540
+
2299
2541
  def cmd_project(args) -> int:
2300
2542
  if args.action == "move":
2301
2543
  return _project_move(args)
2544
+ if args.action == "archive":
2545
+ return _project_archive(args)
2302
2546
  if not args.name:
2303
2547
  raise Abort("give the new name: imprint project rename <name>")
2304
2548
  key = _developer_key(required=True)
@@ -2333,6 +2577,53 @@ def _project_move(args) -> int:
2333
2577
  return 0
2334
2578
 
2335
2579
 
2580
+ def _project_archive(args) -> int:
2581
+ """`imprint project archive [folder] [--into <project>]`: a duplicate project for the
2582
+ same repository (for example one made by `imprint init` and one by the GitHub App) stops
2583
+ taking seals. Two steps on the server, the second only after you agree; its seals, chain
2584
+ and pages stay. ``--into`` merges it: its repository, and its GitHub App connection, move
2585
+ to the project you keep."""
2586
+ root = Path(args.name or ".")
2587
+ cfg = project.load_config(root) if root.is_dir() else {}
2588
+ project_id = getattr(args, "project", None) or cfg.get("project_id")
2589
+ if not project_id:
2590
+ raise Abort("no project: pass --project <ID> (or run this in the project's folder)")
2591
+ into = getattr(args, "into", None)
2592
+ sc = _session_client(args)
2593
+ try:
2594
+ step = sc.archive_project(project_id, into, getattr(args, "reason", None))
2595
+ except (ApiError, NetworkError) as exc:
2596
+ raise Abort(f"the project was not archived: {exc}") from exc
2597
+ lines = [f"Project {project_id}",
2598
+ f"Seals {step.get('seals', 0)}: they stay, with the project's chain and pages"]
2599
+ if into:
2600
+ lines.append(f"Merge into {into}: this project's repository becomes that project's")
2601
+ if step.get("github_repositories"):
2602
+ lines.append(f"GitHub App the repository's connection moves to {into}; then run "
2603
+ "`imprint github link` to authorise the App's key there")
2604
+ lines += ["", "An archived project takes no new seals. Archiving is not undone later."]
2605
+ _say(*lines)
2606
+ _ask(args, f"Archive project {project_id}" + (f" and merge it into {into}?" if into
2607
+ else "?"), "archiving")
2608
+ try:
2609
+ done = sc.archive_project_confirm(project_id, step["confirm"])
2610
+ except (ApiError, NetworkError) as exc:
2611
+ raise Abort(f"the project was not archived: {exc}") from exc
2612
+ _say(f"Archived {project_id} on {done['archived_at']}"
2613
+ + (f", merged into {done['merged_into']}" if done.get("merged_into") else ""))
2614
+ if into and cfg.get("project_id") == project_id:
2615
+ cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
2616
+ current = project.load_config(root)
2617
+ current["project_id"], current["homes"] = into, []
2618
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
2619
+ _note_home(root, _identity(root))
2620
+ _say(f"Saved .imprint/config.json now names {into} (commit it)")
2621
+ if done.get("github_repositories"):
2622
+ _say("Next run `imprint github link` in the repository: your developer key "
2623
+ f"authorises the App's key on {into}")
2624
+ return 0
2625
+
2626
+
2336
2627
  GITHUB_MODES = {
2337
2628
  "upgrade": "The App made this project with a key CodeImprint holds. Your developer key "
2338
2629
  "becomes its key too, and authorises the App's key to keep sealing pushes: "
@@ -2875,20 +3166,61 @@ def build_parser() -> argparse.ArgumentParser:
2875
3166
  tk.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2876
3167
  tk.set_defaults(func=cmd_token)
2877
3168
 
2878
- pj = sub.add_parser("project", help="the project: rename it, or record that its "
2879
- "repository moved")
2880
- pj.add_argument("action", choices=["rename", "move"],
3169
+ pj = sub.add_parser("project", help="the project: rename it, record that its "
3170
+ "repository moved, or archive a duplicate")
3171
+ pj.add_argument("action", choices=["rename", "move", "archive"],
2881
3172
  help="rename: a new display name. move: this repository was renamed, "
2882
- "transferred or moved to another host and is still the same project")
3173
+ "transferred or moved to another host and is still the same project. "
3174
+ "archive: a second project for the same repository stops taking "
3175
+ "seals (--into merges it into the one to keep); nothing is deleted")
2883
3176
  pj.add_argument("name", nargs="?", help="rename: the new name (1-100 characters); "
2884
- "move: the project's folder (default: here)")
3177
+ "move, archive: the project's folder (default: "
3178
+ "here)")
2885
3179
  pj.add_argument("path", nargs="?", default=".")
2886
3180
  pj.add_argument("--private", action="store_true",
2887
3181
  help="show the name to you only, not on the public project page")
2888
3182
  pj.add_argument("--project", help="project ID (default: .imprint/config.json)")
3183
+ pj.add_argument("--into", help="archive: the project to keep; this project's repository "
3184
+ "and GitHub App connection move there")
3185
+ pj.add_argument("--reason", help="archive: a note for you (at most 200 characters)")
3186
+ pj.add_argument("--yes", action="store_true", help="archive: do not ask")
2889
3187
  pj.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2890
3188
  pj.set_defaults(func=cmd_project)
2891
3189
 
3190
+ en = sub.add_parser("engagement", help="work with a vendor or a client: create, list, show, "
3191
+ "end, public, join")
3192
+ en.add_argument("action", choices=["create", "list", "show", "end", "public", "join"])
3193
+ en.add_argument("target", nargs="?", help="show, end, public: the engagement's ID (eng_…)")
3194
+ en.add_argument("state", nargs="?", help="public: on or off")
3195
+ en.add_argument("--vendor", help="create: your vendor's name (you own the project)")
3196
+ en.add_argument("--client", help="create: your client's name (you are the vendor)")
3197
+ en.add_argument("--email", help="create --client: where the client's acceptance links go")
3198
+ en.add_argument("--days", type=int, default=90,
3199
+ help="create --vendor: how long the engagement token lasts, 1 to 365")
3200
+ en.add_argument("--project", help="the project (default: .imprint/config.json)")
3201
+ en.add_argument("--path", default=".", help="the project's folder (default: here)")
3202
+ en.add_argument("--handover", metavar="IMP1_ID",
3203
+ help="end: the seal marked as handed over (default: the vendor's latest)")
3204
+ en.add_argument("--no-handover", action="store_true", help="end: no handover marker")
3205
+ en.add_argument("--json", action="store_true")
3206
+ en.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3207
+ en.set_defaults(func=cmd_engagement)
3208
+
3209
+ dl = sub.add_parser("deliver", help="deliver a seal: to the project's owner (engagement "
3210
+ "token) or to your client (--to-client)")
3211
+ dl.add_argument("seal", metavar="IMP1_ID")
3212
+ dl.add_argument("--note", help="a short note (at most 500 characters)")
3213
+ dl.add_argument("--to-client", action="store_true",
3214
+ help="vendor-led: e-mail your client a link to accept it")
3215
+ dl.add_argument("--engagement", help="--to-client: which engagement, when there are several")
3216
+ dl.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3217
+ dl.set_defaults(func=cmd_deliver)
3218
+
3219
+ ac = sub.add_parser("accept", help="accept a seal your vendor delivered (project owner)")
3220
+ ac.add_argument("seal", metavar="IMP1_ID")
3221
+ ac.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3222
+ ac.set_defaults(func=cmd_accept)
3223
+
2892
3224
  gh = sub.add_parser("github", help="the GitHub App: link this repository's project to your "
2893
3225
  "developer key")
2894
3226
  gh.add_argument("action", choices=["link"])
@@ -689,6 +689,21 @@ def _consistent(a: dict, b: dict, proof_hex: list[str]) -> bool:
689
689
  return False
690
690
 
691
691
 
692
+ def _key_by_fingerprint(client, project: str, fingerprint: str) -> dict | None:
693
+ """A key the public list leaves out (a vendor's scoped key, engine 0.7.0a30), asked for
694
+ by the fingerprint the seal's record already names. None when there is no such key or
695
+ the server is older."""
696
+ if not hasattr(client, "public_project_key"):
697
+ return None
698
+ try:
699
+ k = client.public_project_key(project, fingerprint)
700
+ except Exception: # noqa: BLE001 — an older server, or no such key: the check fails
701
+ return None
702
+ # Only that key: an answer about anything else proves nothing.
703
+ ok = isinstance(k, dict) and k.get("fingerprint") == fingerprint and k.get("valid_from")
704
+ return k if ok else None
705
+
706
+
692
707
  def verify_online(receipt: dict, client, keys: list[dict],
693
708
  anchors: list | None = None) -> list[Check]:
694
709
  """Check the receipt against the server's current log (``client`` is an api.Client)."""
@@ -751,7 +766,7 @@ def verify_online(receipt: dict, client, keys: list[dict],
751
766
  attested = receipt["attestation"]["statement"]["attested_at"]
752
767
  keys_now = {k["fingerprint"]: k
753
768
  for k in client.public_project(signed_for).get("keys", [])}
754
- k = keys_now.get(signer)
769
+ k = keys_now.get(signer) or _key_by_fingerprint(client, signed_for, signer)
755
770
  if k and k["valid_from"] <= attested and (not k["valid_until"]
756
771
  or attested <= k["valid_until"]):
757
772
  checks.append(Check("project key", PASS, f"{signer} was a key of project "
File without changes
File without changes