@ac-kit/format-tsp 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.
Files changed (64) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/LICENSE +28 -0
  3. package/README.md +202 -2
  4. package/dist/_decode.d.ts +17 -0
  5. package/dist/_decode.d.ts.map +1 -0
  6. package/dist/_decode.js +41 -0
  7. package/dist/_decode.js.map +1 -0
  8. package/dist/_generalized-time.d.ts +12 -0
  9. package/dist/_generalized-time.d.ts.map +1 -0
  10. package/dist/_generalized-time.js +40 -0
  11. package/dist/_generalized-time.js.map +1 -0
  12. package/dist/_hash-algorithms.d.ts +41 -0
  13. package/dist/_hash-algorithms.d.ts.map +1 -0
  14. package/dist/_hash-algorithms.js +66 -0
  15. package/dist/_hash-algorithms.js.map +1 -0
  16. package/dist/_pkix.d.ts +37 -0
  17. package/dist/_pkix.d.ts.map +1 -0
  18. package/dist/_pkix.js +48 -0
  19. package/dist/_pkix.js.map +1 -0
  20. package/dist/consistency.d.ts +101 -0
  21. package/dist/consistency.d.ts.map +1 -0
  22. package/dist/consistency.js +61 -0
  23. package/dist/consistency.js.map +1 -0
  24. package/dist/constants.d.ts +32 -0
  25. package/dist/constants.d.ts.map +1 -0
  26. package/dist/constants.js +39 -0
  27. package/dist/constants.js.map +1 -0
  28. package/dist/errors.d.ts +17 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +21 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/index.d.ts +10 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +10 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/message-imprint.d.ts +72 -0
  37. package/dist/message-imprint.d.ts.map +1 -0
  38. package/dist/message-imprint.js +97 -0
  39. package/dist/message-imprint.js.map +1 -0
  40. package/dist/request.d.ts +94 -0
  41. package/dist/request.d.ts.map +1 -0
  42. package/dist/request.js +123 -0
  43. package/dist/request.js.map +1 -0
  44. package/dist/response.d.ts +56 -0
  45. package/dist/response.d.ts.map +1 -0
  46. package/dist/response.js +92 -0
  47. package/dist/response.js.map +1 -0
  48. package/dist/schema.d.ts +39 -0
  49. package/dist/schema.d.ts.map +1 -0
  50. package/dist/schema.js +107 -0
  51. package/dist/schema.js.map +1 -0
  52. package/dist/token.d.ts +51 -0
  53. package/dist/token.d.ts.map +1 -0
  54. package/dist/token.js +137 -0
  55. package/dist/token.js.map +1 -0
  56. package/dist/tst-info.d.ts +94 -0
  57. package/dist/tst-info.d.ts.map +1 -0
  58. package/dist/tst-info.js +140 -0
  59. package/dist/tst-info.js.map +1 -0
  60. package/dist/verify.d.ts +110 -0
  61. package/dist/verify.d.ts.map +1 -0
  62. package/dist/verify.js +160 -0
  63. package/dist/verify.js.map +1 -0
  64. package/package.json +78 -3
