@contentauth/c2pa-node 0.1.2 → 0.2.0

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.
@@ -1,42 +1,8 @@
1
- "use strict";
2
1
  // Copyright 2024 Adobe. All rights reserved.
3
2
  // This file is licensed to you under the Apache License,
4
3
  // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
5
4
  // or the MIT license (http://opensource.org/licenses/MIT),
6
5
  // at your option.
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
6
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
41
7
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
8
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -46,131 +12,140 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
46
12
  step((generator = generator.apply(thisArg, _arguments || [])).next());
47
13
  });
48
14
  };
49
- Object.defineProperty(exports, "__esModule", { value: true });
50
- // Unless required by applicable law or agreed to in writing,
51
- // this software is distributed on an "AS IS" BASIS, WITHOUT
52
- // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
53
- // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
54
- // specific language governing permissions and limitations under
55
- // each license.
56
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
57
- const index_1 = require("./index");
58
- const fs = __importStar(require("fs-extra"));
59
- const crypto = __importStar(require("crypto"));
60
- // TODO: move to a separate test file
15
+ import * as fs from "fs-extra";
16
+ import * as crypto from "crypto";
17
+ import { encode } from "cbor2";
61
18
  class TestSigner {
62
19
  constructor(privateKey) {
63
20
  this.sign = (bytes) => __awaiter(this, void 0, void 0, function* () {
64
- return crypto.sign(null, bytes, this.privateKey);
21
+ const sign = crypto.createSign("SHA256");
22
+ sign.update(bytes);
23
+ sign.end();
24
+ return sign.sign(this.privateKey);
65
25
  });
66
26
  this.privateKey = crypto.createPrivateKey({
67
27
  key: privateKey,
68
- format: 'pem',
28
+ format: "pem",
69
29
  });
70
30
  }
71
31
  }
