@contentauth/c2pa-node 0.9.7 → 0.9.9
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/Cargo.toml +1 -1
- package/README.md +3 -0
- package/dist/Builder.js +3 -0
- package/dist/Builder.spec.js +110 -3
- package/dist/IdentityAssertion.js +1 -1
- package/dist/IdentityAssertion.spec.js +101 -0
- package/dist/Reader.spec.js +17 -0
- package/dist/index.node +2 -2
- package/dist/types/Builder.d.ts +1 -0
- package/dist/types/types.d.ts +28 -4
- package/package.json +3 -3
- package/src/asset.rs +18 -13
- package/src/lib.rs +16 -0
- package/src/neon_builder.rs +47 -0
- package/src/neon_credential_holder.rs +100 -3
- package/src/neon_identity_assertion_builder.rs +35 -3
- package/src/neon_identity_assertion_signer.rs +3 -40
- package/src/neon_reader.rs +6 -12
- package/src/neon_signer.rs +2 -100
package/Cargo.toml
CHANGED
package/README.md
CHANGED
|
@@ -97,6 +97,9 @@ const remoteUrl = reader.remoteUrl();
|
|
|
97
97
|
|
|
98
98
|
`Reader.fromAsset` and `Reader.fromManifestDataAndAsset` reject assets larger than 10 GB, throwing `AssetTooLargeError` (exported from `@contentauth/c2pa-node`). Note that for a `SourceBufferAsset`, this only rejects after the buffer is already fully allocated in memory. Pass a `FileAsset` instead for large or untrusted assets so oversized files are rejected before being read into memory.
|
|
99
99
|
|
|
100
|
+
> [!WARNING]
|
|
101
|
+
> `mimeType` is optional on the input asset for `Reader.fromAsset`/`Reader.fromManifestDataAndAsset`. If it's omitted and cannot be inferred from the file extension, the native library falls back to detecting the format from the asset's bytes. **This is not a feature to lean on.** Always supply `mimeType` when it's known, as byte-based detection is slower than a direct lookup and can be unreliable, which could surface as more confusing errors later on. Only omit it when the caller has no way to determine the asset's format. `Builder` methods always require a `mimeType` to be provided.
|
|
102
|
+
|
|
100
103
|
### Builder
|
|
101
104
|
|
|
102
105
|
The `Builder` class is the main component for creating and signing C2PA manifests. It provides methods to add assertions, resources, and ingredients to manifests, and handles the signing process. Use the `Signer` class to sign the manifests. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
|
package/dist/Builder.js
CHANGED
|
@@ -200,6 +200,9 @@ export class Builder {
|
|
|
200
200
|
updateActions(transform) {
|
|
201
201
|
getNeonBinary().builderUpdateActions.call(this.builder, transform);
|
|
202
202
|
}
|
|
203
|
+
updateAssertion(label, transform) {
|
|
204
|
+
getNeonBinary().builderUpdateAssertion.call(this.builder, label, transform);
|
|
205
|
+
}
|
|
203
206
|
getHandle() {
|
|
204
207
|
return this.builder;
|
|
205
208
|
}
|
package/dist/Builder.spec.js
CHANGED
|
@@ -179,11 +179,10 @@ describe("Builder", () => {
|
|
|
179
179
|
expect(activeManifest?.title).toBe("Test_Manifest");
|
|
180
180
|
});
|
|
181
181
|
it("should add a CBOR assertion, sign, and verify it in the signed manifest", async () => {
|
|
182
|
-
// Add the c2pa.watermarked action as a CBOR assertion
|
|
183
182
|
const actionsAssertion = {
|
|
184
183
|
actions: [
|
|
185
184
|
{
|
|
186
|
-
action: "c2pa.
|
|
185
|
+
action: "c2pa.edited",
|
|
187
186
|
},
|
|
188
187
|
],
|
|
189
188
|
};
|
|
@@ -200,7 +199,7 @@ describe("Builder", () => {
|
|
|
200
199
|
expect(cborAssertion).toBeDefined();
|
|
201
200
|
if (isActionsAssertion(cborAssertion)) {
|
|
202
201
|
const actions = cborAssertion.data.actions.map((a) => a.action);
|
|
203
|
-
expect(actions).toContain("c2pa.
|
|
202
|
+
expect(actions).toContain("c2pa.edited");
|
|
204
203
|
}
|
|
205
204
|
else {
|
|
206
205
|
throw new Error("CBOR assertion does not have the expected structure");
|
|
@@ -825,6 +824,12 @@ describe("Builder", () => {
|
|
|
825
824
|
const context = new Context({ verify: { verifyTrust: false } });
|
|
826
825
|
const builder = await Builder.newAsync(context);
|
|
827
826
|
builder.updateManifestProperty("claim_version", 2);
|
|
827
|
+
// c2pa-rs requires the first action assertion to be c2pa.created/c2pa.opened,
|
|
828
|
+
// and c2pa.created requires a digitalSourceType.
|
|
829
|
+
builder.addAction(JSON.stringify({
|
|
830
|
+
action: "c2pa.created",
|
|
831
|
+
digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
|
|
832
|
+
}));
|
|
828
833
|
await builder.addIngredient(parent_json, source);
|
|
829
834
|
builder.sign(signer, source, dest);
|
|
830
835
|
const reader = await Reader.fromAsset(dest, context);
|
|
@@ -837,6 +842,12 @@ describe("Builder", () => {
|
|
|
837
842
|
// Trust verification disabled via Context.
|
|
838
843
|
const context = new Context({ verify: { verifyTrust: false } });
|
|
839
844
|
const builder = await Builder.withJsonAsync(manifestDefinition, context);
|
|
845
|
+
// c2pa-rs requires the first action assertion to be c2pa.created/c2pa.opened,
|
|
846
|
+
// and c2pa.created requires a digitalSourceType.
|
|
847
|
+
builder.addAction(JSON.stringify({
|
|
848
|
+
action: "c2pa.created",
|
|
849
|
+
digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
|
|
850
|
+
}));
|
|
840
851
|
await builder.addIngredient(parent_json, source);
|
|
841
852
|
await builder.addResource("thumbnail.jpg", {
|
|
842
853
|
mimeType: "jpeg",
|
|
@@ -1042,6 +1053,102 @@ describe("Builder", () => {
|
|
|
1042
1053
|
throw new Error("action predicate boom");
|
|
1043
1054
|
}, () => false)).toThrow("action predicate boom");
|
|
1044
1055
|
});
|
|
1056
|
+
it("updateAssertion updates exact label matches in order and preserves metadata", () => {
|
|
1057
|
+
const builder = Builder.withJson({
|
|
1058
|
+
...actionsManifest(),
|
|
1059
|
+
assertions: [
|
|
1060
|
+
{ label: "org.test.note", data: { value: 1 }, kind: "Cbor" },
|
|
1061
|
+
{ label: "org.test.note.extra", data: { value: 9 } },
|
|
1062
|
+
{ label: "org.test.note", data: { value: 2 }, kind: "Cbor" },
|
|
1063
|
+
],
|
|
1064
|
+
});
|
|
1065
|
+
const seen = [];
|
|
1066
|
+
builder.updateAssertion("org.test.note", (data) => {
|
|
1067
|
+
const value = data.value;
|
|
1068
|
+
seen.push(value);
|
|
1069
|
+
return { value: value + 10 };
|
|
1070
|
+
});
|
|
1071
|
+
expect(seen).toEqual([1, 2]);
|
|
1072
|
+
expect(builder.getManifestDefinition().assertions).toEqual([
|
|
1073
|
+
{ label: "org.test.note", data: { value: 11 }, kind: "Cbor" },
|
|
1074
|
+
{ label: "org.test.note.extra", data: { value: 9 } },
|
|
1075
|
+
{ label: "org.test.note", data: { value: 12 }, kind: "Cbor" },
|
|
1076
|
+
]);
|
|
1077
|
+
});
|
|
1078
|
+
it("updateAssertion preserves JSON and CBOR kinds when signing", async () => {
|
|
1079
|
+
const builder = Builder.withJson({
|
|
1080
|
+
...actionsManifest(),
|
|
1081
|
+
assertions: [
|
|
1082
|
+
...actionsManifest().assertions,
|
|
1083
|
+
{ label: "org.test.json", data: { value: 1 }, kind: "Json" },
|
|
1084
|
+
{ label: "org.test.cbor", data: { value: 2 }, kind: "Cbor" },
|
|
1085
|
+
],
|
|
1086
|
+
});
|
|
1087
|
+
builder.updateAssertion("org.test.json", () => ({ value: 11 }));
|
|
1088
|
+
builder.updateAssertion("org.test.cbor", () => ({ value: 22 }));
|
|
1089
|
+
expect(builder.getManifestDefinition().assertions).toEqual(expect.arrayContaining([
|
|
1090
|
+
{ label: "org.test.json", data: { value: 11 }, kind: "Json" },
|
|
1091
|
+
{ label: "org.test.cbor", data: { value: 22 }, kind: "Cbor" },
|
|
1092
|
+
]));
|
|
1093
|
+
const dest = { path: path.join(tempDir, "updated_assertion_kinds.jpg") };
|
|
1094
|
+
const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
|
|
1095
|
+
builder.sign(signer, source, dest);
|
|
1096
|
+
const reader = await Reader.fromAsset(dest);
|
|
1097
|
+
expect(reader).not.toBeNull();
|
|
1098
|
+
const assertions = reader.getActive().assertions;
|
|
1099
|
+
expect(assertions).toEqual(expect.arrayContaining([
|
|
1100
|
+
expect.objectContaining({
|
|
1101
|
+
label: "org.test.json",
|
|
1102
|
+
data: { value: 11 },
|
|
1103
|
+
}),
|
|
1104
|
+
expect.objectContaining({
|
|
1105
|
+
label: "org.test.cbor",
|
|
1106
|
+
data: { value: 22 },
|
|
1107
|
+
}),
|
|
1108
|
+
]));
|
|
1109
|
+
});
|
|
1110
|
+
it("updateAssertion skips null and undefined results without dropping other updates", () => {
|
|
1111
|
+
const builder = Builder.withJson({
|
|
1112
|
+
...actionsManifest(),
|
|
1113
|
+
assertions: [
|
|
1114
|
+
{ label: "org.test.note", data: { value: 1 }, kind: "Json" },
|
|
1115
|
+
{ label: "org.test.note", data: { value: 2 }, kind: "Json" },
|
|
1116
|
+
{ label: "org.test.note", data: { value: 3 }, kind: "Json" },
|
|
1117
|
+
],
|
|
1118
|
+
});
|
|
1119
|
+
builder.updateAssertion("org.test.note", (data) => {
|
|
1120
|
+
const value = data.value;
|
|
1121
|
+
return value === 1 ? null : value === 2 ? undefined : { value: 33 };
|
|
1122
|
+
});
|
|
1123
|
+
expect(builder.getManifestDefinition().assertions.map((a) => a.data)).toEqual([{ value: 1 }, { value: 2 }, { value: 33 }]);
|
|
1124
|
+
});
|
|
1125
|
+
it("updateAssertion is atomic on callback failure and ignores missing labels", () => {
|
|
1126
|
+
const builder = Builder.withJson({
|
|
1127
|
+
...actionsManifest(),
|
|
1128
|
+
assertions: [
|
|
1129
|
+
{ label: "org.test.note", data: { value: 1 } },
|
|
1130
|
+
{ label: "org.test.note", data: { value: 2 } },
|
|
1131
|
+
],
|
|
1132
|
+
});
|
|
1133
|
+
const before = builder.getManifestDefinition();
|
|
1134
|
+
expect(() => builder.updateAssertion("org.test.note", (data) => {
|
|
1135
|
+
if (data.value === 2) {
|
|
1136
|
+
throw new Error("transform failed");
|
|
1137
|
+
}
|
|
1138
|
+
return { value: 10 };
|
|
1139
|
+
})).toThrow("transform failed");
|
|
1140
|
+
expect(builder.getManifestDefinition()).toEqual(before);
|
|
1141
|
+
expect(() => builder.updateAssertion("org.test.note", (data) => data.value === 2
|
|
1142
|
+
? () => undefined
|
|
1143
|
+
: { value: 10 })).toThrow();
|
|
1144
|
+
expect(builder.getManifestDefinition()).toEqual(before);
|
|
1145
|
+
let calls = 0;
|
|
1146
|
+
builder.updateAssertion("org.test.missing", () => {
|
|
1147
|
+
calls++;
|
|
1148
|
+
return {};
|
|
1149
|
+
});
|
|
1150
|
+
expect(calls).toBe(0);
|
|
1151
|
+
});
|
|
1045
1152
|
it("updateActions patches a parameter on an existing action", () => {
|
|
1046
1153
|
const builder = Builder.withJson(actionsManifest());
|
|
1047
1154
|
builder.updateActions((actions) => actions.map((action) => action.action === "c2pa.created"
|
|
@@ -58,7 +58,7 @@ export class CallbackCredentialHolder {
|
|
|
58
58
|
return new CallbackCredentialHolder(credentialHolder);
|
|
59
59
|
}
|
|
60
60
|
async sign(payload) {
|
|
61
|
-
return getNeonBinary().
|
|
61
|
+
return getNeonBinary().callbackCredentialHolderSignPayload.call(this.callbackCredentialHolder, payload);
|
|
62
62
|
}
|
|
63
63
|
reserveSize() {
|
|
64
64
|
return getNeonBinary().callbackCredentialHolderReserveSize.call(this.callbackCredentialHolder);
|
|
@@ -140,3 +140,104 @@ describe("IdentityAssertionBuilder", () => {
|
|
|
140
140
|
});
|
|
141
141
|
});
|
|
142
142
|
});
|
|
143
|
+
describe("CallbackCredentialHolder accessors", () => {
|
|
144
|
+
it("returns reserveSize and sigType set on the constructor", async () => {
|
|
145
|
+
const { CallbackCredentialHolder } = await import("./IdentityAssertion");
|
|
146
|
+
const holder = CallbackCredentialHolder.newCallbackCredentialHolder(10000, "cawg.x509.cose", async () => Buffer.alloc(0));
|
|
147
|
+
expect(holder.reserveSize()).toBe(10000);
|
|
148
|
+
expect(holder.sigType()).toBe("cawg.x509.cose");
|
|
149
|
+
});
|
|
150
|
+
it("signs a payload through the callback set", async () => {
|
|
151
|
+
const { CallbackCredentialHolder } = await import("./IdentityAssertion");
|
|
152
|
+
const seen = [];
|
|
153
|
+
const holder = CallbackCredentialHolder.newCallbackCredentialHolder(10000, "cawg.x509.cose", async (payload) => {
|
|
154
|
+
seen.push(payload);
|
|
155
|
+
return Buffer.from([1, 2, 3]);
|
|
156
|
+
});
|
|
157
|
+
const signature = await holder.sign({
|
|
158
|
+
referencedAssertions: [
|
|
159
|
+
{
|
|
160
|
+
url: "self#jumbf=c2pa.assertions/cawg.training-mining",
|
|
161
|
+
hash: new Uint8Array([9, 8, 7]),
|
|
162
|
+
alg: "sha256",
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
sigType: "cawg.x509.cose",
|
|
166
|
+
roles: ["cawg.creator"],
|
|
167
|
+
});
|
|
168
|
+
expect(signature).toEqual(Buffer.from([1, 2, 3]));
|
|
169
|
+
expect(seen).toHaveLength(1);
|
|
170
|
+
const payload = seen[0];
|
|
171
|
+
expect(payload.sigType).toBe("cawg.x509.cose");
|
|
172
|
+
expect(payload.roles).toEqual(["cawg.creator"]);
|
|
173
|
+
expect(payload.referencedAssertions).toHaveLength(1);
|
|
174
|
+
expect(payload.referencedAssertions[0].url).toBe("self#jumbf=c2pa.assertions/cawg.training-mining");
|
|
175
|
+
expect(Buffer.from(payload.referencedAssertions[0].hash)).toEqual(Buffer.from([9, 8, 7]));
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
describe("handles reserveSize", () => {
|
|
179
|
+
async function signWithReserveSize(reserveSize) {
|
|
180
|
+
const { CallbackSigner } = await import("./Signer");
|
|
181
|
+
const { Builder } = await import("./Builder");
|
|
182
|
+
const { IdentityAssertionBuilder, IdentityAssertionSigner, CallbackCredentialHolder, } = await import("./IdentityAssertion");
|
|
183
|
+
const c2paPrivateKey = await fs.readFile("./tests/fixtures/certs/es256.pem");
|
|
184
|
+
const c2paPublicKey = await fs.readFile("./tests/fixtures/certs/es256.pub");
|
|
185
|
+
const c2paTestSigner = new TestSigner(c2paPrivateKey);
|
|
186
|
+
const c2paSigner = CallbackSigner.newSigner({
|
|
187
|
+
alg: "es256",
|
|
188
|
+
certs: [c2paPublicKey],
|
|
189
|
+
reserveSize: 10000,
|
|
190
|
+
tsaUrl: undefined,
|
|
191
|
+
tsaHeaders: undefined,
|
|
192
|
+
tsaBody: undefined,
|
|
193
|
+
directCoseHandling: true,
|
|
194
|
+
}, c2paTestSigner.sign);
|
|
195
|
+
const cawgTestSigner = new TestCawgSigner(c2paTestSigner);
|
|
196
|
+
const cawgSigner = CallbackCredentialHolder.newCallbackCredentialHolder(reserveSize, "cawg.x509.cose", cawgTestSigner.sign);
|
|
197
|
+
const builder = Builder.withJson({
|
|
198
|
+
claim_generator_info: [{ name: "c2pa_test", version: "2.0.0" }],
|
|
199
|
+
title: "Test_Manifest",
|
|
200
|
+
format: "image/jpeg",
|
|
201
|
+
instance_id: "1234",
|
|
202
|
+
assertions: [
|
|
203
|
+
{
|
|
204
|
+
label: "c2pa.actions.v2",
|
|
205
|
+
data: {
|
|
206
|
+
actions: [
|
|
207
|
+
{
|
|
208
|
+
action: "c2pa.created",
|
|
209
|
+
digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
},
|
|
213
|
+
kind: "Json",
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
label: "cawg.training-mining",
|
|
217
|
+
data: {
|
|
218
|
+
metadata: {
|
|
219
|
+
"cawg.ai_inference": { use: "notAllowed" },
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
});
|
|
225
|
+
const iaSigner = IdentityAssertionSigner.new(c2paSigner.getHandle());
|
|
226
|
+
const iab = await IdentityAssertionBuilder.identityBuilderForCredentialHolder(cawgSigner);
|
|
227
|
+
iab.addReferencedAssertions(["cawg.training-mining"]);
|
|
228
|
+
iaSigner.addIdentityAssertion(iab);
|
|
229
|
+
return builder.signAsync(iaSigner, {
|
|
230
|
+
buffer: await fs.readFile("./tests/fixtures/CA.jpg"),
|
|
231
|
+
mimeType: "image/jpeg",
|
|
232
|
+
}, { buffer: null });
|
|
233
|
+
}
|
|
234
|
+
it("rejects a reserveSize too small for the identity assertion", async () => {
|
|
235
|
+
await expect(signWithReserveSize(10)).rejects.toThrow(/exceeds the planned size/i);
|
|
236
|
+
});
|
|
237
|
+
it("rejects a reserveSize overflowing into padding", async () => {
|
|
238
|
+
await expect(signWithReserveSize(340)).rejects.toThrow(/reserveSize/i);
|
|
239
|
+
});
|
|
240
|
+
it("signs with a large reserveSize", async () => {
|
|
241
|
+
await expect(signWithReserveSize(10000)).resolves.toBeDefined();
|
|
242
|
+
});
|
|
243
|
+
});
|
package/dist/Reader.spec.js
CHANGED
|
@@ -113,6 +113,14 @@ describe("Reader", () => {
|
|
|
113
113
|
expect(json.manifests).toEqual(manifestStore.manifests);
|
|
114
114
|
expect(json.active_manifest).toEqual(manifestStore.active_manifest);
|
|
115
115
|
});
|
|
116
|
+
it("should read from an ArrayBuffer with no mimeType by detecting the format from its bytes", async () => {
|
|
117
|
+
const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
|
|
118
|
+
const reader = await Reader.fromAsset({ buffer });
|
|
119
|
+
expect(reader).not.toBeNull();
|
|
120
|
+
const json = reader.json();
|
|
121
|
+
expect(json.manifests).toEqual(manifestStore.manifests);
|
|
122
|
+
expect(json.active_manifest).toEqual(manifestStore.active_manifest);
|
|
123
|
+
});
|
|
116
124
|
it("should read from a file", async () => {
|
|
117
125
|
const reader = await Reader.fromAsset({
|
|
118
126
|
path: "./tests/fixtures/CA.jpg",
|
|
@@ -122,6 +130,15 @@ describe("Reader", () => {
|
|
|
122
130
|
expect(json.manifests).toEqual(manifestStore.manifests);
|
|
123
131
|
expect(json.active_manifest).toEqual(manifestStore.active_manifest);
|
|
124
132
|
});
|
|
133
|
+
it("should read from a file with an unrecognized extension by detecting the format from its bytes", async () => {
|
|
134
|
+
const extensionlessPath = path.join(tempDir, "no-extension");
|
|
135
|
+
await fs.copyFile("./tests/fixtures/CA.jpg", extensionlessPath);
|
|
136
|
+
const reader = await Reader.fromAsset({ path: extensionlessPath });
|
|
137
|
+
expect(reader).not.toBeNull();
|
|
138
|
+
const json = reader.json();
|
|
139
|
+
expect(json.manifests).toEqual(manifestStore.manifests);
|
|
140
|
+
expect(json.active_manifest).toEqual(manifestStore.active_manifest);
|
|
141
|
+
});
|
|
125
142
|
it("should return null for a file without C2PA data", async () => {
|
|
126
143
|
const reader = await Reader.fromAsset({
|
|
127
144
|
path: "./tests/fixtures/A.jpg",
|
package/dist/index.node
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/dist/index.node
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 52040488 bytes
|
|
4
|
+
sha256: 5f413ef149badf60fce3372fcd57b3d9a11683aaa13e15de7bd24257f171a125
|
package/dist/types/Builder.d.ts
CHANGED
|
@@ -65,5 +65,6 @@ export declare class Builder implements BuilderInterface {
|
|
|
65
65
|
filterIngredients(rescue: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
|
|
66
66
|
filterActionsAndIngredients(keepAction: (action: Action) => boolean, rescueIngredient: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
|
|
67
67
|
updateActions(transform: (actions: Action[]) => Action[]): void;
|
|
68
|
+
updateAssertion(label: string, transform: (data: unknown) => unknown): void;
|
|
68
69
|
getHandle(): NeonBuilderHandle;
|
|
69
70
|
}
|
package/dist/types/types.d.ts
CHANGED
|
@@ -62,8 +62,14 @@ export type TrustmarkVariant =
|
|
|
62
62
|
export interface SourceBufferAsset {
|
|
63
63
|
// A buffer containing the asset data
|
|
64
64
|
buffer: Buffer;
|
|
65
|
-
// The MIME type of the asset, for instance `image/jpeg
|
|
66
|
-
|
|
65
|
+
// The MIME type of the asset, for instance `image/jpeg`.
|
|
66
|
+
//
|
|
67
|
+
// Always supply this when it's known. It's only optional for Reader operations, which fall
|
|
68
|
+
// back to detecting the format from the asset's bytes when it's omitted. Only rely on this
|
|
69
|
+
// when the MIME type is truly unknown.
|
|
70
|
+
//
|
|
71
|
+
// Builder operations (e.g. signing) require it and will throw if it's omitted.
|
|
72
|
+
mimeType?: string;
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
/**
|
|
@@ -80,8 +86,13 @@ export interface DestinationBufferAsset {
|
|
|
80
86
|
export interface FileAsset {
|
|
81
87
|
// The path to the asset
|
|
82
88
|
path: string;
|
|
83
|
-
// The
|
|
84
|
-
//
|
|
89
|
+
// The MIME type of the asset, for instance `image/jpeg`.
|
|
90
|
+
//
|
|
91
|
+
// Always supply this when it's known. It's only optional for Reader operations, which fall
|
|
92
|
+
// back to detecting the format from the asset's bytes when it's omitted. Only rely on this
|
|
93
|
+
// when the MIME type is truly unknown.
|
|
94
|
+
//
|
|
95
|
+
// Builder operations (e.g. signing) require it and will throw if it's omitted.
|
|
85
96
|
mimeType?: string;
|
|
86
97
|
}
|
|
87
98
|
|
|
@@ -410,6 +421,19 @@ export interface BuilderInterface {
|
|
|
410
421
|
*/
|
|
411
422
|
updateActions(transform: (actions: Action[]) => Action[]): void;
|
|
412
423
|
|
|
424
|
+
/**
|
|
425
|
+
* Replaces the data of every assertion with an exact matching label.
|
|
426
|
+
* `transform` runs once per matching assertion in manifest order. Other assertion
|
|
427
|
+
* fields and positions are preserved. A missing label is a no-op.
|
|
428
|
+
* Returning null or undefined leaves that assertion unchanged.
|
|
429
|
+
* The replacement data must be JSON-serializable and may fail validation at signing time.
|
|
430
|
+
* The callback must not call back into this builder.
|
|
431
|
+
*
|
|
432
|
+
* @param label The exact assertion label to update.
|
|
433
|
+
* @param transform Receives the current data and returns its replacement.
|
|
434
|
+
*/
|
|
435
|
+
updateAssertion(label: string, transform: (data: unknown) => unknown): void;
|
|
436
|
+
|
|
413
437
|
/**
|
|
414
438
|
* Get the internal handle for use with Neon bindings
|
|
415
439
|
*/
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"url": "git+https://github.com/contentauth/c2pa-js.git",
|
|
6
6
|
"directory": "packages/c2pa-node"
|
|
7
7
|
},
|
|
8
|
-
"version": "0.9.
|
|
8
|
+
"version": "0.9.9",
|
|
9
9
|
"description": "Node.js bindings for C2PA",
|
|
10
10
|
"main": "dist/index.js",
|
|
11
11
|
"type": "module",
|
|
@@ -64,8 +64,8 @@
|
|
|
64
64
|
"pkg-dir": "^8.0.0",
|
|
65
65
|
"pretty-bytes": "^6.1.1",
|
|
66
66
|
"unzipper": "^0.10.14",
|
|
67
|
-
"@contentauth/c2pa-types": "0.7.
|
|
68
|
-
"@contentauth/c2pa-utilities": "0.3.
|
|
67
|
+
"@contentauth/c2pa-types": "0.7.5",
|
|
68
|
+
"@contentauth/c2pa-utilities": "0.3.1"
|
|
69
69
|
},
|
|
70
70
|
"nx": {
|
|
71
71
|
"tags": [
|
package/src/asset.rs
CHANGED
|
@@ -31,19 +31,27 @@ impl NeonWriteStreamTrait for Cursor<Vec<u8>> {}
|
|
|
31
31
|
impl NeonWriteStreamTrait for File {}
|
|
32
32
|
|
|
33
33
|
pub enum Asset {
|
|
34
|
-
SourceBuffer(Vec<u8>, String),
|
|
34
|
+
SourceBuffer(Vec<u8>, Option<String>),
|
|
35
35
|
File(String, Option<String>),
|
|
36
36
|
DestinationBuffer(Vec<u8>),
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
impl Asset {
|
|
40
|
+
/// The asset's MIME type, if known.
|
|
41
|
+
///
|
|
42
|
+
/// For a `File`, an omitted MIME type falls back to a guess from the path's extension.
|
|
43
|
+
/// Returns `None` when the MIME type isn't supplied and can't be inferred; callers reading
|
|
44
|
+
/// an asset (as opposed to signing one) can fall back to an empty format string and let the
|
|
45
|
+
/// native library detect the format from the asset's bytes.
|
|
46
|
+
///
|
|
47
|
+
/// Callers should supply the real MIME type whenever it's known and only omit it when there
|
|
48
|
+
/// is no way to determine it.
|
|
40
49
|
pub fn mime_type(&self) -> Option<String> {
|
|
41
50
|
match self {
|
|
42
|
-
Asset::SourceBuffer(_, mime_type) =>
|
|
43
|
-
Asset::File(path, mime_type) =>
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
},
|
|
51
|
+
Asset::SourceBuffer(_, mime_type) => mime_type.clone(),
|
|
52
|
+
Asset::File(path, mime_type) => mime_type
|
|
53
|
+
.clone()
|
|
54
|
+
.or_else(|| format_from_path(Path::new(&path))),
|
|
47
55
|
_ => None,
|
|
48
56
|
}
|
|
49
57
|
}
|
|
@@ -105,12 +113,9 @@ pub fn parse_asset(cx: &mut FunctionContext, obj: Handle<JsObject>) -> NeonResul
|
|
|
105
113
|
None
|
|
106
114
|
};
|
|
107
115
|
|
|
108
|
-
match (buffer,
|
|
109
|
-
(Some(buffer),
|
|
110
|
-
(None,
|
|
111
|
-
(None,
|
|
112
|
-
_ => cx.throw_error(
|
|
113
|
-
"Invalid asset data passed. Must contain either a buffer and mimeType or a path.",
|
|
114
|
-
),
|
|
116
|
+
match (buffer, path) {
|
|
117
|
+
(Some(buffer), _) => Ok(Asset::SourceBuffer(buffer, mime_type)),
|
|
118
|
+
(None, Some(path)) => Ok(Asset::File(path, mime_type)),
|
|
119
|
+
(None, None) => Ok(Asset::DestinationBuffer(Vec::new())),
|
|
115
120
|
}
|
|
116
121
|
}
|
package/src/lib.rs
CHANGED
|
@@ -101,6 +101,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
|
|
|
101
101
|
"builderUpdateActions",
|
|
102
102
|
neon_builder::NeonBuilder::update_actions,
|
|
103
103
|
)?;
|
|
104
|
+
cx.export_function(
|
|
105
|
+
"builderUpdateAssertion",
|
|
106
|
+
neon_builder::NeonBuilder::update_assertion,
|
|
107
|
+
)?;
|
|
104
108
|
|
|
105
109
|
// Reader
|
|
106
110
|
cx.export_function("readerNew", neon_reader::NeonReader::new)?;
|
|
@@ -186,6 +190,18 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
|
|
|
186
190
|
"newCallbackCredentialHolder",
|
|
187
191
|
neon_credential_holder::NeonCallbackCredentialHolder::from_js,
|
|
188
192
|
)?;
|
|
193
|
+
cx.export_function(
|
|
194
|
+
"callbackCredentialHolderSignPayload",
|
|
195
|
+
neon_credential_holder::NeonCallbackCredentialHolder::sign_payload,
|
|
196
|
+
)?;
|
|
197
|
+
cx.export_function(
|
|
198
|
+
"callbackCredentialHolderReserveSize",
|
|
199
|
+
neon_credential_holder::NeonCallbackCredentialHolder::reserve_size_js,
|
|
200
|
+
)?;
|
|
201
|
+
cx.export_function(
|
|
202
|
+
"callbackCredentialHolderSigType",
|
|
203
|
+
neon_credential_holder::NeonCallbackCredentialHolder::sig_type_js,
|
|
204
|
+
)?;
|
|
189
205
|
|
|
190
206
|
// Trustmark
|
|
191
207
|
cx.export_function(
|
package/src/neon_builder.rs
CHANGED
|
@@ -675,6 +675,53 @@ impl NeonBuilder {
|
|
|
675
675
|
Ok(cx.undefined())
|
|
676
676
|
}
|
|
677
677
|
|
|
678
|
+
/// Replaces the data of every assertion with an exact matching label.
|
|
679
|
+
/// A null or undefined result leaves that assertion unchanged.
|
|
680
|
+
/// The builder is left unchanged if any transform throws or returns invalid data.
|
|
681
|
+
/// The callback must not call back into this builder while its lock is held.
|
|
682
|
+
pub fn update_assertion(mut cx: FunctionContext) -> JsResult<JsUndefined> {
|
|
683
|
+
let rt = runtime();
|
|
684
|
+
let this = cx.this::<JsBox<Self>>()?;
|
|
685
|
+
let label = cx.argument::<JsString>(0)?.value(&mut cx);
|
|
686
|
+
let transform = cx.argument::<JsFunction>(1)?;
|
|
687
|
+
let mut builder = rt.block_on(async { this.builder.lock().await });
|
|
688
|
+
|
|
689
|
+
let positions: Vec<usize> = builder
|
|
690
|
+
.definition
|
|
691
|
+
.assertions
|
|
692
|
+
.iter()
|
|
693
|
+
.enumerate()
|
|
694
|
+
.filter(|(_, assertion)| assertion.label == label)
|
|
695
|
+
.map(|(index, _)| index)
|
|
696
|
+
.collect();
|
|
697
|
+
|
|
698
|
+
let mut replacements = Vec::with_capacity(positions.len());
|
|
699
|
+
for &position in &positions {
|
|
700
|
+
let data = serde_json::to_value(&builder.definition.assertions[position].data)
|
|
701
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
702
|
+
let js_data = neon_serde4::to_value(&mut cx, &data)
|
|
703
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
704
|
+
let undefined = cx.undefined();
|
|
705
|
+
let result = transform.call(&mut cx, undefined, [js_data])?;
|
|
706
|
+
if result.is_a::<JsNull, _>(&mut cx) || result.is_a::<JsUndefined, _>(&mut cx) {
|
|
707
|
+
replacements.push(None);
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
let replacement: serde_json::Value = neon_serde4::from_value(&mut cx, result)
|
|
711
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
712
|
+
let replacement = serde_json::from_value(replacement)
|
|
713
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
714
|
+
replacements.push(Some(replacement));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
for (position, replacement) in positions.into_iter().zip(replacements) {
|
|
718
|
+
if let Some(replacement) = replacement {
|
|
719
|
+
builder.definition.assertions[position].data = replacement;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
Ok(cx.undefined())
|
|
723
|
+
}
|
|
724
|
+
|
|
678
725
|
/// Replaces the actions in the `c2pa.actions`/`c2pa.actions.v2` assertions.
|
|
679
726
|
/// `softwareAgents`/`allActionsIncluded`/`templates`/`metadata` are preserved as-is.
|
|
680
727
|
///
|
|
@@ -11,16 +11,72 @@
|
|
|
11
11
|
// specific language governing permissions and limitations under
|
|
12
12
|
// each license.
|
|
13
13
|
|
|
14
|
+
use std::ops::Deref;
|
|
14
15
|
use std::sync::Arc;
|
|
15
16
|
|
|
16
17
|
use async_trait::async_trait;
|
|
17
18
|
use c2pa::identity::builder::{AsyncCredentialHolder, IdentityBuilderError};
|
|
18
19
|
use c2pa::identity::SignerPayload;
|
|
20
|
+
use c2pa::HashedUri;
|
|
19
21
|
use neon::prelude::*;
|
|
20
22
|
use neon::types::buffer::TypedArray;
|
|
21
23
|
use neon_serde4;
|
|
24
|
+
use serde::{Deserialize, Serialize};
|
|
22
25
|
use tokio::sync::oneshot;
|
|
23
26
|
|
|
27
|
+
use crate::runtime::runtime;
|
|
28
|
+
|
|
29
|
+
#[derive(Deserialize, Serialize)]
|
|
30
|
+
#[serde(rename_all = "camelCase")]
|
|
31
|
+
struct JsSignerPayload {
|
|
32
|
+
referenced_assertions: Vec<JsHashedUri>,
|
|
33
|
+
sig_type: String,
|
|
34
|
+
#[serde(default)]
|
|
35
|
+
roles: Vec<String>,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
#[derive(Deserialize, Serialize)]
|
|
39
|
+
#[serde(rename_all = "camelCase")]
|
|
40
|
+
struct JsHashedUri {
|
|
41
|
+
url: String,
|
|
42
|
+
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
43
|
+
alg: Option<String>,
|
|
44
|
+
#[serde(with = "serde_bytes")]
|
|
45
|
+
hash: Vec<u8>,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
impl From<&SignerPayload> for JsSignerPayload {
|
|
49
|
+
fn from(payload: &SignerPayload) -> Self {
|
|
50
|
+
JsSignerPayload {
|
|
51
|
+
referenced_assertions: payload
|
|
52
|
+
.referenced_assertions
|
|
53
|
+
.iter()
|
|
54
|
+
.map(|uri| JsHashedUri {
|
|
55
|
+
url: uri.url(),
|
|
56
|
+
alg: uri.alg(),
|
|
57
|
+
hash: uri.hash(),
|
|
58
|
+
})
|
|
59
|
+
.collect(),
|
|
60
|
+
sig_type: payload.sig_type.clone(),
|
|
61
|
+
roles: payload.roles.clone(),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
impl From<JsSignerPayload> for SignerPayload {
|
|
67
|
+
fn from(payload: JsSignerPayload) -> Self {
|
|
68
|
+
SignerPayload {
|
|
69
|
+
referenced_assertions: payload
|
|
70
|
+
.referenced_assertions
|
|
71
|
+
.into_iter()
|
|
72
|
+
.map(|uri| HashedUri::new(uri.url, uri.alg, &uri.hash))
|
|
73
|
+
.collect(),
|
|
74
|
+
sig_type: payload.sig_type,
|
|
75
|
+
roles: payload.roles,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
24
80
|
/// NeonCallbackCredentialHolder allows JS to asynchronously sign a SignerPayload.
|
|
25
81
|
#[derive(Clone)]
|
|
26
82
|
pub struct NeonCallbackCredentialHolder {
|
|
@@ -58,6 +114,49 @@ impl NeonCallbackCredentialHolder {
|
|
|
58
114
|
sig_type,
|
|
59
115
|
)))
|
|
60
116
|
}
|
|
117
|
+
|
|
118
|
+
/// JS accessor for the reserve size of this holder instance.
|
|
119
|
+
pub fn reserve_size_js(mut cx: FunctionContext) -> JsResult<JsNumber> {
|
|
120
|
+
let this = cx.this::<JsBox<Self>>()?;
|
|
121
|
+
let reserve_size = this.reserve_size as f64;
|
|
122
|
+
Ok(cx.number(reserve_size))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/// JS accessor for the signature type of this holder instance.
|
|
126
|
+
pub fn sig_type_js(mut cx: FunctionContext) -> JsResult<JsString> {
|
|
127
|
+
let this = cx.this::<JsBox<Self>>()?;
|
|
128
|
+
let sig_type = this.sig_type.clone();
|
|
129
|
+
Ok(cx.string(sig_type))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/// Sign a `SignerPayload` supplied from JS,
|
|
133
|
+
/// resolving to the signature bytes.
|
|
134
|
+
pub fn sign_payload(mut cx: FunctionContext) -> JsResult<JsPromise> {
|
|
135
|
+
let payload_arg = cx.argument::<JsValue>(0)?;
|
|
136
|
+
let js_payload: JsSignerPayload = match neon_serde4::from_value(&mut cx, payload_arg) {
|
|
137
|
+
Ok(payload) => payload,
|
|
138
|
+
Err(err) => return cx.throw_error(err.to_string()),
|
|
139
|
+
};
|
|
140
|
+
let signer_payload: SignerPayload = js_payload.into();
|
|
141
|
+
|
|
142
|
+
let holder_handle = cx.this::<JsBox<Self>>()?;
|
|
143
|
+
let holder_ref: &Self = holder_handle.deref();
|
|
144
|
+
let holder = holder_ref.clone();
|
|
145
|
+
let channel = cx.channel();
|
|
146
|
+
let (deferred, promise) = cx.promise();
|
|
147
|
+
let rt = runtime();
|
|
148
|
+
|
|
149
|
+
// The credential holder's `sign` awaits a JS callback.
|
|
150
|
+
rt.spawn(async move {
|
|
151
|
+
let result = holder.sign(&signer_payload).await;
|
|
152
|
+
deferred.settle_with(&channel, move |mut cx| match result {
|
|
153
|
+
Ok(bytes) => Ok(JsBuffer::from_slice(&mut cx, &bytes)?),
|
|
154
|
+
Err(err) => cx.throw_error(err.to_string()),
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
Ok(promise)
|
|
159
|
+
}
|
|
61
160
|
}
|
|
62
161
|
|
|
63
162
|
/// # Safety
|
|
@@ -102,12 +201,10 @@ impl AsyncCredentialHolder for NeonCallbackCredentialHolder {
|
|
|
102
201
|
let callback = self.callback.clone();
|
|
103
202
|
let channel = self.channel.clone();
|
|
104
203
|
|
|
105
|
-
|
|
106
|
-
let payload = signer_payload.clone();
|
|
204
|
+
let payload = JsSignerPayload::from(signer_payload);
|
|
107
205
|
|
|
108
206
|
channel
|
|
109
207
|
.try_send(move |mut cx| {
|
|
110
|
-
// Convert Rust SignerPayload to JS object
|
|
111
208
|
let js_payload = match neon_serde4::to_value(&mut cx, &payload) {
|
|
112
209
|
Ok(val) => val,
|
|
113
210
|
Err(err) => return cx.throw_error(err.to_string()),
|
|
@@ -192,7 +192,7 @@ fn finalize_identity_assertion(
|
|
|
192
192
|
return Err(c2pa::Error::BadParam(format!("Serialized assertion is {len} bytes, which exceeds the planned size of {assertion_size} bytes", len = assertion_cbor.len())));
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
ia.pad1 = vec![0u8; assertion_size
|
|
195
|
+
ia.pad1 = vec![0u8; pad_len(assertion_size, assertion_cbor.len(), PAD1_CBOR_OVERHEAD)?];
|
|
196
196
|
|
|
197
197
|
assertion_cbor.clear();
|
|
198
198
|
c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
|
|
@@ -200,14 +200,46 @@ fn finalize_identity_assertion(
|
|
|
200
200
|
|
|
201
201
|
ia.pad2 = Some(ByteBuf::from(vec![
|
|
202
202
|
0u8;
|
|
203
|
-
|
|
203
|
+
pad_len(
|
|
204
|
+
assertion_size,
|
|
205
|
+
assertion_cbor.len(),
|
|
206
|
+
PAD2_CBOR_OVERHEAD
|
|
207
|
+
)?
|
|
204
208
|
]));
|
|
205
209
|
|
|
206
210
|
assertion_cbor.clear();
|
|
207
211
|
c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
|
|
208
212
|
.map_err(|e| c2pa::Error::BadParam(e.to_string()))?;
|
|
209
|
-
|
|
213
|
+
|
|
214
|
+
if assertion_size != assertion_cbor.len() {
|
|
215
|
+
return Err(c2pa::Error::BadParam(format!(
|
|
216
|
+
"Padded assertion is {len} bytes, different from expected {assertion_size} bytes",
|
|
217
|
+
len = assertion_cbor.len()
|
|
218
|
+
)));
|
|
219
|
+
}
|
|
210
220
|
}
|
|
211
221
|
|
|
212
222
|
Ok(DynamicAssertionContent::Cbor(assertion_cbor))
|
|
213
223
|
}
|
|
224
|
+
|
|
225
|
+
/// CBOR framing cost of writing the `pad1` byte string into the assertion.
|
|
226
|
+
const PAD1_CBOR_OVERHEAD: usize = 15;
|
|
227
|
+
|
|
228
|
+
/// CBOR framing cost of writing the `pad2` byte string into the assertion.
|
|
229
|
+
const PAD2_CBOR_OVERHEAD: usize = 6;
|
|
230
|
+
|
|
231
|
+
/// Size of a padding field that brings the encoded assertion up to
|
|
232
|
+
/// `assertion_size`.
|
|
233
|
+
/// Returns a `BadParam` error when the caller's reserved size
|
|
234
|
+
/// cannot fit in the CBOR framing.
|
|
235
|
+
fn pad_len(assertion_size: usize, encoded_len: usize, overhead: usize) -> c2pa::Result<usize> {
|
|
236
|
+
assertion_size
|
|
237
|
+
.checked_sub(encoded_len)
|
|
238
|
+
.and_then(|remaining| remaining.checked_sub(overhead))
|
|
239
|
+
.ok_or_else(|| {
|
|
240
|
+
c2pa::Error::BadParam(format!(
|
|
241
|
+
"Identity assertion reserveSize {assertion_size} bytes needs at least {min} bytes",
|
|
242
|
+
min = encoded_len + overhead
|
|
243
|
+
))
|
|
244
|
+
})
|
|
245
|
+
}
|
|
@@ -16,11 +16,7 @@ use std::sync::RwLock;
|
|
|
16
16
|
|
|
17
17
|
use async_trait::async_trait;
|
|
18
18
|
use c2pa::{
|
|
19
|
-
crypto::
|
|
20
|
-
raw_signature::{AsyncRawSigner, RawSignerError},
|
|
21
|
-
time_stamp::AsyncTimeStampProvider,
|
|
22
|
-
},
|
|
23
|
-
dynamic_assertion::AsyncDynamicAssertion,
|
|
19
|
+
crypto::time_stamp::AsyncTimeStampProvider, dynamic_assertion::AsyncDynamicAssertion,
|
|
24
20
|
AsyncSigner, SigningAlg,
|
|
25
21
|
};
|
|
26
22
|
use neon::prelude::FunctionContext;
|
|
@@ -87,37 +83,12 @@ impl Clone for NeonIdentityAssertionSigner {
|
|
|
87
83
|
/// - `Sync`: Allows the type to be shared between threads
|
|
88
84
|
///
|
|
89
85
|
/// The type needs these capabilities because it:
|
|
90
|
-
/// - Implements `AsyncSigner`
|
|
86
|
+
/// - Implements the `AsyncSigner` trait for asynchronous signing operations
|
|
91
87
|
/// - Is used in the `identity_sign_async` function which performs asynchronous operations
|
|
92
88
|
/// - Is part of a Node.js binding where async operations are common
|
|
93
89
|
unsafe impl Send for NeonIdentityAssertionSigner {}
|
|
94
90
|
unsafe impl Sync for NeonIdentityAssertionSigner {}
|
|
95
91
|
|
|
96
|
-
#[async_trait]
|
|
97
|
-
impl AsyncRawSigner for NeonIdentityAssertionSigner {
|
|
98
|
-
async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, RawSignerError> {
|
|
99
|
-
let signer = self.signer.read().unwrap().clone();
|
|
100
|
-
AsyncRawSigner::sign(&signer, data).await
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
fn alg(&self) -> SigningAlg {
|
|
104
|
-
AsyncRawSigner::alg(&*self.signer.read().unwrap())
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
|
|
108
|
-
self.signer.read().unwrap().cert_chain()
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
fn reserve_size(&self) -> usize {
|
|
112
|
-
AsyncRawSigner::reserve_size(&*self.signer.read().unwrap())
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async fn ocsp_response(&self) -> Option<Vec<u8>> {
|
|
116
|
-
let signer = self.signer.read().unwrap().clone();
|
|
117
|
-
AsyncRawSigner::ocsp_response(&signer).await
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
92
|
impl AsyncTimeStampProvider for NeonIdentityAssertionSigner {
|
|
122
93
|
fn time_stamp_service_url(&self) -> Option<String> {
|
|
123
94
|
self.signer.read().unwrap().time_stamp_service_url()
|
|
@@ -140,11 +111,7 @@ impl AsyncSigner for NeonIdentityAssertionSigner {
|
|
|
140
111
|
}
|
|
141
112
|
|
|
142
113
|
fn certs(&self) -> Result<Vec<Vec<u8>>, c2pa::Error> {
|
|
143
|
-
self.signer
|
|
144
|
-
.read()
|
|
145
|
-
.unwrap()
|
|
146
|
-
.cert_chain()
|
|
147
|
-
.map_err(|e| e.into())
|
|
114
|
+
c2pa::AsyncSigner::certs(&*self.signer.read().unwrap())
|
|
148
115
|
}
|
|
149
116
|
|
|
150
117
|
fn reserve_size(&self) -> usize {
|
|
@@ -173,10 +140,6 @@ impl AsyncSigner for NeonIdentityAssertionSigner {
|
|
|
173
140
|
c2pa::AsyncSigner::send_timestamp_request(&signer, message).await
|
|
174
141
|
}
|
|
175
142
|
|
|
176
|
-
fn async_raw_signer(&self) -> Option<Box<&dyn AsyncRawSigner>> {
|
|
177
|
-
Some(Box::new(self))
|
|
178
|
-
}
|
|
179
|
-
|
|
180
143
|
fn dynamic_assertions(&self) -> Vec<Box<dyn AsyncDynamicAssertion>> {
|
|
181
144
|
let mut identity_assertions = self.identity_assertions.write().unwrap();
|
|
182
145
|
let ia_clone = identity_assertions.split_off(0);
|
package/src/neon_reader.rs
CHANGED
|
@@ -57,12 +57,9 @@ impl NeonReader {
|
|
|
57
57
|
let (deferred, promise) = cx.promise();
|
|
58
58
|
rt.spawn(async move {
|
|
59
59
|
let result: Result<Reader> = async {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
Error::Reading("Source asset must have a mime type".to_string())
|
|
64
|
-
})?
|
|
65
|
-
.to_owned();
|
|
60
|
+
// An empty format asks the native library to detect the asset's format from its
|
|
61
|
+
// bytes, so a source with no known MIME type can still be read.
|
|
62
|
+
let format = source.mime_type().unwrap_or_default();
|
|
66
63
|
|
|
67
64
|
let stream = source.into_read_stream()?;
|
|
68
65
|
|
|
@@ -119,12 +116,9 @@ impl NeonReader {
|
|
|
119
116
|
let (deferred, promise) = cx.promise();
|
|
120
117
|
rt.spawn(async move {
|
|
121
118
|
let result = async {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
Error::Reading("Source asset must have a mime type".to_string())
|
|
126
|
-
})?
|
|
127
|
-
.to_owned();
|
|
119
|
+
// An empty format asks the native library to detect the asset's format from its
|
|
120
|
+
// bytes, so an asset with no known MIME type can still be read.
|
|
121
|
+
let format = asset.mime_type().unwrap_or_default();
|
|
128
122
|
let stream = asset.into_read_stream()?;
|
|
129
123
|
|
|
130
124
|
let reader = if let Some(context) = context_opt {
|
package/src/neon_signer.rs
CHANGED
|
@@ -17,10 +17,7 @@ use std::{boxed::Box, str::FromStr, sync::Arc};
|
|
|
17
17
|
use async_trait::async_trait;
|
|
18
18
|
use c2pa::{
|
|
19
19
|
create_signer,
|
|
20
|
-
crypto::{
|
|
21
|
-
raw_signature::{AsyncRawSigner, RawSigner, RawSignerError},
|
|
22
|
-
time_stamp::{AsyncTimeStampProvider, TimeStampProvider},
|
|
23
|
-
},
|
|
20
|
+
crypto::time_stamp::{AsyncTimeStampProvider, TimeStampProvider},
|
|
24
21
|
AsyncSigner,
|
|
25
22
|
Error::OtherError,
|
|
26
23
|
Signer, SigningAlg,
|
|
@@ -233,10 +230,6 @@ impl NeonCallbackSigner {
|
|
|
233
230
|
|
|
234
231
|
Ok(promise)
|
|
235
232
|
}
|
|
236
|
-
|
|
237
|
-
pub fn as_raw_signer(&self) -> &dyn AsyncRawSigner {
|
|
238
|
-
self
|
|
239
|
-
}
|
|
240
233
|
}
|
|
241
234
|
|
|
242
235
|
/// # Safety
|
|
@@ -258,7 +251,7 @@ impl NeonCallbackSigner {
|
|
|
258
251
|
/// - `Sync`: Allows the type to be shared between threads
|
|
259
252
|
///
|
|
260
253
|
/// The type needs these capabilities because it:
|
|
261
|
-
/// - Implements `AsyncSigner`
|
|
254
|
+
/// - Implements the `AsyncSigner` trait for asynchronous signing operations
|
|
262
255
|
/// - Is used in the `identity_sign_async` function which performs asynchronous operations
|
|
263
256
|
/// - Is part of a Node.js binding where async operations are common
|
|
264
257
|
unsafe impl Send for NeonCallbackSigner {}
|
|
@@ -329,10 +322,6 @@ impl AsyncSigner for NeonCallbackSigner {
|
|
|
329
322
|
fn direct_cose_handling(&self) -> bool {
|
|
330
323
|
self.config.direct_cose_handling
|
|
331
324
|
}
|
|
332
|
-
|
|
333
|
-
fn async_raw_signer(&self) -> Option<Box<&dyn AsyncRawSigner>> {
|
|
334
|
-
Some(Box::new(self))
|
|
335
|
-
}
|
|
336
325
|
}
|
|
337
326
|
|
|
338
327
|
impl TimeStampProvider for NeonCallbackSigner {
|
|
@@ -353,93 +342,6 @@ impl AsyncTimeStampProvider for NeonCallbackSigner {
|
|
|
353
342
|
}
|
|
354
343
|
}
|
|
355
344
|
|
|
356
|
-
#[async_trait]
|
|
357
|
-
impl AsyncRawSigner for NeonCallbackSigner {
|
|
358
|
-
async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, RawSignerError> {
|
|
359
|
-
let (tx, rx) = oneshot::channel();
|
|
360
|
-
let sign_fn = self.callback.clone();
|
|
361
|
-
let data = data.to_vec();
|
|
362
|
-
|
|
363
|
-
// Send the signing request to the JavaScript side
|
|
364
|
-
self.channel
|
|
365
|
-
.try_send(move |mut cx| {
|
|
366
|
-
let to_be_signed = JsBuffer::from_slice(&mut cx, &data)?;
|
|
367
|
-
let sign_fn = sign_fn.to_inner(&mut cx);
|
|
368
|
-
|
|
369
|
-
let sign_fut = sign_fn
|
|
370
|
-
.call_with(&cx)
|
|
371
|
-
.arg(to_be_signed)
|
|
372
|
-
.apply::<JsPromise, _>(&mut cx)?
|
|
373
|
-
.to_future(&mut cx, |mut cx, result| match result {
|
|
374
|
-
Ok(value) => {
|
|
375
|
-
let buffer = value.downcast_or_throw::<JsBuffer, _>(&mut cx)?;
|
|
376
|
-
Ok(Ok(buffer.as_slice(&cx).to_vec()))
|
|
377
|
-
}
|
|
378
|
-
Err(err) => {
|
|
379
|
-
let err_string = match err.to_string(&mut cx) {
|
|
380
|
-
Ok(js_string) => js_string.value(&mut cx),
|
|
381
|
-
Err(e) => return Err(e),
|
|
382
|
-
};
|
|
383
|
-
Ok(Err(RawSignerError::CryptoLibraryError(err_string)))
|
|
384
|
-
}
|
|
385
|
-
})?;
|
|
386
|
-
|
|
387
|
-
let _ = tx.send(sign_fut);
|
|
388
|
-
Ok(())
|
|
389
|
-
})
|
|
390
|
-
.map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
|
|
391
|
-
|
|
392
|
-
// Wait for the JavaScript promise to resolve
|
|
393
|
-
let sign_fut = rx
|
|
394
|
-
.await
|
|
395
|
-
.map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
|
|
396
|
-
|
|
397
|
-
// Get the result from the future
|
|
398
|
-
sign_fut
|
|
399
|
-
.await
|
|
400
|
-
.map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
fn alg(&self) -> SigningAlg {
|
|
404
|
-
self.config.alg
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
|
|
408
|
-
let pems = pem::parse_many(&self.config.certs)
|
|
409
|
-
.map_err(|e| RawSignerError::CryptoLibraryError(e.to_string()))?;
|
|
410
|
-
Ok(pems.into_iter().map(|p| p.into_contents()).collect())
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
fn reserve_size(&self) -> usize {
|
|
414
|
-
self.config.reserve_size
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
async fn ocsp_response(&self) -> Option<Vec<u8>> {
|
|
418
|
-
None
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
impl RawSigner for NeonCallbackSigner {
|
|
423
|
-
fn sign(&self, _data: &[u8]) -> Result<Vec<u8>, RawSignerError> {
|
|
424
|
-
// Synchronous signing is not supported; use AsyncRawSigner instead
|
|
425
|
-
Err(RawSignerError::InternalError(
|
|
426
|
-
"Synchronous signing not supported - use AsyncRawSigner instead".to_string(),
|
|
427
|
-
))
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
fn alg(&self) -> SigningAlg {
|
|
431
|
-
AsyncRawSigner::alg(self)
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
|
|
435
|
-
AsyncRawSigner::cert_chain(self)
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
fn reserve_size(&self) -> usize {
|
|
439
|
-
AsyncRawSigner::reserve_size(self)
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
|
|
443
345
|
pub struct NeonLocalSigner {
|
|
444
346
|
signer: Box<dyn Signer>,
|
|
445
347
|
}
|