package/dist/token.js ADDED
@@ -0,0 +1,137 @@
1
+ import { ContentInfoSchema, EncapsulatedContentInfoSchema, } from "@ac-kit/cred-cms";
2
+ import { BerReader, DecodingError, ref } from "@ac-kit/format-asn1";
3
+ import { oidEqual, oidToDotted } from "@ac-kit/format-oid";
4
+ import { decodeDer_, toTspFormatError_ } from "./_decode.js";
5
+ import { idCtTstInfo, idSignedData } from "./constants.js";
6
+ import { TspFormatError } from "./errors.js";
7
+ import { decodeTstInfo } from "./tst-info.js";
8
+ /** Universal, constructed, tag 16. */
9
+ const SEQUENCE_IDENTIFIER = 0x30;
10
+ const CONTENT_INFO_DEF_ = ref(ContentInfoSchema);
11
+ const ENCAPSULATED_DEF_ = ref(EncapsulatedContentInfoSchema);
12
+ /**
13
+ * Accepts a token stored on its own (a `.tst` file, an evidence package):
14
+ * checks that it is one DER-framed `ContentInfo` of type `id-signedData` whose
15
+ * content is a SEQUENCE, and copies it. Nothing inside the `SignedData` is
16
+ * checked beyond its framing.
17
+ *
18
+ * Complexity: O(bytes).
19
+ *
20
+ * @throws {TspFormatError} For malformed framing, trailing bytes, a content
21
+ * type other than `id-signedData`, or content that is not a SEQUENCE.
22
+ */
23
+ export function decodeTimeStampToken(bytes) {
24
+ checkTokenEnvelope_(bytes, 0);
25
+ return { encoded: new Uint8Array(bytes) };
26
+ }
27
+ /**
28
+ * Reads the `TSTInfo` a token carries **without verifying anything**: not the
29
+ * signature, not the signer, not a certificate. The result has no authenticity
30
+ * at all — anyone can build a token saying anything. Use it to display what a
31
+ * token claims, or to check consistency with a request before or after a CMS
32
+ * verifier has authenticated the same bytes.
33
+ *
34
+ * Walks `ContentInfo → SignedData → encapContentInfo` with a permissive
35
+ * envelope (non-strict DER: CMS encoders often leave certificate sets
36
+ * unsorted), reading only the `encapContentInfo`: the certificates, CRLs and
37
+ * signer infos are skipped undecoded, so no set in them costs memory past its
38
+ * bytes. Requires `eContentType` to be `id-ct-TSTInfo`, then decodes the
39
+ * `eContent` with {@link decodeTstInfo} and `options`.
40
+ *
41
+ * Complexity: O(token).
42
+ *
43
+ * @throws {TspFormatError} With a position relative to the token for an
44
+ * envelope fault, or relative to the `eContent` octets (the message starts
45
+ * with `TSTInfo:`) for a `TSTInfo` fault. A BER indefinite-length token is
46
+ * refused, with a message saying so.
47
+ */
48
+ export function readTstInfoUnverified(token, options = {}) {
49
+ const part = "TimeStampToken";
50
+ checkTokenEnvelope_(token.encoded, 0);
51
+ const { element, start } = encapsulatedElement_(token.encoded, part);
52
+ let encapsulated;
53
+ try {
54
+ encapsulated = decodeDer_(ENCAPSULATED_DEF_, element, false, part);
55
+ }
56
+ catch (error) {
57
+ throw shifted_(error, start);
58
+ }
59
+ if (!oidEqual(encapsulated.eContentType, idCtTstInfo)) {
60
+ throw new TspFormatError(`${part}: eContentType ${oidToDotted(encapsulated.eContentType)}, expected id-ct-TSTInfo`, undefined);
61
+ }
62
+ if (encapsulated.eContent === undefined) {
63
+ throw new TspFormatError(`${part}: no eContent`, undefined);
64
+ }
65
+ return decodeTstInfo(encapsulated.eContent, options);
66
+ }
67
+ /** A TspFormatError's position moved by `offset`; anything else unchanged. */
68
+ function shifted_(error, offset) {
69
+ return error instanceof TspFormatError && error.position !== undefined
70
+ ? new TspFormatError(error.message, error.position + offset, {
71
+ cause: error.cause,
72
+ })
73
+ : error;
74
+ }
75
+ /**
76
+ * The `encapContentInfo` element of a token whose envelope checked out, and
77
+ * where it starts: the SignedData's version and digest algorithm set are passed
78
+ * over by tag, what follows by framing alone.
79
+ */
80
+ function encapsulatedElement_(bytes, part) {
81
+ try {
82
+ const contentInfo = new BerReader(bytes, "ber").enter();
83
+ contentInfo.skip();
84
+ const explicit = contentInfo.enter();
85
+ const signedData = explicit.enter();
86
+ for (const [tagNumber, name] of [
87
+ [2, "version"],
88
+ [17, "digestAlgorithms"],
89
+ [16, "encapContentInfo"],
90
+ ]) {
91
+ signedData.peekHeader();
92
+ if (signedData.tagClass !== "universal" ||
93
+ signedData.tagNumber !== tagNumber) {
94
+ throw new TspFormatError(`${part}: the SignedData ${name} is missing`, signedData.offset);
95
+ }
96
+ if (tagNumber !== 16) {
97
+ signedData.skip();
98
+ }
99
+ }
100
+ const start = signedData.offset;
101
+ const element = signedData.readElement();
102
+ while (!signedData.atEnd) {
103
+ signedData.skip();
104
+ }
105
+ signedData.finish();
106
+ explicit.finish();
107
+ contentInfo.finish();
108
+ return { element, start };
109
+ }
110
+ catch (error) {
111
+ throw error instanceof DecodingError
112
+ ? toTspFormatError_(error, part)
113
+ : error;
114
+ }
115
+ }
116
+ /**
117
+ * Checks `bytes` is one `ContentInfo` of type `id-signedData`, positions
118
+ * shifted by `offset` (where the token sits in a larger message).
119
+ */
120
+ export function checkTokenEnvelope_(bytes, offset) {
121
+ const part = "TimeStampToken";
122
+ let contentInfo;
123
+ try {
124
+ contentInfo = decodeDer_(CONTENT_INFO_DEF_, bytes, false, part);
125
+ }
126
+ catch (error) {
127
+ throw shifted_(error, offset);
128
+ }
129
+ if (!oidEqual(contentInfo.contentType, idSignedData)) {
130
+ throw new TspFormatError(`${part}: content type ${oidToDotted(contentInfo.contentType)}, expected id-signedData`, offset);
131
+ }
132
+ const content = contentInfo.content.encoded;
133
+ if (content[0] !== SEQUENCE_IDENTIFIER) {
134
+ throw new TspFormatError(`${part}: the SignedData content is not a SEQUENCE`, offset + bytes.length - content.length);
135
+ }
136
+ }
137
+ //# sourceMappingURL=token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,iBAAiB,EACjB,6BAA6B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EAAE,aAAa,EAAgB,MAAM,eAAe,CAAC;AAE5D,sCAAsC;AACtC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC,MAAM,iBAAiB,GAAG,GAAG,CAAC,iBAAiB,CAAC,CAAC;AACjD,MAAM,iBAAiB,GAAG,GAAG,CAAC,6BAA6B,CAAC,CAAC;AAY7D;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAiB;IACrD,mBAAmB,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAC9B,OAAO,EAAE,OAAO,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;AAC3C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,qBAAqB,CACpC,KAAqB,EACrB,OAAO,GAAqB,EAAE;IAE9B,MAAM,IAAI,GAAG,gBAAgB,CAAC;IAC9B,mBAAmB,CAAC,KAAK,CAAC,OAA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ACV,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAiB,EAAE,MAAc;IACpE,MAAM,IAAI,GAAG,gBAAgB,CAAC;IAC9B,IAAI,WAAW,CAAC;IAChB,IAAI,CAAC;QACJ,WAAW,GAAG,UAAU,CAAC,iBAAiB,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,WAAW,EAAE,YAAY,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,cAAc,CACvB,GAAG,IAAI,kBAAkB,WAAW,CAAC,WAAW,CAAC,WAAW,CAAC,0BAA0B,EACvF,MAAM,CACN,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,OAAQ,CAAC;IAC7C,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,mBAAmB,EAAE,CAAC;QACxC,MAAM,IAAI,cAAc,CACvB,GAAG,IAAI,4CAA4C,EACnD,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CACtC,CAAC;IACH,CAAC;AACF,CAAC"}
@@ -0,0 +1,94 @@
1
+ import type { ObjectIdentifier } from "@ac-kit/format-oid";
2
+ import type { MessageImprint } from "./message-imprint.js";
3
+ import type { TspDecodeOptions, TspExtension } from "./request.js";
4
+ /**
5
+ * A UTC `GeneralizedTime`, as a `TSTInfo`'s `genTime` is. The same fields as
6
+ * `@ac-kit/format-asn1`'s `GeneralizedTimeValue`, restated so this entry point
7
+ * does not load that package's schema types.
8
+ */
9
+ export interface UtcGeneralizedTime {
10
+ readonly year: number;
11
+ readonly month: number;
12
+ readonly day: number;
13
+ readonly hour: number;
14
+ readonly minute: number;
15
+ readonly second: number;
16
+ /**
17
+ * The fractional-second digits exactly as encoded (`"5"` for `.5`); absent
18
+ * when the time has none.
19
+ */
20
+ readonly fractionDigits?: string;
21
+ }
22
+ /**
23
+ * How far the true time may be from `genTime`, either way (RFC 3161 §2.4.2).
24
+ * `millis` and `micros` are 1 to 999 when present.
25
+ */
26
+ export interface Accuracy {
27
+ readonly seconds?: number;
28
+ readonly millis?: number;
29
+ readonly micros?: number;
30
+ }
31
+ /**
32
+ * A `TSTInfo`, the content a TSA signs (RFC 3161 §2.4.2). The version is always
33
+ * v1, so it is not a field.
34
+ *
35
+ * Nothing about this value is authenticated by itself: it is what the bytes
36
+ * say. Only the `tstInfo` of a {@link VerifiedTimeStampToken}, decoded from the
37
+ * `eContent` bytes the CMS signature covers, is evidence.
38
+ */
39
+ export interface TstInfo {
40
+ readonly policy: ObjectIdentifier;
41
+ readonly messageImprint: MessageImprint;
42
+ readonly serialNumber: bigint;
43
+ readonly genTime: UtcGeneralizedTime;
44
+ readonly accuracy?: Accuracy;
45
+ readonly ordering: boolean;
46
+ readonly nonce?: bigint;
47
+ /**
48
+ * The complete DER of the `GeneralName` inside `[0]`; typed decoding belongs
49
+ * to an X.509 package.
50
+ */
51
+ readonly tsa?: Uint8Array<ArrayBuffer>;
52
+ /** Never empty when present. */
53
+ readonly extensions?: readonly TspExtension[];
54
+ }
55
+ /** An interval of instants, both ends included. */
56
+ export interface TimeWindow {
57
+ readonly earliest: Temporal.Instant;
58
+ readonly latest: Temporal.Instant;
59
+ }
60
+ /** `genTime` and the interval its accuracy allows. */
61
+ export interface TstInfoTimeInterval extends TimeWindow {
62
+ readonly genTime: Temporal.Instant;
63
+ }
64
+ /**
65
+ * Decodes the DER of a `TSTInfo` — the `eContent` of a time-stamp token, or of
66
+ * whatever a CMS verifier hands over once the signature checked out.
67
+ *
68
+ * Strict by default, as RFC 3161 requires DER of a `TSTInfo` and every token
69
+ * observed (OpenSSL's and FreeTSA's) complies; a signature covers these exact
70
+ * bytes either way, so `strict: false` changes what is accepted, never what is
71
+ * signed. Even then, `millis` or `micros` of 0 are the only range relaxation.
72
+ *
73
+ * Complexity: O(bytes).
74
+ *
75
+ * @throws {TspFormatError} For malformed DER (canonical-form violations too,
76
+ * unless `strict` is `false`); a version other than 1; a `genTime` that is
77
+ * not UTC; `millis` or `micros` outside 1–999 (0–999 when not strict);
78
+ * `seconds` negative or above `Number.MAX_SAFE_INTEGER`; a `tsa` that is not
79
+ * a `GeneralName` alternative (context tags [0] to [8], with the DER form of
80
+ * each when strict); empty `extensions`.
81
+ */
82
+ export declare function decodeTstInfo(bytes: Uint8Array, options?: TspDecodeOptions): TstInfo;
83
+ /**
84
+ * `genTime` and the interval `genTime ± accuracy`, where RFC 3161 places the
85
+ * true time. With no `accuracy` the interval is `genTime` alone: the RFC lets
86
+ * the accuracy be known "by other means", so widen the comparison window
87
+ * instead. A fraction finer than a nanosecond is rounded outwards, and both
88
+ * ends are clamped to `Temporal.Instant`'s range.
89
+ *
90
+ * Complexity: O(fraction digits). Never throws for a value from
91
+ * {@link decodeTstInfo}.
92
+ */
93
+ export declare function tstInfoTimeInterval(tstInfo: TstInfo): TstInfoTimeInterval;
94
+ //# sourceMappingURL=tst-info.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tst-info.d.ts","sourceRoot":"","sources":["../src/tst-info.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAS3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGnE;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,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AAO,GAAE,gBAAqB,GAC5B,OAAO,CA6CT;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,mBAAmB,CAezE"}
@@ -0,0 +1,140 @@
1
+ import { decodeDer_ } from "./_decode.js";
2
+ import { clampedInstant_, generalizedTimeEpochNanoseconds_, } from "./_generalized-time.js";
3
+ import { algorithmIdentifierFromDer_, extensionsFromDer_ } from "./_pkix.js";
4
+ import { TspFormatError } from "./errors.js";
5
+ import { tstInfoSchema } from "./schema.js";
6
+ const NANOSECONDS_PER_SECOND = 1000000000n;
7
+ const NANOSECONDS_PER_MILLISECOND = 1000000n;
8
+ const NANOSECONDS_PER_MICROSECOND = 1000n;
9
+ /**
10
+ * Decodes the DER of a `TSTInfo` — the `eContent` of a time-stamp token, or of
11
+ * whatever a CMS verifier hands over once the signature checked out.
12
+ *
13
+ * Strict by default, as RFC 3161 requires DER of a `TSTInfo` and every token
14
+ * observed (OpenSSL's and FreeTSA's) complies; a signature covers these exact
15
+ * bytes either way, so `strict: false` changes what is accepted, never what is
16
+ * signed. Even then, `millis` or `micros` of 0 are the only range relaxation.
17
+ *
18
+ * Complexity: O(bytes).
19
+ *
20
+ * @throws {TspFormatError} For malformed DER (canonical-form violations too,
21
+ * unless `strict` is `false`); a version other than 1; a `genTime` that is
22
+ * not UTC; `millis` or `micros` outside 1–999 (0–999 when not strict);
23
+ * `seconds` negative or above `Number.MAX_SAFE_INTEGER`; a `tsa` that is not
24
+ * a `GeneralName` alternative (context tags [0] to [8], with the DER form of
25
+ * each when strict); empty `extensions`.
26
+ */
27
+ export function decodeTstInfo(bytes, options = {}) {
28
+ const part = "TSTInfo";
29
+ const strict = options.strict ?? true;
30
+ const value = decodeDer_(tstInfoSchema, bytes, strict, part);
31
+ if (value.version !== 1n) {
32
+ throw new TspFormatError(`${part}: version ${value.version}, expected 1`, undefined);
33
+ }
34
+ if (value.genTime.utcOffsetMinutes !== 0) {
35
+ throw new TspFormatError(`${part}: genTime must be UTC (a trailing Z)`, undefined);
36
+ }
37
+ const tsa = value.tsa?.encoded;
38
+ if (tsa !== undefined && !isGeneralNameIdentifier_(tsa[0], strict)) {
39
+ throw new TspFormatError(`${part}: tsa is not a GeneralName (context tag [0] to [8])`, undefined);
40
+ }
41
+ const accuracy = value.accuracy === undefined
42
+ ? undefined
43
+ : accuracyFromDer_(value.accuracy, strict, part);
44
+ return {
45
+ policy: value.policy,
46
+ messageImprint: {
47
+ hashAlgorithm: algorithmIdentifierFromDer_(value.messageImprint.hashAlgorithm),
48
+ hashedMessage: new Uint8Array(value.messageImprint.hashedMessage),
49
+ },
50
+ serialNumber: value.serialNumber,
51
+ genTime: utcGeneralizedTime_(value.genTime),
52
+ ...(accuracy === undefined ? {} : { accuracy }),
53
+ ordering: value.ordering ?? false,
54
+ ...(value.nonce === undefined ? {} : { nonce: value.nonce }),
55
+ ...(tsa === undefined ? {} : { tsa: new Uint8Array(tsa) }),
56
+ ...(value.extensions === undefined
57
+ ? {}
58
+ : { extensions: extensionsFromDer_(value.extensions, part) }),
59
+ };
60
+ }
61
+ /**
62
+ * `genTime` and the interval `genTime ± accuracy`, where RFC 3161 places the
63
+ * true time. With no `accuracy` the interval is `genTime` alone: the RFC lets
64
+ * the accuracy be known "by other means", so widen the comparison window
65
+ * instead. A fraction finer than a nanosecond is rounded outwards, and both
66
+ * ends are clamped to `Temporal.Instant`'s range.
67
+ *
68
+ * Complexity: O(fraction digits). Never throws for a value from
69
+ * {@link decodeTstInfo}.
70
+ */
71
+ export function tstInfoTimeInterval(tstInfo) {
72
+ const accuracy = tstInfo.accuracy;
73
+ const width = accuracy === undefined
74
+ ? 0n
75
+ : BigInt(accuracy.seconds ?? 0) * NANOSECONDS_PER_SECOND +
76
+ BigInt(accuracy.millis ?? 0) * NANOSECONDS_PER_MILLISECOND +
77
+ BigInt(accuracy.micros ?? 0) * NANOSECONDS_PER_MICROSECOND;
78
+ const lower = generalizedTimeEpochNanoseconds_(tstInfo.genTime, false);
79
+ const upper = generalizedTimeEpochNanoseconds_(tstInfo.genTime, true);
80
+ return {
81
+ genTime: clampedInstant_(lower),
82
+ earliest: clampedInstant_(lower - width),
83
+ latest: clampedInstant_(upper + width),
84
+ };
85
+ }
86
+ function accuracyFromDer_(value, strict, part) {
87
+ const smallest = strict ? 1n : 0n;
88
+ const fields = {};
89
+ if (value.seconds !== undefined) {
90
+ if (value.seconds < 0n || value.seconds > BigInt(Number.MAX_SAFE_INTEGER)) {
91
+ throw new TspFormatError(`${part}: accuracy seconds ${value.seconds} out of range`, undefined);
92
+ }
93
+ fields.seconds = Number(value.seconds);
94
+ }
95
+ for (const name of ["millis", "micros"]) {
96
+ const field = value[name];
97
+ if (field === undefined) {
98
+ continue;
99
+ }
100
+ if (field < smallest || field > 999n) {
101
+ throw new TspFormatError(`${part}: accuracy ${name} ${field} outside ${smallest}..999`, undefined);
102
+ }
103
+ fields[name] = Number(field);
104
+ }
105
+ return fields;
106
+ }
107
+ function utcGeneralizedTime_(value) {
108
+ const { year, month, day, hour, minute, second, fractionDigits } = value;
109
+ return {
110
+ year,
111
+ month,
112
+ day,
113
+ hour,
114
+ minute,
115
+ second,
116
+ ...(fractionDigits ? { fractionDigits } : {}),
117
+ };
118
+ }
119
+ /**
120
+ * The identifier octets of the nine `GeneralName` alternatives (RFC 5280
121
+ * §4.2.1.6, implicit tags): otherName, x400Address and ediPartyName are
122
+ * implicitly tagged SEQUENCEs and directoryName an explicitly tagged CHOICE, so
123
+ * constructed; the strings, the address and the OID are primitive.
124
+ */
125
+ const GENERAL_NAME_IDENTIFIERS = new Set([
126
+ 0xa0, 0x81, 0x82, 0xa3, 0xa4, 0xa5, 0x86, 0x87, 0x88,
127
+ ]);
128
+ const CONTEXT_CLASS = 0x80;
129
+ const CLASS_MASK = 0xc0;
130
+ const TAG_NUMBER_MASK = 0x1f;
131
+ const LAST_GENERAL_NAME_TAG = 8;
132
+ /** Strict: the DER identifier; otherwise any form of context tag 0–8. */
133
+ function isGeneralNameIdentifier_(identifier, strict) {
134
+ if (strict) {
135
+ return GENERAL_NAME_IDENTIFIERS.has(identifier);
136
+ }
137
+ return ((identifier & CLASS_MASK) === CONTEXT_CLASS &&
138
+ (identifier & TAG_NUMBER_MASK) <= LAST_GENERAL_NAME_TAG);
139
+ }
140
+ //# sourceMappingURL=tst-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tst-info.js","sourceRoot":"","sources":["../src/tst-info.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EACN,eAAe,EACf,gCAAgC,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAmE5C,MAAM,sBAAsB,GAAG,WAAc,CAAC;AAC9C,MAAM,2BAA2B,GAAG,QAAU,CAAC;AAC/C,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAE1C;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,aAAa,CAC5B,KAAiB,EACjB,OAAO,GAAqB,EAAE;IAE9B,MAAM,IAAI,GAAG,SAAS,CAAC;IACvB,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;IACtC,MAAM,KAAK,GAAG,UAAU,CAAC,aAAa,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAC7D,IAAI,KAAK,CAAC,OAAO,KAAK,EAAE,EAAE,CAAC;QAC1B,MAAM,IAAI,cAAc,CACvB,GAAG,IAAI,aAAa,KAAK,CAAC,OAAO,cAAc,EAC/C,SAAS,CACT,CAAC;IACH,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,gBAAgB,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,c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AAE,IAAI,EAAE,IAAI,EAAE,IAAI;CACpD,CAAC,CAAC;AACH,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,yEAAyE;AACzE,SAAS,wBAAwB,CAChC,UAAkB,EAClB,MAAe;IAEf,IAAI,MAAM,EAAE,CAAC;QACZ,OAAO,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,CACN,CAAC,UAAU,GAAG,UAAU,CAAC,KAAK,aAAa;QAC3C,CAAC,UAAU,GAAG,eAAe,CAAC,IAAI,qBAAqB,CACvD,CAAC;AACH,CAAC"}
@@ -0,0 +1,110 @@
1
+ import { type SignedDataVerificationFailureReason } from "@ac-kit/cred-cms";
2
+ import type { TspDecodeOptions } from "./request.js";
3
+ import type { TimeStampToken } from "./token.js";
4
+ import { type TstInfo } from "./tst-info.js";
5
+ /** Revocation checking of the TSA certificate's path, over given CRLs only. */
6
+ export interface TimeStampRevocationOptions {
7
+ /** DER CRLs, beside those the token carries. Nothing is ever fetched. */
8
+ readonly crls: readonly Uint8Array[];
9
+ /**
10
+ * `"require"` (the default): every certificate of the path needs a CRL;
11
+ * `"ifAvailable"`: an unknown status passes, a revoked certificate fails.
12
+ */
13
+ readonly mode?: "require" | "ifAvailable";
14
+ /** DER certificates of separate CRL issuers. */
15
+ readonly certificates?: readonly Uint8Array[];
16
+ }
17
+ /** Options of {@link verifyTimeStampToken}. */
18
+ export interface TimeStampTokenVerificationOptions {
19
+ /**
20
+ * The DER certificates of the TSA roots trusted: every path must start at
21
+ * one. No root store ships.
22
+ */
23
+ readonly trustAnchors: readonly Uint8Array[];
24
+ /**
25
+ * Untrusted DER certificates: the TSA's own when the token carries none (a
26
+ * request without `certReq`), intermediates.
27
+ */
28
+ readonly certificates?: readonly Uint8Array[];
29
+ /**
30
+ * The token must carry the TSA certificate, as RFC 3161 §2.4.1 requires of an
31
+ * answer to a request with `certReq`. Default false.
32
+ */
33
+ readonly requireCertificate?: boolean;
34
+ /** Accept SHA-1 in the signature or the certificate path. Default false. */
35
+ readonly allowSha1?: boolean;
36
+ /** The smallest RSA modulus accepted, in bits. Default 2048. */
37
+ readonly minimumRsaModulusBits?: number;
38
+ /** Check the revocation of the TSA certificate's path. */
39
+ readonly revocation?: TimeStampRevocationOptions;
40
+ /** How the `TSTInfo` is decoded (strict DER by default). */
41
+ readonly tstInfo?: TspDecodeOptions;
42
+ }
43
+ /**
44
+ * A time-stamp token whose CMS signature, TSA certificate and certificate path
45
+ * at `genTime` verified: the only type in this package that is evidence.
46
+ */
47
+ export interface VerifiedTimeStampToken {
48
+ readonly valid: true;
49
+ readonly token: TimeStampToken;
50
+ /** The `TSTInfo` the TSA signed, decoded from the verified bytes. */
51
+ readonly tstInfo: TstInfo;
52
+ /** `genTime`, the time the path was validated at. */
53
+ readonly genTime: Temporal.Instant;
54
+ /** The DER of the TSA certificate that signed. */
55
+ readonly tsaCertificate: Uint8Array;
56
+ /**
57
+ * The certification path, DER, from the certificate the trust anchor issued
58
+ * to the TSA certificate.
59
+ */
60
+ readonly certificatePath: readonly Uint8Array[];
61
+ }
62
+ /**
63
+ * Why {@link verifyTimeStampToken} refused a token:
64
+ *
65
+ * - `malformed`: not a CMS SignedData, or a `TSTInfo` that does not decode;
66
+ * - `signerCount`: other than one SignerInfo (RFC 3161 §2.4.1);
67
+ * - `tsaNameMismatch`: a `tsa` field naming none of the TSA certificate's subject
68
+ * names (RFC 3161 §2.4.2);
69
+ * - `certificateNotIncluded`: `requireCertificate` and the token does not carry
70
+ * the TSA certificate;
71
+ * - The CMS verification's reasons (`@ac-kit/cred-cms`): among them
72
+ * `contentTypeMismatch` (not `id-ct-TSTInfo`), `missingSigningCertificate`
73
+ * and `signingCertificateMismatch` (the ESS attribute RFC 3161 and RFC 5816
74
+ * require), `signature`, and `path` (which includes the critical, sole
75
+ * `id-kp-timeStamping` extended key usage of RFC 3161 §2.3 and validity at
76
+ * `genTime`).
77
+ */
78
+ export type TimeStampTokenVerificationFailureReason = SignedDataVerificationFailureReason | "signerCount" | "tsaNameMismatch" | "certificateNotIncluded";
79
+ /** A refused time-stamp token. */
80
+ export interface TimeStampTokenVerificationFailure {
81
+ readonly valid: false;
82
+ readonly reason: TimeStampTokenVerificationFailureReason;
83
+ readonly message: string;
84
+ /** For `path`: the path validation's reason (`expired`, `extendedKeyUsage`…). */
85
+ readonly pathFailureReason?: string;
86
+ /** For `signature`: why the signature was refused. */
87
+ readonly signatureFailureReason?: string;
88
+ }
89
+ /** The result of {@link verifyTimeStampToken}. */
90
+ export type TimeStampTokenVerification = VerifiedTimeStampToken | TimeStampTokenVerificationFailure;
91
+ /**
92
+ * Verifies a time-stamp token (RFC 3161 §2.4, RFC 5816) with
93
+ * `@ac-kit/cred-cms`: one SignerInfo; an `eContentType` of `id-ct-TSTInfo`; the
94
+ * CMS signature, ECDSA or RSA alike; the ESS SigningCertificate or
95
+ * SigningCertificateV2 attribute naming the signer's certificate; that
96
+ * certificate's path to one of `trustAnchors`, valid at the token's own
97
+ * `genTime`, with a critical `id-kp-timeStamping` as its only extended key
98
+ * usage; the `tsa` name, when present, one of the certificate's names. The
99
+ * `TSTInfo` returned is decoded from the very bytes the signature covers.
100
+ *
101
+ * It does not check that the token answers a request: run
102
+ * {@link checkTstInfoConsistency} on the verified `tstInfo` for that. Nothing is
103
+ * fetched.
104
+ *
105
+ * Complexity: O(token) plus the signature and path verifications.
106
+ *
107
+ * @throws {RangeError} When a trust anchor is not a DER certificate.
108
+ */
109
+ export declare function verifyTimeStampToken(token: TimeStampToken, options: TimeStampTokenVerificationOptions): Promise<TimeStampTokenVerification>;
110
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AACA,OAAO,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AAO,EAAE,QAAQ,CAAC,OAAO,CAAC;IACnC,kDAAkD;IAClD,QAAQ,CAAC,cAAc,EAAE,UAAU,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,UAAU,EAAE,CAAC;CAChD;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,uCAAuC,GAChD,mCAAmC,GACnC,aAAa,GACb,iBAAiB,GACjB,wBAAwB,CAAC;AAE5B,kCAAkC;AAClC,MAAM,WAAW,iCAAiC;IACjD,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,uCAAuC,CAAC;IACzD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,iFAAiF;IACjF,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,sDAAsD;IACtD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACzC;AAED,kDAAkD;AAClD,MAAM,MAAM,0BAA0B,GACnC,sBAAsB,GACtB,iCAAiC,CAAC;AAsDrC;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,oBAAoB,CACzC,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,iCAAiC,GACxC,OAAO,CAAC,0BAA0B,CAAC,CAmIrC"}
package/dist/verify.js ADDED
@@ -0,0 +1,160 @@
1
+ import { bytesIsEqual } from "@ac-kit/core";
2
+ import { CmsError, parseSignedData, verifySignedData, } from "@ac-kit/cred-cms";
3
+ import { GeneralNameSchema, nameEqual, trustAnchorFromCertificate, } from "@ac-kit/cred-x509";
4
+ import { ref } from "@ac-kit/format-asn1";
5
+ import { derDecode, derEncode } from "@ac-kit/format-asn1/der";
6
+ import { oidEqual, oidToDotted } from "@ac-kit/format-oid";
7
+ import { idCtTstInfo, idKpTimeStamping } from "./constants.js";
8
+ import { TspFormatError } from "./errors.js";
9
+ import { decodeTstInfo, tstInfoTimeInterval, } from "./tst-info.js";
10
+ const GENERAL_NAME_DEF_ = ref(GeneralNameSchema);
11
+ function failure_(reason, message) {
12
+ return Object.freeze({ valid: false, reason, message });
13
+ }
14
+ function anchors_(certificates) {
15
+ return certificates.map((certificate, index) => {
16
+ try {
17
+ return trustAnchorFromCertificate(certificate);
18
+ }
19
+ catch (error) {
20
+ throw new RangeError(`verifyTimeStampToken: trust anchor ${index} is not a certificate`, { cause: error });
21
+ }
22
+ });
23
+ }
24
+ // RFC 3161 §2.4.2: the tsa name "MUST correspond to one of the subject names
25
+ // included in the certificate": the subject as a directoryName, or a subject
26
+ // alternative name.
27
+ function tsaNameMatches_(tsa, certificate) {
28
+ let name;
29
+ try {
30
+ name = derDecode(GENERAL_NAME_DEF_, tsa, false);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ if (name.kind === "directoryName" &&
36
+ nameEqual(name.value, certificate.subject)) {
37
+ return true;
38
+ }
39
+ return (certificate.decodedExtensions.subjectAltName ?? []).some((alternative) => alternative.kind === "directoryName" && name.kind === "directoryName"
40
+ ? nameEqual(alternative.value, name.value)
41
+ : bytesIsEqual(derEncode(GENERAL_NAME_DEF_, alternative), tsa));
42
+ }
43
+ /**
44
+ * Verifies a time-stamp token (RFC 3161 §2.4, RFC 5816) with
45
+ * `@ac-kit/cred-cms`: one SignerInfo; an `eContentType` of `id-ct-TSTInfo`; the
46
+ * CMS signature, ECDSA or RSA alike; the ESS SigningCertificate or
47
+ * SigningCertificateV2 attribute naming the signer's certificate; that
48
+ * certificate's path to one of `trustAnchors`, valid at the token's own
49
+ * `genTime`, with a critical `id-kp-timeStamping` as its only extended key
50
+ * usage; the `tsa` name, when present, one of the certificate's names. The
51
+ * `TSTInfo` returned is decoded from the very bytes the signature covers.
52
+ *
53
+ * It does not check that the token answers a request: run
54
+ * {@link checkTstInfoConsistency} on the verified `tstInfo` for that. Nothing is
55
+ * fetched.
56
+ *
57
+ * Complexity: O(token) plus the signature and path verifications.
58
+ *
59
+ * @throws {RangeError} When a trust anchor is not a DER certificate.
60
+ */
61
+ export async function verifyTimeStampToken(token, options) {
62
+ const trustAnchors = anchors_(options.trustAnchors);
63
+ let signedData;
64
+ try {
65
+ signedData = parseSignedData(token.encoded);
66
+ }
67
+ catch (error) {
68
+ if (error instanceof CmsError) {
69
+ return failure_(error.reason, `TimeStampToken: ${error.message}`);
70
+ }
71
+ throw error;
72
+ }
73
+ if (!oidEqual(signedData.contentType, idCtTstInfo)) {
74
+ return failure_("contentTypeMismatch", `TimeStampToken: eContentType ${oidToDotted(signedData.contentType)}, expected id-ct-TSTInfo`);
75
+ }
76
+ if (signedData.signerInfos.length !== 1) {
77
+ return failure_("signerCount", `TimeStampToken: ${signedData.signerInfos.length} signers, RFC 3161 §2.4.1 allows the TSA's alone`);
78
+ }
79
+ if (signedData.content === undefined) {
80
+ return failure_("missingContent", "TimeStampToken: no eContent");
81
+ }
82
+ let tstInfo;
83
+ try {
84
+ tstInfo = decodeTstInfo(signedData.content, options.tstInfo);
85
+ }
86
+ catch (error) {
87
+ if (error instanceof TspFormatError) {
88
+ return failure_("malformed", error.message);
89
+ }
90
+ throw error;
91
+ }
92
+ const genTime = tstInfoTimeInterval(tstInfo).genTime;
93
+ const result = await verifySignedData(signedData, {
94
+ trustAnchors,
95
+ time: genTime,
96
+ certificates: options.certificates ?? [],
97
+ expectedContentType: idCtTstInfo,
98
+ requireSigningCertificate: true,
99
+ extendedKeyUsage: {
100
+ usage: idKpTimeStamping,
101
+ allowAnyExtendedKeyUsage: false,
102
+ requirePresent: true,
103
+ requireCritical: true,
104
+ requireSole: true,
105
+ },
106
+ signaturePolicy: {
107
+ ...(options.allowSha1 === undefined
108
+ ? {}
109
+ : { allowSha1: options.allowSha1 }),
110
+ ...(options.minimumRsaModulusBits === undefined
111
+ ? {}
112
+ : { minimumRsaModulusBits: options.minimumRsaModulusBits }),
113
+ },
114
+ ...(options.revocation === undefined
115
+ ? {}
116
+ : {
117
+ revocation: {
118
+ crls: options.revocation.crls,
119
+ ...(options.revocation.mode === undefined
120
+ ? {}
121
+ : { mode: options.revocation.mode }),
122
+ ...(options.revocation.certificates === undefined
123
+ ? {}
124
+ : { certificates: options.revocation.certificates }),
125
+ },
126
+ }),
127
+ });
128
+ if (!result.valid) {
129
+ return Object.freeze({
130
+ valid: false,
131
+ reason: result.reason,
132
+ message: `TimeStampToken: ${result.message}`,
133
+ ...(result.pathFailure === undefined
134
+ ? {}
135
+ : { pathFailureReason: result.pathFailure.reason }),
136
+ ...(result.signatureFailure === undefined
137
+ ? {}
138
+ : { signatureFailureReason: result.signatureFailure }),
139
+ });
140
+ }
141
+ const signer = result.signers[0];
142
+ if (options.requireCertificate === true &&
143
+ !signedData.certificates.some((choice) => choice.kind === "certificate" &&
144
+ bytesIsEqual(choice.certificate.der, signer.certificate.der))) {
145
+ return failure_("certificateNotIncluded", "TimeStampToken: the TSA certificate is not in the token (RFC 3161 §2.4.1, certReq)");
146
+ }
147
+ if (tstInfo.tsa !== undefined &&
148
+ !tsaNameMatches_(tstInfo.tsa, signer.certificate)) {
149
+ return failure_("tsaNameMismatch", "TimeStampToken: the tsa field names none of the TSA certificate's names (RFC 3161 §2.4.2)");
150
+ }
151
+ return Object.freeze({
152
+ valid: true,
153
+ token,
154
+ tstInfo,
155
+ genTime,
156
+ tsaCertificate: Uint8Array.from(signer.certificate.der),
157
+ certificatePath: Object.freeze(signer.path.path.map((certificate) => Uint8Array.from(certificate.der))),
158
+ });
159
+ }
160
+ //# sourceMappingURL=verify.js.map