72
- describe('IdentityAssertionBuilder', () => {
32
+ class TestCawgSigner {
33
+ constructor(manifestSigner) {
34
+ this.manifestSigner = manifestSigner;
35
+ this.sign = (payload) => __awaiter(this, void 0, void 0, function* () {
36
+ const cborBytes = Buffer.from(encode(payload));
37
+ return this.manifestSigner.sign(cborBytes);
38
+ });
39
+ }
40
+ }
41
+ describe("IdentityAssertionBuilder", () => {
73
42
  const manifestDefinition = {
74
- vendor: 'test',
75
- claim_version: 2,
43
+ vendor: "test",
76
44
  claim_generator_info: [
77
45
  {
78
- name: 'c2pa_test',
79
- version: '2.0.0',
80
- },
81
- ],
82
- metadata: [
83
- {
84
- dateTime: '1985-04-12T23:20:50.52Z',
85
- my_custom_metadata: 'my custom metatdata value',
46
+ name: "c2pa_test",
47
+ version: "2.0.0",
86
48
  },
87
49
  ],
88
- title: 'Test_Manifest',
89
- format: 'image/jpeg',
90
- instance_id: '1234',
50
+ claim_generator: "c2pa_test",
51
+ title: "Test_Manifest",
52
+ format: "image/jpeg",
53
+ instance_id: "1234",
54
+ thumbnail: { format: "image/jpeg", identifier: "thumbnail.jpg" },
55
+ resources: { resources: {} },
91
56
  ingredients: [
92
57
  {
93
- title: 'Test',
94
- format: 'image/jpeg',
95
- instance_id: '12345',
96
- relationship: 'componentOf',
58
+ title: "Test",
59
+ format: "image/jpeg",
60
+ instance_id: "12345",
61
+ relationship: "componentOf",
62
+ thumbnail: { format: "image/jpeg", identifier: "ingredient-thumb.jpg" },
63
+ resources: { resources: {} },
97
64
  },
98
65
  ],
99
66
  assertions: [
100
67
  {
101
- label: 'c2pa.actions',
68
+ label: "c2pa.actions.v2",
102
69
  data: {
103
70
  actions: [
104
71
  {
105
- action: 'c2pa.created',
106
- digitalSourceType: 'http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture',
72
+ action: "c2pa.created",
73
+ parameters: {
74
+ digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
75
+ },
107
76
  },
108
77
  ],
109
78
  },
79
+ kind: "Json",
110
80
  },
111
81
  {
112
- label: 'cawg.training-mining',
82
+ label: "cawg.training-mining",
113
83
  data: {
114
- entries: {
115
- 'cawg.ai_inference': {
116
- use: 'notAllowed',
84
+ metadata: {
85
+ "cawg.ai_inference": {
86
+ use: "notAllowed",
117
87
  },
118
- 'cawg.ai_generative_training': {
119
- use: 'notAllowed',
88
+ "cawg.ai_generative_training": {
89
+ use: "notAllowed",
120
90
  },
121
91
  },
122
92
  },
123
93
  },
124
94
  ],
125
95
  };
126
- it('should build an Identity Assertion Signer', () => __awaiter(void 0, void 0, void 0, function* () {
96
+ it("should build an Identity Assertion Signer", () => __awaiter(void 0, void 0, void 0, function* () {
97
+ const { CallbackSigner } = yield import("./Signer");
98
+ const { Reader } = yield import("./Reader");
99
+ const { Builder } = yield import("./Builder");
100
+ const { IdentityAssertionBuilder, IdentityAssertionSigner, CallbackCredentialHolder, } = yield import("./IdentityAssertion");
127
101
  // Read certificate files once
128
- const c2paPrivateKey = yield fs.readFile('./tests/fixtures/certs/es256.pem');
129
- const c2paPublicKey = yield fs.readFile('./tests/fixtures/certs/es256.pub');
130
- const cawgPrivateKey = yield fs.readFile('./tests/fixtures/certs/ed25519.pem');
131
- const cawgPublicKey = yield fs.readFile('./tests/fixtures/certs/ed25519.pub');
102
+ const c2paPrivateKey = yield fs.readFile("./tests/fixtures/certs/es256.pem");
103
+ const c2paPublicKey = yield fs.readFile("./tests/fixtures/certs/es256.pub");
104
+ // Use the same signer for both C2PA manifest and COSE signing
132
105
  // Create signer configurations
133
106
  const c2paConfig = {
134
- alg: 'es256',
107
+ alg: "es256",
135
108
  certs: [c2paPublicKey],
136
109
  reserveSize: 10000,
137
110
  tsaUrl: undefined,
138
111
  tsaHeaders: undefined,
139
112
  tsaBody: undefined,
140
- };
141
- const cawgConfig = {
142
- alg: 'ed25519',
143
- certs: [cawgPublicKey],
144
- reserveSize: 10000,
145
- tsaUrl: undefined,
146
- tsaHeaders: undefined,
147
- tsaBody: undefined,
113
+ directCoseHandling: true,
148
114
  };
149
115
  // Create signers
150
116
  const c2paTestSigner = new TestSigner(c2paPrivateKey);
151
- const cawgTestSigner = new TestSigner(cawgPrivateKey);
152
- const c2paSigner = index_1.CallbackSigner.newSigner(c2paConfig, c2paTestSigner.sign);
153
- const cawgSigner = index_1.CallbackSigner.newSigner(cawgConfig, cawgTestSigner.sign);
117
+ const c2paSigner = CallbackSigner.newSigner(c2paConfig, c2paTestSigner.sign);
118
+ const cawgTestSigner = new TestCawgSigner(c2paTestSigner);
119
+ const cawgSigner = CallbackCredentialHolder.newCallbackCredentialHolder(10000, "cawg.x509.cose", cawgTestSigner.sign);
154
120
  const source = {
155
- buffer: yield fs.readFile('./tests/fixtures/CA.jpg'),
156
- mimeType: 'jpeg',
121
+ buffer: yield fs.readFile("./tests/fixtures/CA.jpg"),
122
+ mimeType: "image/jpeg",
157
123
  };
158
124
  const dest = {
159
125
  buffer: null,
160
126
  };
161
127
  // Create the manifest builder
162
- const builder = index_1.Builder.withJson(manifestDefinition);
128
+ const builder = Builder.withJson(manifestDefinition);
129
+ // Add the required resources
130
+ yield builder.addResource("thumbnail.jpg", {
131
+ mimeType: "image/jpeg",
132
+ buffer: yield fs.readFile("./tests/fixtures/thumbnail.jpg"),
133
+ });
134
+ yield builder.addResource("ingredient-thumb.jpg", {
135
+ mimeType: "image/jpeg",
136
+ buffer: yield fs.readFile("./tests/fixtures/thumbnail.jpg"),
137
+ });
163
138
  // Create and configure the identity assertion
164
- const ia_signer = index_1.IdentityAssertionSigner.new(c2paSigner);
165
- const iab = yield index_1.IdentityAssertionBuilder.identityBuilderForCredentialHolder(cawgSigner);
166
- iab.addReferencedAssertions(['cawg.training-mining']);
167
- ia_signer.addIdentityAssertion(iab);
168
- // Sign the manifest
169
- yield builder.signAsync(c2paSigner, source, dest);
139
+ const iaSigner = IdentityAssertionSigner.new(c2paSigner.signer());
140
+ const iab = yield IdentityAssertionBuilder.identityBuilderForCredentialHolder(cawgSigner);
141
+ iab.addReferencedAssertions(["cawg.training-mining"]);
142
+ iaSigner.addIdentityAssertion(iab);
143
+ // Sign the manifest (standard async flow)
144
+ yield builder.signAsync(iaSigner, source, dest);
170
145
  // Verify the manifest
171
- const reader = yield index_1.Reader.fromAsset({
146
+ const reader = yield Reader.fromAsset({
172
147
  buffer: dest.buffer,
173
- mimeType: 'jpeg',
148
+ mimeType: "image/jpeg",
174
149
  });
175
150
  yield reader.postValidateCawg();
176
151
  }));
package/dist/Reader.js CHANGED
@@ -1,42 +1,8 @@
1
- "use strict";
2
1
  // Copyright 2024 Adobe. All rights reserved.
3
2
  // This file is licensed to you under the Apache License,
4
3
  // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
5
4
  // or the MIT license (http://opensource.org/licenses/MIT),
6
5
  // at your option.
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
6
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
41
7
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
8
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -46,16 +12,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
46
12
  step((generator = generator.apply(thisArg, _arguments || [])).next());
47
13
  });
48
14
  };
49
- Object.defineProperty(exports, "__esModule", { value: true });
50
- exports.Reader = void 0;
51
15
  // Unless required by applicable law or agreed to in writing,
52
16
  // this software is distributed on an "AS IS" BASIS, WITHOUT
53
17
  // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
54
18
  // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
55
19
  // specific language governing permissions and limitations under
56
20
  // each license.
57
- const neon = __importStar(require("index.node"));
58
- class Reader {
21
+ const neon = require("./index.node");
22
+ export class Reader {
59
23
  constructor(reader) {
60
24
  this.reader = reader;
61
25
  }
@@ -105,4 +69,3 @@ class Reader {
105
69
  });
106
70
  }
107
71
  }
108
- exports.Reader = Reader;
@@ -1,42 +1,8 @@
1
- "use strict";
2
1
  // Copyright 2024 Adobe. All rights reserved.
3
2
  // This file is licensed to you under the Apache License,
4
3
  // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
5
4
  // or the MIT license (http://opensource.org/licenses/MIT),
6
5
  // at your option.
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
6
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
41
7
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
8
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -46,20 +12,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
46
12
  step((generator = generator.apply(thisArg, _arguments || [])).next());
47
13
  });
48
14
  };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- Object.defineProperty(exports, "__esModule", { value: true });
53
15
  // Unless required by applicable law or agreed to in writing,
54
16
  // this software is distributed on an "AS IS" BASIS, WITHOUT
55
17
  // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
56
18
  // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
57
19
  // specific language governing permissions and limitations under
58
20
  // each license.
59
- const index_1 = require("./index");
60
- const path_1 = __importDefault(require("path"));
61
- const fs = __importStar(require("fs-extra"));
62
- const tempDir = path_1.default.join(__dirname, "tmp");
21
+ import { Reader } from "./Reader";
22
+ import path from "path";
23
+ import * as fs from "fs-extra";
24
+ const tempDir = path.join(__dirname, "tmp");
63
25
  describe("Reader", () => {
64
26
  const manifestStore = JSON.parse(`{
65
27
  "active_manifest": "contentauth:urn:uuid:e8ce52bc-df72-4ba5-ba37-52c360e76ba4",
@@ -169,6 +131,7 @@ describe("Reader", () => {
169
131
  "signature_info": {
170
132
  "alg": "Ps256",
171
133
  "issuer": "C2PA Test Signing Cert",
134
+ "common_name": "C2PA Signer",
172
135
  "cert_serial_number": "720724073027128164015125666832722375746636448153",
173
136
  "time": "2025-02-04T17:38:01+00:00"
174
137
  },
@@ -184,13 +147,18 @@ describe("Reader", () => {
184
147
  }));
185
148
  it("should read from an ArrayBuffer", () => __awaiter(void 0, void 0, void 0, function* () {
186
149
  const buffer = yield fs.readFile("./tests/fixtures/CAI.jpg");
187
- const reader = yield index_1.Reader.fromAsset({ buffer, mimeType: "jpeg" });
150
+ const reader = yield Reader.fromAsset({
151
+ buffer,
152
+ mimeType: "jpeg",
153
+ });
188
154
  const json = reader.json();
189
155
  expect(json.manifests).toEqual(manifestStore.manifests);
190
156
  expect(json.active_manifest).toEqual(manifestStore.active_manifest);
191
157
  }));
192
158
  it("should read from a file", () => __awaiter(void 0, void 0, void 0, function* () {
193
- const reader = yield index_1.Reader.fromAsset({ path: "./tests/fixtures/CAI.jpg" });
159
+ const reader = yield Reader.fromAsset({
160
+ path: "./tests/fixtures/CAI.jpg",
161
+ });
194
162
  const json = reader.json();
195
163
  expect(json.manifests).toEqual(manifestStore.manifests);
196
164
  expect(json.active_manifest).toEqual(manifestStore.active_manifest);
@@ -198,7 +166,7 @@ describe("Reader", () => {
198
166
  it("should read from manifest data and buffer", () => __awaiter(void 0, void 0, void 0, function* () {
199
167
  const manifestData = yield fs.readFile("./tests/fixtures/CAI/manifest_data.c2pa");
200
168
  const buffer = yield fs.readFile("./tests/fixtures/CAI.jpg");
201
- const reader = yield index_1.Reader.fromManifestDataAndAsset(manifestData, {
169
+ const reader = yield Reader.fromManifestDataAndAsset(manifestData, {
202
170
  buffer,
203
171
  mimeType: "jpeg",
204
172
  });
@@ -208,7 +176,7 @@ describe("Reader", () => {
208
176
  }));
209
177
  it("should read from manifest data and file", () => __awaiter(void 0, void 0, void 0, function* () {
210
178
  const manifestData = yield fs.readFile("./tests/fixtures/CAI/manifest_data.c2pa");
211
- const reader = yield index_1.Reader.fromManifestDataAndAsset(manifestData, {
179
+ const reader = yield Reader.fromManifestDataAndAsset(manifestData, {
212
180
  path: "./tests/fixtures/CAI.jpg",
213
181
  });
214
182
  const json = reader.json();
@@ -217,8 +185,10 @@ describe("Reader", () => {
217
185
  it("should write to a file", () => __awaiter(void 0, void 0, void 0, function* () {
218
186
  var _a;
219
187
  let bytesWritten = 0;
220
- const outputPath = path_1.default.join(tempDir, "thumbnail.jpg");
221
- const reader = yield index_1.Reader.fromAsset({ path: "./tests/fixtures/CAI.jpg" });
188
+ const outputPath = path.join(tempDir, "thumbnail.jpg");
189
+ const reader = yield Reader.fromAsset({
190
+ path: "./tests/fixtures/CAI.jpg",
191
+ });
222
192
  const activeManifest = reader.getActive();
223
193
  const uri = (_a = activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.thumbnail) === null || _a === void 0 ? void 0 : _a.identifier;
224
194
  if (uri !== undefined) {
@@ -230,12 +200,14 @@ describe("Reader", () => {
230
200
  expect(fs.existsSync(outputPath));
231
201
  }));
232
202
  it("should report manifest is embedded", () => __awaiter(void 0, void 0, void 0, function* () {
233
- const reader = yield index_1.Reader.fromAsset({ path: "./tests/fixtures/CAI.jpg" });
203
+ const reader = yield Reader.fromAsset({
204
+ path: "./tests/fixtures/CAI.jpg",
205
+ });
234
206
  expect(reader.remoteUrl()).toEqual("");
235
207
  expect(reader.isEmbedded()).toBeTruthy();
236
208
  }));
237
209
  it("should report manifest is not embedded", () => __awaiter(void 0, void 0, void 0, function* () {
238
- const reader = yield index_1.Reader.fromAsset({
210
+ const reader = yield Reader.fromAsset({
239
211
  path: "./tests/fixtures/cloud.jpg",
240
212
  });
241
213
  expect(reader.remoteUrl()).toEqual("https://cai-manifests.adobe.com/manifests/adobe-urn-uuid-5f37e182-3687-462e-a7fb-573462780391");
@@ -0,0 +1,203 @@
1
+ // Copyright 2025 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License,
3
+ // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
+ // or the MIT license (http://opensource.org/licenses/MIT),
5
+ // at your option.
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ // Unless required by applicable law or agreed to in writing,
16
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
17
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
18
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
19
+ // specific language governing permissions and limitations under
20
+ // each license.
21
+ const neon = require("./index.node");
22
+ import * as fs from "fs-extra";
23
+ import path from "path";
24
+ import fetch from "node-fetch";
25
+ /**
26
+ * Load settings from a JSON string and apply them globally.
27
+ * @param json The JSON string containing the settings configuration
28
+ */
29
+ export function loadC2paSettings(json) {
30
+ neon.loadSettings(json);
31
+ }
32
+ /**
33
+ * Load settings from a TOML string and apply them globally.
34
+ * @param toml The TOML string containing the settings configuration
35
+ */
36
+ export function loadC2paSettingsToml(toml) {
37
+ neon.loadSettingsToml(toml);
38
+ }
39
+ /**
40
+ * Load settings from a TOML or JSON file path and apply them globally.
41
+ * The file format is determined by the file extension (.toml for TOML, otherwise JSON).
42
+ * @param filePath The path to the settings file
43
+ */
44
+ export function loadSettingsFromFile(filePath) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ const ext = path.extname(filePath).toLowerCase();
47
+ const content = yield fs.readFile(filePath, "utf8");
48
+ if (ext === ".toml") {
49
+ loadC2paSettingsToml(content);
50
+ return;
51
+ }
52
+ // Assume JSON (or JSON5 that is valid JSON) otherwise
53
+ // If needed, callers can ensure the content is valid JSON.
54
+ loadC2paSettings(content);
55
+ });
56
+ }
57
+ /**
58
+ * Load settings from a URL and apply them globally.
59
+ * The format is determined by the content-type header or file extension (.toml for TOML, otherwise JSON).
60
+ * @param url The URL to fetch the settings from
61
+ */
62
+ export function loadSettingsFromUrl(url) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ const res = yield fetch(url);
65
+ if (!res.ok) {
66
+ throw new Error(`Failed to fetch settings from URL: ${res.status} ${res.statusText}`);
67
+ }
68
+ const contentType = res.headers.get("content-type") || "";
69
+ const text = yield res.text();
70
+ const isToml = contentType.includes("toml") || url.toLowerCase().endsWith(".toml");
71
+ if (isToml) {
72
+ loadC2paSettingsToml(text);
73
+ return;
74
+ }
75
+ // Treat as JSON by default
76
+ loadC2paSettings(text);
77
+ });
78
+ }
79
+ /**
80
+ * Get the current settings as a JSON string.
81
+ * @returns The JSON representation of the current settings
82
+ */
83
+ export function getSettingsJson() {
84
+ return neon.getSettingsJson();
85
+ }
86
+ /**
87
+ * Load trust configuration into the main trust settings.
88
+ * @param trustConfig The trust configuration object
89
+ */
90
+ export function loadTrustConfig(trustConfig) {
91
+ var _a, _b, _c, _d;
92
+ // Convert settings to snake_case for the neon Rust code.
93
+ // Explicitly set undefined fields to null to ensure they are cleared
94
+ const config = {
95
+ verify_trust_list: trustConfig.verifyTrustList,
96
+ user_anchors: (_a = trustConfig.userAnchors) !== null && _a !== void 0 ? _a : null,
97
+ trust_anchors: (_b = trustConfig.trustAnchors) !== null && _b !== void 0 ? _b : null,
98
+ trust_config: (_c = trustConfig.trustConfig) !== null && _c !== void 0 ? _c : null,
99
+ allowed_list: (_d = trustConfig.allowedList) !== null && _d !== void 0 ? _d : null,
100
+ };
101
+ neon.loadTrustConfig(JSON.stringify(config));
102
+ }
103
+ /**
104
+ * Load trust configuration into the CAWG trust settings.
105
+ * @param trustConfig The trust configuration object
106
+ */
107
+ export function loadCawgTrustConfig(trustConfig) {
108
+ var _a, _b, _c, _d;
109
+ // Convert settings to snake_case for the neon Rust code
110
+ // Explicitly set undefined fields to null to ensure they are cleared
111
+ const config = {
112
+ verify_trust_list: trustConfig.verifyTrustList,
113
+ user_anchors: (_a = trustConfig.userAnchors) !== null && _a !== void 0 ? _a : null,
114
+ trust_anchors: (_b = trustConfig.trustAnchors) !== null && _b !== void 0 ? _b : null,
115
+ trust_config: (_c = trustConfig.trustConfig) !== null && _c !== void 0 ? _c : null,
116
+ allowed_list: (_d = trustConfig.allowedList) !== null && _d !== void 0 ? _d : null,
117
+ };
118
+ neon.loadCawgTrustConfig(JSON.stringify(config));
119
+ }
120
+ /**
121
+ * Get the current trust configuration.
122
+ * @returns The current trust configuration object
123
+ */
124
+ export function getTrustConfig() {
125
+ var _a, _b, _c, _d;
126
+ const json = neon.getTrustConfig();
127
+ const parsed = JSON.parse(json);
128
+ // Convert snake_case to camelCase to match TrustConfig interface
129
+ // Handle undefined values by converting them to null
130
+ return {
131
+ verifyTrustList: parsed.verify_trust_list,
132
+ userAnchors: (_a = parsed.user_anchors) !== null && _a !== void 0 ? _a : null,
133
+ trustAnchors: (_b = parsed.trust_anchors) !== null && _b !== void 0 ? _b : null,
134
+ trustConfig: (_c = parsed.trust_config) !== null && _c !== void 0 ? _c : null,
135
+ allowedList: (_d = parsed.allowed_list) !== null && _d !== void 0 ? _d : null,
136
+ };
137
+ }
138
+ /**
139
+ * Get the current CAWG trust configuration.
140
+ * @returns The current CAWG trust configuration object
141
+ */
142
+ export function getCawgTrustConfig() {
143
+ var _a, _b, _c, _d;
144
+ const json = neon.getCawgTrustConfig();
145
+ const parsed = JSON.parse(json);
146
+ // Convert snake_case to camelCase to match TrustConfig interface
147
+ // Handle undefined values by converting them to null
148
+ return {
149
+ verifyTrustList: parsed.verify_trust_list,
150
+ userAnchors: (_a = parsed.user_anchors) !== null && _a !== void 0 ? _a : null,
151
+ trustAnchors: (_b = parsed.trust_anchors) !== null && _b !== void 0 ? _b : null,
152
+ trustConfig: (_c = parsed.trust_config) !== null && _c !== void 0 ? _c : null,
153
+ allowedList: (_d = parsed.allowed_list) !== null && _d !== void 0 ? _d : null,
154
+ };
155
+ }
156
+ /**
157
+ * Load verify configuration into the verify settings.
158
+ * @param verifyConfig The verify configuration object
159
+ */
160
+ export function loadVerifyConfig(verifyConfig) {
161
+ // Convert camelCase to snake_case for the neon Rust code
162
+ const config = {
163
+ verify_after_reading: verifyConfig.verifyAfterReading,
164
+ verify_after_sign: verifyConfig.verifyAfterSign,
165
+ verify_trust: verifyConfig.verifyTrust,
166
+ verify_timestamp_trust: verifyConfig.verifyTimestampTrust,
167
+ ocsp_fetch: verifyConfig.ocspFetch,
168
+ remote_manifest_fetch: verifyConfig.remoteManifestFetch,
169
+ check_ingredient_trust: verifyConfig.checkIngredientTrust,
170
+ skip_ingredient_conflict_resolution: verifyConfig.skipIngredientConflictResolution,
171
+ strict_v1_validation: verifyConfig.strictV1Validation,
172
+ };
173
+ neon.loadVerifyConfig(JSON.stringify(config));
174
+ }
175
+ /**
176
+ * Patch the verify configuration with any subset of fields.
177
+ * @param patch Partial verify config fields to update
178
+ */
179
+ export function patchVerifyConfig(patch) {
180
+ const current = getVerifyConfig();
181
+ const updated = Object.assign(Object.assign({}, current), patch);
182
+ loadVerifyConfig(updated);
183
+ }
184
+ /**
185
+ * Get the current verify configuration.
186
+ * @returns The current verify configuration object
187
+ */
188
+ export function getVerifyConfig() {
189
+ const json = neon.getVerifyConfig();
190
+ const parsed = JSON.parse(json);
191
+ // Convert snake_case to camelCase to match VerifyConfig interface
192
+ return {
193
+ verifyAfterReading: parsed.verify_after_reading,
194
+ verifyAfterSign: parsed.verify_after_sign,
195
+ verifyTrust: parsed.verify_trust,
196
+ verifyTimestampTrust: parsed.verify_timestamp_trust,
197
+ ocspFetch: parsed.ocsp_fetch,
198
+ remoteManifestFetch: parsed.remote_manifest_fetch,
199
+ checkIngredientTrust: parsed.check_ingredient_trust,
200
+ skipIngredientConflictResolution: parsed.skip_ingredient_conflict_resolution,
201
+ strictV1Validation: parsed.strict_v1_validation,
202
+ };
203
+ }