@praxso/attested 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @praxso/attested
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Signed, verifiable test receipts for agent-authored pull requests.
4
+
5
+ `attested` wraps an ordinary Playwright run, or any test run that writes a [CTRF](https://ctrf.io) report, and turns it into an [in-toto](https://github.com/in-toto/attestation) receipt: the result, the failing tests, the exact commit, and the sha256 of every trace, video, and screenshot. In GitHub Actions the receipt is signed with Sigstore keyless signing through `actions/attest`, and anyone can check it with `gh attestation verify`.
6
+
7
+ No custom runner, no hosted service, no images posted anywhere. Evidence stays in the workflow artifact of the run that produced it; only digests travel in the receipt.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install --save-dev @praxso/attested
13
+ ```
14
+
15
+ Requires Node 22 or newer.
16
+
17
+ ## Use
18
+
19
+ ```bash
20
+ npx attested run -- npx playwright test
21
+ ```
22
+
23
+ ```bash
24
+ npx attested attest
25
+ ```
26
+
27
+ `run` executes your test command, requires a CTRF report, and writes `attested/receipt.json`. On a red run it also writes `attested/packet.json`, a redacted failure packet under 12 KB that a coding agent can act on. `attest` prepares the predicate for the `actions/attest` step in your workflow. `check` posts a text-only GitHub check run.
28
+
29
+ Workflow setup, the `attested verify` required check, and the organization ruleset that makes it unforgeable are documented in the repository: https://github.com/Praxso/attested
30
+
31
+ ## Agents
32
+
33
+ The MCP server is a separate package, [`@praxso/attested-mcp`](https://www.npmjs.com/package/@praxso/attested-mcp).
34
+
35
+ ## License
36
+
37
+ Apache-2.0
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // Committed launcher so the bin shim exists before `pnpm build` runs.
3
+ // pnpm does not create a bin shim for a workspace package whose bin target is
4
+ // missing at install time, and dist/ only exists after the build.
5
+ import('../dist/index.js').catch((err) => {
6
+ process.stderr.write(`attested: not built (${err.message}); run \`pnpm build\` first\n`);
7
+ process.exit(1);
8
+ });
@@ -0,0 +1,112 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, rmSync, statSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { buildPacket, serializePacket } from './packet.js';
5
+ import { buildReceipt, testResultFromCtrf, toolInfo, validateCtrf } from './receipt.js';
6
+ import { clean } from './redact.js';
7
+ import { AttestedError, checkInside, classify, info, readInside, relPath, runUrl, sha256File, walk, writeOutput } from './util.js';
8
+ // Largest ctrf.json that is parsed. CTRF for tens of thousands of tests is a few MB.
9
+ export const MAX_CTRF_BYTES = 32 * 1024 * 1024;
10
+ const SUMMARY_FIELDS = ['tests', 'passed', 'failed', 'skipped', 'pending', 'other', 'flaky', 'start', 'stop', 'duration'];
11
+ // The CTRF metadata copied into the receipt: allowlisted fields only, strings redacted and bounded, counts numeric.
12
+ // The ctrf.json subject itself is never rewritten; only these copies are.
13
+ export function ctrfMeta(ctrf) {
14
+ const str = (v, max) => (typeof v === 'string' ? clean(v, max) : null);
15
+ const t = ctrf.results.tool;
16
+ const tool = t && typeof t === 'object' ? { name: str(t.name, 100), version: str(t.version, 50) } : null;
17
+ const s = ctrf.results.summary;
18
+ let summary = null;
19
+ if (s && typeof s === 'object') {
20
+ summary = {};
21
+ for (const k of SUMMARY_FIELDS) {
22
+ const v = s[k];
23
+ if (typeof v === 'number' && Number.isFinite(v))
24
+ summary[k] = v;
25
+ }
26
+ }
27
+ return { specVersion: str(ctrf.specVersion, 32), tool, summary };
28
+ }
29
+ // Longest file path or configuration name written into the signed predicate.
30
+ const MAX_PUBLIC_PATH = 1000;
31
+ // A path as it is written into the signed, public predicate. Paths must stay exact so the evidence can be checked
32
+ // against them, so a path that redaction would change (it looks like it holds a secret or an email) or that is too
33
+ // long is refused rather than rewritten.
34
+ export function publicPath(root, file, who) {
35
+ const path = relPath(root, file);
36
+ if (clean(path, MAX_PUBLIC_PATH) !== path)
37
+ throw new AttestedError(`${who}: refusing to publish the path ${clean(path, 200)}: it is over ${MAX_PUBLIC_PATH} characters or looks like it contains a secret or an email; rename it`);
38
+ return path;
39
+ }
40
+ // Everything the receipt says about the run, computed from files under `root` only: the CTRF report, the output dir,
41
+ // and the test config. Used by `attested run` (root = the project) and by `attested attest --from-results`
42
+ // (root = a downloaded results directory, which is treated strictly as data).
43
+ export function assemble(root, o) {
44
+ const ctrfPath = resolve(root, o.ctrf);
45
+ if (!checkInside(root, ctrfPath, 'CTRF report'))
46
+ throw new AttestedError(`${o.who}: CTRF report not found at ${o.ctrf} (configure the CTRF reporter or pass --ctrf)`);
47
+ const size = statSync(ctrfPath).size;
48
+ if (size > MAX_CTRF_BYTES)
49
+ throw new AttestedError(`${o.who}: ${o.ctrf} is ${size} bytes, over the ${MAX_CTRF_BYTES}-byte limit for CTRF reports`);
50
+ // One descriptor: the bytes parsed are the bytes hashed into the subject, whatever happens to the path meanwhile.
51
+ const bytes = readInside(root, ctrfPath, MAX_CTRF_BYTES, 'CTRF report');
52
+ if (!bytes)
53
+ throw new AttestedError(`${o.who}: CTRF report not found at ${o.ctrf}`);
54
+ let ctrf;
55
+ try {
56
+ ctrf = JSON.parse(bytes.toString('utf8'));
57
+ }
58
+ catch {
59
+ throw new AttestedError(`${o.who}: ${o.ctrf} is not valid JSON`);
60
+ }
61
+ const invalid = validateCtrf(ctrf);
62
+ if (invalid)
63
+ throw new AttestedError(`${o.who}: ${o.ctrf} is not a CTRF report (${invalid})`);
64
+ const subject = { sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.length };
65
+ const artifacts = [{ path: publicPath(root, ctrfPath, o.who), ...subject, kind: 'report' }];
66
+ const outputDir = resolve(root, o.outputDir);
67
+ if (checkInside(root, outputDir, 'output directory')) {
68
+ for (const file of walk(outputDir))
69
+ artifacts.push({ path: publicPath(root, file, o.who), ...sha256File(file), kind: classify(file) });
70
+ }
71
+ const configuration = [];
72
+ const configPath = o.config ?? ['playwright.config.ts', 'playwright.config.js', 'playwright.config.mjs'].find((p) => checkInside(root, resolve(root, p), 'test config')) ?? null;
73
+ if (configPath && checkInside(root, resolve(root, configPath), 'test config'))
74
+ configuration.push({ name: publicPath(root, resolve(root, configPath), o.who), digest: { sha256: sha256File(resolve(root, configPath)).sha256 } });
75
+ if (process.env.GITHUB_WORKFLOW_REF)
76
+ configuration.push({ name: clean(process.env.GITHUB_WORKFLOW_REF, MAX_PUBLIC_PATH), digest: { gitCommit: process.env.GITHUB_SHA ?? '' } });
77
+ const testResult = testResultFromCtrf(ctrf, configuration, runUrl());
78
+ const packet = testResult.result === 'FAILED' ? buildPacket(ctrf, artifacts, root, o.rerun) : null;
79
+ return { ctrf, subject, artifacts, testResult, packet };
80
+ }
81
+ // Write the packet (on red), the receipt, the predicate, and the in-toto Test Result predicate.
82
+ export function writeReceipt(a, out, rest) {
83
+ const artifacts = [...a.artifacts];
84
+ rmSync(out.packet, { force: true });
85
+ if (a.packet) {
86
+ mkdirSync(dirname(out.packet), { recursive: true });
87
+ writeOutput(out.packet, serializePacket(a.packet));
88
+ // The packet's digest sits next to the evidence it points at.
89
+ artifacts.push({ path: out.packetArtifactPath, ...sha256File(out.packet), kind: 'packet' });
90
+ info(`failure packet: ${out.packetArtifactPath} (${a.packet.failingTests.length} failure groups${a.packet.truncated ? ', truncated' : ''})`);
91
+ }
92
+ const predicate = {
93
+ testResult: a.testResult,
94
+ source: rest.source,
95
+ target: rest.target,
96
+ artifacts,
97
+ tool: toolInfo(),
98
+ ctrf: ctrfMeta(a.ctrf),
99
+ createdAt: rest.createdAt,
100
+ };
101
+ const receipt = buildReceipt(a.subject.sha256, predicate);
102
+ mkdirSync(dirname(out.receipt), { recursive: true });
103
+ writeOutput(out.receipt, JSON.stringify(receipt, null, 2) + '\n');
104
+ writeOutput(out.predicate, JSON.stringify(predicate, null, 2) + '\n');
105
+ // Second, pure in-toto Test Result statement for interoperability.
106
+ writeOutput(out.testResultPredicate, JSON.stringify(a.testResult, null, 2) + '\n');
107
+ const tr = a.testResult;
108
+ info(`receipt: ${relPath(process.cwd(), out.receipt)} (${tr.result}, ${tr.passedTests.length} passed, ${tr.failedTests.length} failed, ${artifacts.length} artifacts)`);
109
+ if (tr.failedTests.length)
110
+ info(`failed: ${tr.failedTests.join('; ')}`);
111
+ return receipt;
112
+ }
package/dist/attest.js ADDED
@@ -0,0 +1,94 @@
1
+ import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { assemble, writeReceipt } from './assemble.js';
4
+ import { DEFAULTS, PREDICATE_TYPE, TEST_RESULT_PREDICATE_TYPE } from './constants.js';
5
+ import { AttestedError, inActions, info, readEvent, relPath, sha256File, warn, writeOutput } from './util.js';
6
+ export function defaultAttestOptions() {
7
+ return {
8
+ receipt: DEFAULTS.receipt, ctrf: DEFAULTS.ctrf, predicate: DEFAULTS.predicate, testResultPredicate: DEFAULTS.testResultPredicate,
9
+ fromResults: null, out: 'signed/attested', outputDir: DEFAULTS.outputDir, config: null, rerun: null,
10
+ };
11
+ }
12
+ function emitOutputs(subjectPath, sha256, predicatePath, testResultPath) {
13
+ setOutput('subject-path', subjectPath);
14
+ setOutput('subject-sha256', sha256);
15
+ setOutput('predicate-path', predicatePath);
16
+ setOutput('predicate-type', PREDICATE_TYPE);
17
+ setOutput('test-result-predicate-path', testResultPath);
18
+ setOutput('test-result-predicate-type', TEST_RESULT_PREDICATE_TYPE);
19
+ info(`prepared predicate for actions/attest: subject ctrf.json sha256:${sha256}, type ${PREDICATE_TYPE}`);
20
+ }
21
+ // The results directory (attested/ctrf.json, test-results/, the test config) was written by PR code and is only read
22
+ // and hashed here. Everything about the source comes from the event context of this job, never from those files.
23
+ export function attestFromResults(opts) {
24
+ const root = resolve(opts.fromResults);
25
+ if (!existsSync(root) && !isSymlink(root))
26
+ throw new AttestedError(`attested attest: results directory ${opts.fromResults} not found`);
27
+ if (isSymlink(root))
28
+ throw new AttestedError(`attested attest: results directory ${opts.fromResults} is a symlink; refusing to read it`);
29
+ if (!statSync(root).isDirectory())
30
+ throw new AttestedError(`attested attest: results directory ${opts.fromResults} is not a directory`);
31
+ const commit = process.env.GITHUB_SHA;
32
+ if (!commit)
33
+ throw new AttestedError('attested attest: --from-results needs GITHUB_SHA (the commit the test job checked out) from the workflow context');
34
+ const a = assemble(root, { ctrf: opts.ctrf, outputDir: opts.outputDir, config: opts.config, rerun: opts.rerun ?? 'see the attested run job', who: 'attested attest' });
35
+ const out = resolve(opts.out);
36
+ mkdirSync(out, { recursive: true });
37
+ const subjectPath = join(out, 'ctrf.json');
38
+ copyFileSync(resolve(root, opts.ctrf), subjectPath);
39
+ if (sha256File(subjectPath).sha256 !== a.subject.sha256)
40
+ throw new AttestedError('attested attest: ctrf.json changed while copying; refusing to attest');
41
+ const paths = { receipt: join(out, 'receipt.json'), predicate: join(out, 'predicate.json'), testResultPredicate: join(out, 'test-result.json'), packet: join(out, 'packet.json') };
42
+ writeReceipt(a, { ...paths, packetArtifactPath: relPath(dirname(out), paths.packet) }, {
43
+ source: { commit, headCommit: readEvent()?.pull_request?.head?.sha ?? null, dirty: null, ref: process.env.GITHUB_REF ?? null },
44
+ target: { buildSha: null, url: null },
45
+ createdAt: new Date().toISOString(),
46
+ });
47
+ if (!inActions())
48
+ warn('not running in GitHub Actions: receipt is UNSIGNED and no attestation was created.');
49
+ emitOutputs(subjectPath, a.subject.sha256, paths.predicate, paths.testResultPredicate);
50
+ return 0;
51
+ }
52
+ function isSymlink(p) {
53
+ try {
54
+ return lstatSync(p).isSymbolicLink();
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ function setOutput(name, value) {
61
+ const file = process.env.GITHUB_OUTPUT;
62
+ if (file)
63
+ appendFileSync(file, `${name}=${value}\n`);
64
+ else
65
+ info(`output ${name}=${value}`);
66
+ }
67
+ export function attest(opts) {
68
+ if (opts.fromResults)
69
+ return attestFromResults(opts);
70
+ const cwd = process.cwd();
71
+ const receiptPath = resolve(cwd, opts.receipt);
72
+ const ctrfPath = resolve(cwd, opts.ctrf);
73
+ if (!existsSync(receiptPath))
74
+ throw new AttestedError(`attested attest: receipt not found at ${opts.receipt}; run \`attested run\` first`);
75
+ if (!existsSync(ctrfPath))
76
+ throw new AttestedError(`attested attest: CTRF report not found at ${opts.ctrf}`);
77
+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
78
+ const actual = sha256File(ctrfPath).sha256;
79
+ const expected = receipt.subject[0]?.digest.sha256;
80
+ if (actual !== expected) {
81
+ throw new AttestedError(`attested attest: ${opts.ctrf} changed since \`attested run\` (sha256 ${actual} != ${expected}); refusing to attest`);
82
+ }
83
+ if (!inActions()) {
84
+ // The receipt carries no signed/unsigned claim; `gh attestation verify` is the only answer to that question.
85
+ warn('not running in GitHub Actions: receipt is UNSIGNED and no attestation was created. Push to GitHub to get a Sigstore-signed attestation.');
86
+ return 0;
87
+ }
88
+ // In Actions, signing is delegated to the actions/attest step that follows.
89
+ // The predicate file was written by `attested run`; we re-emit it from the receipt so the two cannot drift.
90
+ writeOutput(resolve(cwd, opts.predicate), JSON.stringify(receipt.predicate, null, 2) + '\n');
91
+ writeOutput(resolve(cwd, opts.testResultPredicate), JSON.stringify(receipt.predicate.testResult, null, 2) + '\n');
92
+ emitOutputs(ctrfPath, actual, resolve(cwd, opts.predicate), resolve(cwd, opts.testResultPredicate));
93
+ return 0;
94
+ }
package/dist/check.js ADDED
@@ -0,0 +1,152 @@
1
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { DEFAULTS, PREDICATE_TYPE, TOOL_NAME } from './constants.js';
4
+ import { AttestedError, info, readEvent, runUrl, signerWorkflow } from './util.js';
5
+ export function defaultCheckOptions() {
6
+ return { receipt: DEFAULTS.receipt, packet: DEFAULTS.packet, artifactUrl: null, artifactName: null, evidenceName: null, attestationUrl: null };
7
+ }
8
+ // Selects the statement `attested verify` accepts from `gh attestation verify --format json`: the certificate names
9
+ // this run and ref, and the predicate's commit or PR head is the head the check is attached to. Null (jq -e fails) when none.
10
+ const STATEMENT_JQ = `[.[].verificationResult | select(.signature.certificate.sourceRepositoryRef == $ref and ((.signature.certificate.runInvocationURI // "") | test("/actions/runs/" + $run + "(/attempts/[0-9]+)?$"))) | .statement | select(.predicateType == "${PREDICATE_TYPE}" and (.predicate.source.commit == $head or .predicate.source.headCommit == $head))] | first`;
11
+ const SUM_LINE = '"\\(.sha256) \\(.path)"';
12
+ function shellQuote(s) {
13
+ return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
14
+ }
15
+ export function conclusionFor(result) {
16
+ if (result === 'PASSED')
17
+ return 'success';
18
+ if (result === 'FAILED')
19
+ return 'failure';
20
+ return 'neutral';
21
+ }
22
+ // The sha the check run is attached to: the PR head on pull_request (GITHUB_SHA is the synthetic merge commit there).
23
+ export function checkHeadSha() {
24
+ const ev = readEvent();
25
+ return ev?.pull_request?.head?.sha ?? process.env.GITHUB_SHA ?? null;
26
+ }
27
+ // On a pull_request from a fork, GITHUB_TOKEN is read-only and cannot create check runs.
28
+ export function isForkPullRequest() {
29
+ const ev = readEvent();
30
+ const head = ev?.pull_request?.head?.repo?.full_name;
31
+ const base = ev?.pull_request?.base?.repo?.full_name ?? process.env.GITHUB_REPOSITORY;
32
+ return Boolean(head && base && head !== base);
33
+ }
34
+ export function buildSummary(receipt, packet, opts) {
35
+ const p = receipt.predicate;
36
+ const tr = p.testResult;
37
+ const s = (p.ctrf.summary ?? {});
38
+ const repo = process.env.GITHUB_REPOSITORY ?? '<owner>/<repo>';
39
+ const signer = signerWorkflow() ?? `${repo}/.github/workflows/attested.yml`;
40
+ const digest = receipt.subject[0]?.digest.sha256 ?? '';
41
+ const lines = [];
42
+ const counts = `${s.tests ?? tr.passedTests.length + tr.failedTests.length + tr.warnedTests.length} tests: ${tr.passedTests.length} passed, ${tr.failedTests.length} failed, ${tr.warnedTests.length} other`;
43
+ const title = `${tr.result}: ${counts}`;
44
+ lines.push(`### ${TOOL_NAME}: ${tr.result}`, '', '| | |', '|---|---|');
45
+ lines.push(`| Verdict | **${tr.result}** |`);
46
+ const head = p.source.headCommit;
47
+ lines.push(`| Commit tested | \`${p.source.commit ?? 'unknown'}\`${head && head !== p.source.commit ? ` (PR head \`${head}\`)` : ''} |`);
48
+ lines.push(`| Target build | ${p.target.buildSha ? `\`${p.target.buildSha}\` at ${p.target.url}` : 'none (no --target-url)'} |`);
49
+ lines.push(`| Tests | ${counts} |`);
50
+ lines.push(`| Subject | \`ctrf.json\` sha256 \`${digest}\` |`);
51
+ lines.push(`| Evidence | ${opts.artifactUrl ? `[workflow artifact](${opts.artifactUrl})` : 'workflow artifact'} (traces, videos, screenshots; access follows this repository's visibility; never posted to the PR) |`);
52
+ if (opts.attestationUrl)
53
+ lines.push(`| Attestation | ${opts.attestationUrl} |`);
54
+ const url = runUrl();
55
+ if (url)
56
+ lines.push(`| Run | ${url} |`);
57
+ lines.push('', 'Verify this receipt yourself:', '', '```bash');
58
+ const runId = process.env.GITHUB_RUN_ID;
59
+ const ref = process.env.GITHUB_REF;
60
+ const headSha = checkHeadSha();
61
+ if (runId && opts.artifactName)
62
+ lines.push(`gh run download ${runId} --repo ${repo} --name ${opts.artifactName} --dir attested-receipt`);
63
+ const verify = `gh attestation verify attested-receipt/attested/ctrf.json --repo ${repo} --predicate-type ${PREDICATE_TYPE} --signer-workflow ${signer}`;
64
+ // The accepted statement is the one `attested verify` would accept: signed in this run, on this ref, for this head.
65
+ // Every later check reads the statement, never the downloaded receipt.json, which is unsigned.
66
+ const pinned = Boolean(runId && ref && headSha);
67
+ if (pinned) {
68
+ lines.push(`${verify} --format json > attested-verify.json`);
69
+ lines.push(`jq -e --arg run ${runId} --arg ref ${shellQuote(ref)} --arg head ${headSha} '${STATEMENT_JQ}' attested-verify.json > attested-statement.json`);
70
+ }
71
+ else {
72
+ lines.push(verify);
73
+ }
74
+ lines.push('```');
75
+ // The evidence travels in its own artifact. Its name defaults to the bundled workflow's (results-<sha> beside
76
+ // attested-<sha>), as the signer workflow above defaults to the bundled attested.yml.
77
+ const evidence = opts.evidenceName ?? (opts.artifactName?.startsWith('attested-') ? `results-${opts.artifactName.slice('attested-'.length)}` : null);
78
+ if (pinned && evidence) {
79
+ lines.push('', 'Get the evidence (screenshots, videos, traces) and check each file against the fingerprints in the signed statement:', '', '```bash');
80
+ lines.push(`gh run download ${runId} --repo ${repo} --name ${evidence} --dir attested-evidence`);
81
+ // The sign job writes the failure packet into the receipt artifact, so packet entries are checked there.
82
+ lines.push(`(cd attested-evidence && jq -r '.predicate.artifacts[] | select(.kind != "packet") | ${SUM_LINE}' ../attested-statement.json | shasum -a 256 -c)`);
83
+ if (p.artifacts?.some((a) => a.kind === 'packet')) {
84
+ lines.push(`(cd attested-receipt && jq -r '.predicate.artifacts[] | select(.kind == "packet") | ${SUM_LINE}' ../attested-statement.json | shasum -a 256 -c)`);
85
+ }
86
+ lines.push('```');
87
+ lines.push('', "Artifacts follow this repository's artifact retention (90 days by default); the receipt's digests and signature outlast them.");
88
+ }
89
+ if (tr.failedTests.length && packet) {
90
+ lines.push('', 'Failure packet (`attested/packet.json`):', '', '```json', packet.trimEnd(), '```');
91
+ }
92
+ else if (tr.failedTests.length) {
93
+ lines.push('', 'Failed tests:', '', ...tr.failedTests.map((t) => `- ${t}`));
94
+ }
95
+ return { title, summary: lines.join('\n') + '\n' };
96
+ }
97
+ function toLogAndSummary(summary) {
98
+ process.stdout.write(summary);
99
+ const file = process.env.GITHUB_STEP_SUMMARY;
100
+ if (file)
101
+ appendFileSync(file, summary);
102
+ }
103
+ export async function check(opts) {
104
+ const cwd = process.cwd();
105
+ const receiptPath = resolve(cwd, opts.receipt);
106
+ if (!existsSync(receiptPath))
107
+ throw new AttestedError(`attested check: receipt not found at ${opts.receipt}; run \`attested run\` first`);
108
+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
109
+ const packetPath = resolve(cwd, opts.packet);
110
+ const packet = existsSync(packetPath) ? readFileSync(packetPath, 'utf8') : null;
111
+ const conclusion = conclusionFor(receipt.predicate.testResult.result);
112
+ const { title, summary } = buildSummary(receipt, packet, opts);
113
+ const token = process.env.GITHUB_TOKEN;
114
+ const repo = process.env.GITHUB_REPOSITORY;
115
+ const headSha = checkHeadSha();
116
+ if (isForkPullRequest()) {
117
+ toLogAndSummary(summary);
118
+ process.stdout.write(`::notice title=attested check::forked pull request: GITHUB_TOKEN is read-only, so no check run was created; the summary above is the same content (conclusion ${conclusion}).\n`);
119
+ return 0;
120
+ }
121
+ if (!token || !repo || !headSha) {
122
+ toLogAndSummary(summary);
123
+ info(`no GITHUB_TOKEN/GITHUB_REPOSITORY/head sha: printed the check summary instead of creating a check run (conclusion ${conclusion})`);
124
+ return 0;
125
+ }
126
+ const api = process.env.GITHUB_API_URL ?? 'https://api.github.com';
127
+ const body = {
128
+ name: TOOL_NAME,
129
+ head_sha: headSha,
130
+ status: 'completed',
131
+ conclusion,
132
+ details_url: runUrl() ?? undefined,
133
+ // Text only. The `images` field is never used: evidence stays in the workflow artifact, as visible as the repository's Actions artifacts (PixelLeak rule).
134
+ output: { title, summary },
135
+ };
136
+ const res = await fetch(`${api}/repos/${repo}/check-runs`, {
137
+ method: 'POST',
138
+ headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', 'content-type': 'application/json' },
139
+ body: JSON.stringify(body),
140
+ });
141
+ if (res.status === 403) {
142
+ toLogAndSummary(summary);
143
+ process.stdout.write(`::notice title=attested check::GITHUB_TOKEN cannot create check runs here (HTTP 403; add \`checks: write\`, or this is a fork); the summary above is the same content (conclusion ${conclusion}).\n`);
144
+ return 0;
145
+ }
146
+ if (!res.ok)
147
+ throw new AttestedError(`attested check: creating the check run failed: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`);
148
+ const created = (await res.json());
149
+ toLogAndSummary(summary);
150
+ info(`check run "${TOOL_NAME}" (${conclusion}) on ${headSha}: ${created.html_url ?? ''}`);
151
+ return 0;
152
+ }
@@ -0,0 +1,17 @@
1
+ // Single place to rename the project or move the predicate URI.
2
+ export const TOOL_NAME = 'attested';
3
+ // Must equal packages/cli/package.json version; test/version.test.mjs enforces it.
4
+ export const TOOL_VERSION = '0.1.1';
5
+ export const PREDICATE_TYPE = 'https://praxso.ai/attested/v0.1';
6
+ export const TEST_RESULT_PREDICATE_TYPE = 'https://in-toto.io/attestation/test-result/v0.1';
7
+ export const STATEMENT_TYPE = 'https://in-toto.io/Statement/v1';
8
+ export const SUBJECT_NAME = 'ctrf.json';
9
+ export const DEFAULTS = {
10
+ ctrf: 'attested/ctrf.json',
11
+ outputDir: 'test-results',
12
+ receipt: 'attested/receipt.json',
13
+ predicate: 'attested/predicate.json',
14
+ testResultPredicate: 'attested/test-result.json',
15
+ packet: 'attested/packet.json',
16
+ healthPath: '/healthz',
17
+ };