@nakafa/aksara-contracts 0.50.0 → 0.51.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.
Files changed (94) hide show
  1. package/dist/artifact/integrity.d.ts +15 -2
  2. package/dist/artifact/integrity.js +3 -15
  3. package/dist/artifact/limits.js +3 -4
  4. package/dist/artifact/source.js +4 -8
  5. package/dist/artifact/spec.d.ts +30 -10
  6. package/dist/assessment/hash.d.ts +3 -1
  7. package/dist/assessment/paper.d.ts +3 -1
  8. package/dist/errors.d.ts +3 -1
  9. package/dist/graph/family.d.ts +6 -2
  10. package/dist/graph/identity.d.ts +3 -1
  11. package/dist/hash/digest.d.ts +10 -0
  12. package/dist/hash/digest.js +40 -0
  13. package/dist/hash/stream.d.ts +12 -0
  14. package/dist/hash/stream.js +27 -0
  15. package/dist/hash/text.d.ts +3 -1
  16. package/dist/hash/text.js +2 -15
  17. package/dist/preview/auth.d.ts +4 -2
  18. package/dist/preview/auth.js +26 -12
  19. package/dist/program/snapshot/digest.d.ts +3 -1
  20. package/dist/program/snapshot/digest.js +14 -22
  21. package/dist/program/snapshot/hash.d.ts +6 -2
  22. package/dist/program/snapshot/hash.js +10 -21
  23. package/dist/projection/digest.d.ts +11 -9
  24. package/dist/projection/digest.js +23 -32
  25. package/dist/projection/hash.d.ts +222 -2
  26. package/dist/projection/hash.js +6 -8
  27. package/dist/projection/verify.d.ts +16 -6
  28. package/dist/question/item.d.ts +3 -1
  29. package/dist/question/item.js +3 -1
  30. package/dist/quran/notes.d.ts +3 -1
  31. package/dist/quran/provenance.d.ts +6 -2
  32. package/dist/quran/provenance.js +8 -15
  33. package/dist/quran/snapshot/digest.d.ts +9 -5
  34. package/dist/quran/snapshot/digest.js +33 -41
  35. package/dist/quran/snapshot/hash.d.ts +3 -1
  36. package/dist/quran/snapshot/hash.js +9 -15
  37. package/dist/quran/snapshot/row/hash.d.ts +3 -1
  38. package/dist/quran/snapshot/row/hash.js +2 -8
  39. package/dist/release/digest.d.ts +10 -8
  40. package/dist/release/digest.js +22 -31
  41. package/dist/release/hash.d.ts +3 -1
  42. package/dist/release/hash.js +3 -8
  43. package/dist/release/items.d.ts +25 -9
  44. package/dist/release/items.js +12 -3
  45. package/dist/release/policy.d.ts +3 -1
  46. package/dist/release/result/digest.d.ts +23 -13
  47. package/dist/release/result/digest.js +20 -29
  48. package/dist/release/rollback/digest.d.ts +16 -10
  49. package/dist/release/rollback/digest.js +25 -32
  50. package/dist/release/route/digest.d.ts +10 -8
  51. package/dist/release/route/digest.js +22 -31
  52. package/dist/release/route/verify.d.ts +16 -6
  53. package/dist/release/route/verify.js +8 -2
  54. package/dist/release/snapshot/evidence/requirement.d.ts +3 -1
  55. package/dist/release/snapshot/evidence/tryout.d.ts +1 -1
  56. package/dist/release/snapshot/evidence/tryout.js +1 -1
  57. package/dist/release/snapshot/evidence.d.ts +1 -1
  58. package/dist/release/snapshot/verify.d.ts +19 -7
  59. package/dist/release/snapshot/verify.js +20 -18
  60. package/dist/release/verify.d.ts +9 -3
  61. package/dist/renderer/compatibility.d.ts +6 -2
  62. package/dist/renderer/compatibility.js +3 -1
  63. package/dist/renderer/contract.d.ts +9 -3
  64. package/dist/renderer/contract.js +3 -1
  65. package/dist/runtime/error.d.ts +3 -1
  66. package/dist/runtime/protected/verify.d.ts +1 -1
  67. package/dist/runtime/verify.d.ts +2 -2
  68. package/dist/runtime/verify.js +2 -1
  69. package/dist/signature/key.d.ts +21 -0
  70. package/dist/signature/key.js +104 -0
  71. package/dist/signature/spec.d.ts +18 -6
  72. package/dist/signature/spec.js +16 -4
  73. package/dist/transport/request.d.ts +728 -728
  74. package/dist/transport/response.d.ts +26 -26
  75. package/dist/tryout/canonical.d.ts +11 -1
  76. package/dist/tryout/canonical.js +6 -10
  77. package/dist/tryout/closure/accounting.d.ts +3 -1
  78. package/dist/tryout/digest.d.ts +12 -6
  79. package/dist/tryout/digest.js +21 -14
  80. package/dist/tryout/hash/catalog.d.ts +228 -3
  81. package/dist/tryout/hash/catalog.js +5 -7
  82. package/dist/tryout/hash/content.d.ts +113 -2
  83. package/dist/tryout/hash/content.js +10 -8
  84. package/dist/tryout/hash/placement.d.ts +236 -5
  85. package/dist/tryout/hash/placement.js +7 -8
  86. package/dist/tryout/runtime/hash.d.ts +3 -1
  87. package/dist/tryout/runtime/hash.js +3 -1
  88. package/dist/tryout/runtime/source.d.ts +3 -1
  89. package/dist/tryout/runtime/verify.d.ts +13 -5
  90. package/dist/tryout/runtime/verify.js +1 -1
  91. package/dist/tryout/scoring.d.ts +3 -1
  92. package/dist/tryout/snapshot/hash.d.ts +45 -4
  93. package/dist/tryout/snapshot/hash.js +9 -7
  94. package/package.json +18 -2
@@ -1,8 +1,21 @@
1
1
  import { Effect } from "effect";
2
2
  import { ArtifactHashComputationError, ArtifactHashMismatchError, ArtifactVerificationDecodeError } from "#contracts/artifact/spec";
3
- import { type CompiledContentPayload } from "#contracts/content";
4
3
  /** Computes the immutable identity of one canonical compiled payload. */
5
- export declare function hashCompiledContentPayload(payload: CompiledContentPayload): string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">;
4
+ export declare const hashCompiledContentPayload: (payload: {
5
+ readonly artifactLocale: ("de" | "en" | "id") & import("effect/Brand").Brand<"@NakafaAI/AksaraArtifactLocale">;
6
+ readonly byteLength: number;
7
+ readonly compiledCode: string;
8
+ readonly compilerConfigHash: string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">;
9
+ readonly compilerVersion: "0.1.0";
10
+ readonly contentKey: string & import("effect/Brand").Brand<"@NakafaAI/AksaraContentKey">;
11
+ readonly format: "mdx-function-body";
12
+ readonly mdxCompilerVersion: "3.1.1";
13
+ readonly plainText: string;
14
+ readonly rawMdx: string;
15
+ readonly rendererDomain: "ai-ds" | "biology" | "chemistry" | "mathematics" | "physics" | "politics" | "site" | "snbt-general" | "snbt-math" | "snbt-plain" | "snbt-quant" | "tka-math";
16
+ readonly requiredComponents: readonly string[];
17
+ readonly sourceHash: string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">;
18
+ }) => Effect.Effect<string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">, ArtifactHashComputationError, never>;
6
19
  /** Strictly authenticates artifact integrity without renderer compatibility. */
7
20
  export declare const verifySignedContentArtifactIntegrity: (input: unknown) => Effect.Effect<{
8
21
  readonly artifactHash: string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">;
@@ -1,24 +1,12 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Effect, Schema } from "effect";
3
2
  import { validateArtifactByteIntegrity } from "#contracts/artifact/limits";
4
3
  import { verifyCompiledContentSourceHash } from "#contracts/artifact/source";
5
4
  import { ArtifactHashComputationError, ArtifactHashMismatchError, ArtifactVerificationDecodeError, } from "#contracts/artifact/spec";
6
5
  import { canonicalizeCompiledContentPayload, canonicalizeContentArtifactSigningInput, SignedContentArtifactSchema, } from "#contracts/content";
7
- import { Sha256HashSchema } from "#contracts/ids";
6
+ import { hashText } from "#contracts/hash/text";
8
7
  import { verifyEd25519Signature } from "#contracts/signature/verify";
9
8
  /** Computes the immutable identity of one canonical compiled payload. */
10
- export function hashCompiledContentPayload(payload) {
11
- return Sha256HashSchema.make(`sha256:${createHash("sha256")
12
- .update(canonicalizeCompiledContentPayload(payload))
13
- .digest("hex")}`);
14
- }
15
- /** Computes an artifact hash while preserving typed computation failures. */
16
- function hashPayload(payload) {
17
- return Effect.try({
18
- catch: () => new ArtifactHashComputationError({ contentKey: payload.contentKey }),
19
- try: () => hashCompiledContentPayload(payload),
20
- });
21
- }
9
+ export const hashCompiledContentPayload = Effect.fn("AksaraContracts.hashCompiledContentPayload")((payload) => hashText(canonicalizeCompiledContentPayload(payload)).pipe(Effect.mapError(() => new ArtifactHashComputationError({ contentKey: payload.contentKey }))));
22
10
  /** Confirms that an artifact envelope identifies its canonical payload. */
23
11
  function validateArtifactHash(artifact, actualHash) {
24
12
  if (artifact.artifactHash === actualHash) {
@@ -33,7 +21,7 @@ function validateArtifactHash(artifact, actualHash) {
33
21
  /** Verifies immutable bytes, hashes, source, and signature without a renderer. */
34
22
  function authenticateSignedArtifact(artifact) {
35
23
  return Effect.gen(function* () {
36
- const actualHash = yield* hashPayload(artifact.payload);
24
+ const actualHash = yield* hashCompiledContentPayload(artifact.payload);
37
25
  yield* validateArtifactHash(artifact, actualHash);
38
26
  yield* verifyEd25519Signature({
39
27
  keyId: artifact.keyId,
@@ -1,11 +1,10 @@
1
- import { Buffer } from "node:buffer";
2
1
  import { Effect } from "effect";
3
2
  import { ArtifactCompiledByteLengthMismatchError, ArtifactPayloadFieldByteLimitError, ArtifactVerificationByteLimitError, } from "#contracts/artifact/spec";
4
3
  import { canonicalizeCompiledContentPayload, canonicalizeSignedContentArtifact, } from "#contracts/content";
5
4
  import { MAX_CANONICAL_PAYLOAD_BYTES, MAX_COMPILED_CODE_BYTES, MAX_PLAIN_TEXT_BYTES, MAX_RAW_MDX_BYTES, MAX_SIGNED_ARTIFACT_BYTES, } from "#contracts/limits";
6
5
  /** Rejects a complete signed artifact envelope above its wire ceiling. */
7
6
  function enforceSignedWireLimit(artifact) {
8
- const actualBytes = Buffer.byteLength(canonicalizeSignedContentArtifact(artifact), "utf8");
7
+ const actualBytes = new TextEncoder().encode(canonicalizeSignedContentArtifact(artifact)).byteLength;
9
8
  if (actualBytes <= MAX_SIGNED_ARTIFACT_BYTES) {
10
9
  return Effect.void;
11
10
  }
@@ -16,7 +15,7 @@ function enforceSignedWireLimit(artifact) {
16
15
  }
17
16
  /** Rejects one authenticated payload field above its shared ceiling. */
18
17
  function enforcePayloadFieldLimit(payload, field, value, maxBytes) {
19
- const actualBytes = Buffer.byteLength(value, "utf8");
18
+ const actualBytes = new TextEncoder().encode(value).byteLength;
20
19
  if (actualBytes <= maxBytes) {
21
20
  return Effect.void;
22
21
  }
@@ -31,7 +30,7 @@ function enforcePayloadFieldLimit(payload, field, value, maxBytes) {
31
30
  export const validateArtifactByteIntegrity = Effect.fn("AksaraContracts.validateArtifactByteIntegrity")(function* (artifact) {
32
31
  yield* enforceSignedWireLimit(artifact);
33
32
  const { payload } = artifact;
34
- const compiledBytes = Buffer.byteLength(payload.compiledCode, "utf8");
33
+ const compiledBytes = new TextEncoder().encode(payload.compiledCode).byteLength;
35
34
  if (payload.byteLength !== compiledBytes) {
36
35
  return yield* new ArtifactCompiledByteLengthMismatchError({
37
36
  actualBytes: compiledBytes,
@@ -1,15 +1,11 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Effect } from "effect";
3
2
  import { ArtifactSourceHashComputationError, ArtifactSourceHashMismatchError, } from "#contracts/artifact/spec";
4
- import { Sha256HashSchema } from "#contracts/ids";
3
+ import { hashText } from "#contracts/hash/text";
5
4
  /** Computes the authenticated hash of the complete authored MDX source. */
6
5
  function hashAuthoredSource(payload) {
7
- return Effect.try({
8
- catch: () => new ArtifactSourceHashComputationError({
9
- contentKey: payload.contentKey,
10
- }),
11
- try: () => Sha256HashSchema.make(`sha256:${createHash("sha256").update(payload.rawMdx).digest("hex")}`),
12
- });
6
+ return hashText(payload.rawMdx).pipe(Effect.mapError(() => new ArtifactSourceHashComputationError({
7
+ contentKey: payload.contentKey,
8
+ })));
13
9
  }
14
10
  /** Verifies that sourceHash identifies the complete authenticated raw MDX. */
15
11
  export const verifyCompiledContentSourceHash = Effect.fn("AksaraContracts.verifyCompiledContentSourceHash")((payload) => hashAuthoredSource(payload).pipe(Effect.flatMap((actualHash) => {
@@ -35,14 +35,18 @@ export declare const ArtifactVerificationRequestSchema: Schema.Struct<{
35
35
  export type ArtifactVerificationRequest = typeof ArtifactVerificationRequestSchema.Type;
36
36
  declare const ArtifactVerificationDecodeError_base: Schema.Class<ArtifactVerificationDecodeError, Schema.TaggedStruct<"ArtifactVerificationDecodeError", {
37
37
  readonly message: Schema.Literal<"Artifact verification input does not satisfy its exact wire contract.">;
38
- }>, import("effect/Cause").YieldableError>;
38
+ }>, import("effect/Cause").YieldableError & {
39
+ readonly brand: unique symbol;
40
+ }>;
39
41
  /** Unknown artifact input did not exactly satisfy the verification contract. */
40
42
  export declare class ArtifactVerificationDecodeError extends ArtifactVerificationDecodeError_base {
41
43
  }
42
44
  declare const ArtifactVerificationByteLimitError_base: Schema.Class<ArtifactVerificationByteLimitError, Schema.TaggedStruct<"ArtifactVerificationByteLimitError", {
43
45
  readonly actualBytes: Schema.Finite;
44
46
  readonly maxBytes: Schema.Finite;
45
- }>, import("effect/Cause").YieldableError>;
47
+ }>, import("effect/Cause").YieldableError & {
48
+ readonly brand: unique symbol;
49
+ }>;
46
50
  /** A signed artifact exceeded the canonical UTF-8 wire ceiling. */
47
51
  export declare class ArtifactVerificationByteLimitError extends ArtifactVerificationByteLimitError_base {
48
52
  }
@@ -50,7 +54,9 @@ declare const ArtifactCompiledByteLengthMismatchError_base: Schema.Class<Artifac
50
54
  readonly actualBytes: Schema.Finite;
51
55
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
52
56
  readonly declaredBytes: Schema.Finite;
53
- }>, import("effect/Cause").YieldableError>;
57
+ }>, import("effect/Cause").YieldableError & {
58
+ readonly brand: unique symbol;
59
+ }>;
54
60
  /** Declared compiled bytes differ from the authenticated function body. */
55
61
  export declare class ArtifactCompiledByteLengthMismatchError extends ArtifactCompiledByteLengthMismatchError_base {
56
62
  }
@@ -59,13 +65,17 @@ declare const ArtifactPayloadFieldByteLimitError_base: Schema.Class<ArtifactPayl
59
65
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
60
66
  readonly field: Schema.Literals<readonly ["rawMdx", "compiledCode", "plainText", "canonicalPayload"]>;
61
67
  readonly maxBytes: Schema.Finite;
62
- }>, import("effect/Cause").YieldableError>;
68
+ }>, import("effect/Cause").YieldableError & {
69
+ readonly brand: unique symbol;
70
+ }>;
63
71
  /** One authenticated payload field exceeded its shared runtime ceiling. */
64
72
  export declare class ArtifactPayloadFieldByteLimitError extends ArtifactPayloadFieldByteLimitError_base {
65
73
  }
66
74
  declare const ArtifactHashComputationError_base: Schema.Class<ArtifactHashComputationError, Schema.TaggedStruct<"ArtifactHashComputationError", {
67
75
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
68
- }>, import("effect/Cause").YieldableError>;
76
+ }>, import("effect/Cause").YieldableError & {
77
+ readonly brand: unique symbol;
78
+ }>;
69
79
  /** SHA-256 computation failed before authenticity could be established. */
70
80
  export declare class ArtifactHashComputationError extends ArtifactHashComputationError_base {
71
81
  }
@@ -73,13 +83,17 @@ declare const ArtifactHashMismatchError_base: Schema.Class<ArtifactHashMismatchE
73
83
  readonly actualHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
74
84
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
75
85
  readonly expectedHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
76
- }>, import("effect/Cause").YieldableError>;
86
+ }>, import("effect/Cause").YieldableError & {
87
+ readonly brand: unique symbol;
88
+ }>;
77
89
  /** The signed artifact hash does not identify its canonical payload. */
78
90
  export declare class ArtifactHashMismatchError extends ArtifactHashMismatchError_base {
79
91
  }
80
92
  declare const ArtifactSourceHashComputationError_base: Schema.Class<ArtifactSourceHashComputationError, Schema.TaggedStruct<"ArtifactSourceHashComputationError", {
81
93
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
82
- }>, import("effect/Cause").YieldableError>;
94
+ }>, import("effect/Cause").YieldableError & {
95
+ readonly brand: unique symbol;
96
+ }>;
83
97
  /** SHA-256 could not be calculated for the authenticated authored source. */
84
98
  export declare class ArtifactSourceHashComputationError extends ArtifactSourceHashComputationError_base {
85
99
  }
@@ -87,21 +101,27 @@ declare const ArtifactSourceHashMismatchError_base: Schema.Class<ArtifactSourceH
87
101
  readonly actualHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
88
102
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
89
103
  readonly expectedHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
90
- }>, import("effect/Cause").YieldableError>;
104
+ }>, import("effect/Cause").YieldableError & {
105
+ readonly brand: unique symbol;
106
+ }>;
91
107
  /** The authenticated source hash does not identify the complete raw MDX. */
92
108
  export declare class ArtifactSourceHashMismatchError extends ArtifactSourceHashMismatchError_base {
93
109
  }
94
110
  declare const ArtifactRendererComponentMissingError_base: Schema.Class<ArtifactRendererComponentMissingError, Schema.TaggedStruct<"ArtifactRendererComponentMissingError", {
95
111
  readonly componentName: Schema.String;
96
112
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
97
- }>, import("effect/Cause").YieldableError>;
113
+ }>, import("effect/Cause").YieldableError & {
114
+ readonly brand: unique symbol;
115
+ }>;
98
116
  /** A custom component required by the artifact is absent from the renderer. */
99
117
  export declare class ArtifactRendererComponentMissingError extends ArtifactRendererComponentMissingError_base {
100
118
  }
101
119
  declare const ArtifactRendererDomainUnpublishedError_base: Schema.Class<ArtifactRendererDomainUnpublishedError, Schema.TaggedStruct<"ArtifactRendererDomainUnpublishedError", {
102
120
  readonly contentKey: Schema.brand<Schema.String, "@NakafaAI/AksaraContentKey">;
103
121
  readonly rendererDomain: Schema.Literals<readonly ["ai-ds", "biology", "chemistry", "mathematics", "physics", "politics", "site", "snbt-general", "snbt-math", "snbt-plain", "snbt-quant", "tka-math"]>;
104
- }>, import("effect/Cause").YieldableError>;
122
+ }>, import("effect/Cause").YieldableError & {
123
+ readonly brand: unique symbol;
124
+ }>;
105
125
  /** The deployed Nakafa app cannot route this artifact's renderer domain. */
106
126
  export declare class ArtifactRendererDomainUnpublishedError extends ArtifactRendererDomainUnpublishedError_base {
107
127
  }
@@ -11,7 +11,9 @@ export declare const canonicalJson: (value: unknown) => Effect.Effect<string, Sc
11
11
  declare const VersionHashMismatchError_base: Schema.Class<VersionHashMismatchError, Schema.TaggedStruct<"VersionHashMismatchError", {
12
12
  readonly actualHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
13
13
  readonly expectedHash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
14
- }>, import("effect/Cause").YieldableError>;
14
+ }>, import("effect/Cause").YieldableError & {
15
+ readonly brand: unique symbol;
16
+ }>;
15
17
  /** A stored hash is not the hash of the content that carries it. */
16
18
  export declare class VersionHashMismatchError extends VersionHashMismatchError_base {
17
19
  }
@@ -50,7 +50,9 @@ declare const PaperStimuliMismatchError_base: Schema.Class<PaperStimuliMismatchE
50
50
  readonly hash: Schema.brand<Schema.String, "@NakafaAI/AksaraSha256Hash">;
51
51
  readonly id: Schema.brand<Schema.String, "@NakafaAI/AksaraStimulusId">;
52
52
  }>>;
53
- }>, import("effect/Cause").YieldableError>;
53
+ }>, import("effect/Cause").YieldableError & {
54
+ readonly brand: unique symbol;
55
+ }>;
54
56
  /**
55
57
  * A paper does not list the stimulus versions that its item versions use.
56
58
  * `missing` are the ones the items use and the paper leaves out, and `unused`
package/dist/errors.d.ts CHANGED
@@ -3,7 +3,9 @@ declare const ContractDecodeError_base: Schema.Class<ContractDecodeError, Schema
3
3
  readonly cause: Schema.Unknown;
4
4
  readonly contract: Schema.Trimmed;
5
5
  readonly message: Schema.Trimmed;
6
- }>, import("effect/Cause").YieldableError>;
6
+ }>, import("effect/Cause").YieldableError & {
7
+ readonly brand: unique symbol;
8
+ }>;
7
9
  /** Describes a wire value that failed its named Effect Schema contract. */
8
10
  export declare class ContractDecodeError extends ContractDecodeError_base {
9
11
  }
@@ -13,7 +13,9 @@ export declare const LearningGraphAssetOwnerSchema: Schema.Struct<{
13
13
  export type LearningGraphAssetOwner = typeof LearningGraphAssetOwnerSchema.Type;
14
14
  declare const LearningGraphAssetFamilyError_base: Schema.Class<LearningGraphAssetFamilyError, Schema.TaggedStruct<"LearningGraphAssetFamilyError", {
15
15
  readonly assetId: Schema.String;
16
- }>, import("effect/Cause").YieldableError>;
16
+ }>, import("effect/Cause").YieldableError & {
17
+ readonly brand: unique symbol;
18
+ }>;
17
19
  /** One asset ID cannot address a supported current semantic content family. */
18
20
  export declare class LearningGraphAssetFamilyError extends LearningGraphAssetFamilyError_base {
19
21
  }
@@ -25,7 +27,9 @@ declare const LearningGraphFamilyError_base: Schema.Class<LearningGraphFamilyErr
25
27
  readonly learningObjectId: Schema.String;
26
28
  readonly lensId: Schema.String;
27
29
  }>;
28
- }>, import("effect/Cause").YieldableError>;
30
+ }>, import("effect/Cause").YieldableError & {
31
+ readonly brand: unique symbol;
32
+ }>;
29
33
  /** One graph identity does not coherently belong to a current semantic family. */
30
34
  export declare class LearningGraphFamilyError extends LearningGraphFamilyError_base {
31
35
  }
@@ -10,7 +10,9 @@ export declare const LearningGraphSegmentsSchema: Schema.Struct<{
10
10
  export type LearningGraphSegments = typeof LearningGraphSegmentsSchema.Type;
11
11
  declare const LearningGraphIdentityError_base: Schema.Class<LearningGraphIdentityError, Schema.TaggedStruct<"LearningGraphIdentityError", {
12
12
  readonly cause: Schema.Unknown;
13
- }>, import("effect/Cause").YieldableError>;
13
+ }>, import("effect/Cause").YieldableError & {
14
+ readonly brand: unique symbol;
15
+ }>;
14
16
  /** Source segments could not produce valid stable graph identities. */
15
17
  export declare class LearningGraphIdentityError extends LearningGraphIdentityError_base {
16
18
  }
@@ -0,0 +1,10 @@
1
+ import { Crypto, Effect, PlatformError } from "effect";
2
+ /**
3
+ * Web Crypto behind Effect's `Crypto` service. Every runtime that Aksara
4
+ * contracts run in has `crypto.subtle`, so digests need no runtime layer.
5
+ */
6
+ export declare const webCryptoService: Crypto.Crypto;
7
+ /** Computes the SHA-256 digest bytes of one byte sequence through Effect's Crypto service. */
8
+ export declare const digestSha256: (bytes: Uint8Array<ArrayBufferLike>) => Effect.Effect<Uint8Array<ArrayBufferLike>, PlatformError.PlatformError, never>;
9
+ /** Computes the `sha256:` identity of one byte sequence, the form every stored hash uses. */
10
+ export declare const hashBytes: (bytes: Uint8Array<ArrayBufferLike>) => Effect.Effect<string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">, PlatformError.PlatformError, never>;
@@ -0,0 +1,40 @@
1
+ import { Crypto, Effect, PlatformError } from "effect";
2
+ import { Hex } from "effect/encoding";
3
+ import { Sha256HashSchema } from "#contracts/ids";
4
+ /** Largest byte count that one `crypto.getRandomValues` call accepts. */
5
+ const RANDOM_CHUNK_BYTES = 65_536;
6
+ /**
7
+ * Web Crypto behind Effect's `Crypto` service. Every runtime that Aksara
8
+ * contracts run in has `crypto.subtle`, so digests need no runtime layer.
9
+ */
10
+ export const webCryptoService = Crypto.make({
11
+ digest: (algorithm, data) => Effect.tryPromise({
12
+ catch: (cause) => PlatformError.systemError({
13
+ _tag: "Unknown",
14
+ cause,
15
+ description: "Could not compute digest",
16
+ method: "digest",
17
+ module: "Crypto",
18
+ }),
19
+ try: () => globalThis.crypto.subtle
20
+ .digest(algorithm, new Uint8Array(data))
21
+ .then((digest) => new Uint8Array(digest)),
22
+ }),
23
+ randomBytes: (size) => {
24
+ const bytes = new Uint8Array(size);
25
+ for (let offset = 0; offset < size; offset += RANDOM_CHUNK_BYTES) {
26
+ globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + RANDOM_CHUNK_BYTES));
27
+ }
28
+ return bytes;
29
+ },
30
+ });
31
+ /** Computes the SHA-256 digest bytes of one byte sequence through Effect's Crypto service. */
32
+ export const digestSha256 = Effect.fn("AksaraContracts.digestSha256")(function* (bytes) {
33
+ const crypto = yield* Crypto.Crypto;
34
+ return yield* crypto.digest("SHA-256", bytes);
35
+ }, Effect.provideService(Crypto.Crypto, webCryptoService));
36
+ /** Computes the `sha256:` identity of one byte sequence, the form every stored hash uses. */
37
+ export const hashBytes = Effect.fn("AksaraContracts.hashBytes")(function* (bytes) {
38
+ const digest = yield* digestSha256(bytes);
39
+ return Sha256HashSchema.make(`sha256:${Hex.encode(digest)}`);
40
+ });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Collects the UTF-8 bytes of one digest stream so that Web Crypto can digest
3
+ * it in one call. Each piece is encoded on its own, exactly as an incremental
4
+ * hash encoded it, so a lone surrogate keeps the bytes it always had.
5
+ */
6
+ export declare class DigestStream {
7
+ #private;
8
+ /** Appends one piece of text in the order the stream was built. */
9
+ add(text: string): void;
10
+ /** Digests every piece in order and returns the branded sha256 identity. */
11
+ digest(): import("effect/Effect").Effect<string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">, import("effect/PlatformError").PlatformError, never>;
12
+ }
@@ -0,0 +1,27 @@
1
+ import { MutableList } from "effect";
2
+ import { hashBytes } from "#contracts/hash/digest";
3
+ /**
4
+ * Collects the UTF-8 bytes of one digest stream so that Web Crypto can digest
5
+ * it in one call. Each piece is encoded on its own, exactly as an incremental
6
+ * hash encoded it, so a lone surrogate keeps the bytes it always had.
7
+ */
8
+ export class DigestStream {
9
+ #pieces = MutableList.make();
10
+ #length = 0;
11
+ /** Appends one piece of text in the order the stream was built. */
12
+ add(text) {
13
+ const bytes = new TextEncoder().encode(text);
14
+ MutableList.append(this.#pieces, bytes);
15
+ this.#length += bytes.byteLength;
16
+ }
17
+ /** Digests every piece in order and returns the branded sha256 identity. */
18
+ digest() {
19
+ const bytes = new Uint8Array(this.#length);
20
+ let offset = 0;
21
+ for (const piece of MutableList.toArray(this.#pieces)) {
22
+ bytes.set(piece, offset);
23
+ offset += piece.byteLength;
24
+ }
25
+ return hashBytes(bytes);
26
+ }
27
+ }
@@ -1,7 +1,9 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  declare const TextHashError_base: Schema.Class<TextHashError, Schema.TaggedStruct<"TextHashError", {
3
3
  readonly cause: Schema.Unknown;
4
- }>, import("effect/Cause").YieldableError>;
4
+ }>, import("effect/Cause").YieldableError & {
5
+ readonly brand: unique symbol;
6
+ }>;
5
7
  /** Web Crypto could not hash one UTF-8 contract value. */
6
8
  export declare class TextHashError extends TextHashError_base {
7
9
  }
package/dist/hash/text.js CHANGED
@@ -1,20 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
- import { Sha256HashSchema } from "#contracts/ids";
2
+ import { hashBytes } from "#contracts/hash/digest";
3
3
  /** Web Crypto could not hash one UTF-8 contract value. */
4
4
  export class TextHashError extends Schema.TaggedError()("TextHashError", { cause: Schema.Unknown }) {
5
5
  }
6
- /** Encodes one SHA-256 digest without depending on a Node runtime. */
7
- function encodeDigest(value) {
8
- let hex = "";
9
- for (const byte of new Uint8Array(value)) {
10
- hex += byte.toString(16).padStart(2, "0");
11
- }
12
- return Sha256HashSchema.make(`sha256:${hex}`);
13
- }
14
6
  /** Hashes exact UTF-8 text through the Web Crypto contract. */
15
- export const hashText = Effect.fn("AksaraContracts.hashText")((value) => Effect.tryPromise({
16
- catch: (cause) => new TextHashError({ cause }),
17
- try: () => crypto.subtle
18
- .digest("SHA-256", new TextEncoder().encode(value))
19
- .then(encodeDigest),
20
- }));
7
+ export const hashText = Effect.fn("AksaraContracts.hashText")((value) => hashBytes(new TextEncoder().encode(value)).pipe(Effect.mapError((cause) => new TextHashError({ cause }))));
@@ -29,7 +29,9 @@ export declare const PreviewRendererResponseSchema: Schema.Struct<{
29
29
  export type PreviewRendererResponse = typeof PreviewRendererResponseSchema.Type;
30
30
  declare const PreviewRendererAuthError_base: Schema.Class<PreviewRendererAuthError, Schema.TaggedStruct<"PreviewRendererAuthError", {
31
31
  readonly reason: Schema.Literals<readonly ["compute", "invalid"]>;
32
- }>, import("effect/Cause").YieldableError>;
32
+ }>, import("effect/Cause").YieldableError & {
33
+ readonly brand: unique symbol;
34
+ }>;
33
35
  /** Renderer authentication could not be computed or did not match. */
34
36
  export declare class PreviewRendererAuthError extends PreviewRendererAuthError_base {
35
37
  }
@@ -44,7 +46,7 @@ export declare const computePreviewRendererProof: (input: {
44
46
  readonly nonce: PreviewRendererNonce;
45
47
  readonly secret: PreviewRendererSecret;
46
48
  }) => Effect.Effect<string, PreviewRendererAuthError, never>;
47
- /** Verifies one proof without exposing timing-sensitive string comparison. */
49
+ /** Verifies one proof with the HMAC verification of Web Crypto, which compares in constant time. */
48
50
  export declare const verifyPreviewRendererProof: (input: {
49
51
  readonly manifestHash: typeof Sha256HashSchema.Type;
50
52
  readonly nonce: PreviewRendererNonce;
@@ -1,6 +1,5 @@
1
- import { Buffer } from "node:buffer";
2
- import { createHmac, timingSafeEqual } from "node:crypto";
3
1
  import { Effect, Schema } from "effect";
2
+ import { Base64Url } from "effect/encoding";
4
3
  import { RendererManifestEnvelopeSchema } from "#contracts/renderer/contract";
5
4
  import { encodeJsonText } from "#contracts/text/json";
6
5
  const BASE64URL_SHA256_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
@@ -19,7 +18,9 @@ export const PreviewRendererResponseSchema = Schema.Struct({
19
18
  proof: PreviewRendererProofSchema,
20
19
  });
21
20
  /** Renderer authentication could not be computed or did not match. */
22
- export class PreviewRendererAuthError extends Schema.TaggedError()("PreviewRendererAuthError", { reason: Schema.Literals(["compute", "invalid"]) }) {
21
+ export class PreviewRendererAuthError extends Schema.TaggedError()("PreviewRendererAuthError", {
22
+ reason: Schema.Literals(["compute", "invalid"]),
23
+ }) {
23
24
  }
24
25
  /** Canonicalizes one challenge and exact validated renderer identity. */
25
26
  export function canonicalizePreviewRendererAuth(input) {
@@ -29,21 +30,34 @@ export function canonicalizePreviewRendererAuth(input) {
29
30
  input.manifestHash,
30
31
  ]);
31
32
  }
33
+ /** Imports the process-local secret as one HMAC-SHA256 key through Web Crypto. */
34
+ const importPreviewRendererKey = Effect.fn("AksaraContracts.importPreviewRendererKey")(function* (secret) {
35
+ const raw = yield* Effect.fromResult(Base64Url.decode(secret)).pipe(Effect.orDie);
36
+ return yield* Effect.tryPromise({
37
+ catch: () => new PreviewRendererAuthError({ reason: "compute" }),
38
+ try: () => globalThis.crypto.subtle.importKey("raw", raw, { hash: "SHA-256", name: "HMAC" }, false, ["sign", "verify"]),
39
+ });
40
+ });
32
41
  /** Computes one renderer response proof from a process-local secret. */
33
42
  export const computePreviewRendererProof = Effect.fn("AksaraContracts.computePreviewRendererProof")(function* (input) {
34
- return yield* Effect.try({
43
+ const key = yield* importPreviewRendererKey(input.secret);
44
+ const message = new TextEncoder().encode(canonicalizePreviewRendererAuth(input));
45
+ const tag = yield* Effect.tryPromise({
35
46
  catch: () => new PreviewRendererAuthError({ reason: "compute" }),
36
- try: () => PreviewRendererProofSchema.make(createHmac("sha256", Buffer.from(input.secret, "base64url"))
37
- .update(canonicalizePreviewRendererAuth(input))
38
- .digest("base64url")),
47
+ try: () => globalThis.crypto.subtle.sign("HMAC", key, message),
39
48
  });
49
+ return PreviewRendererProofSchema.make(Base64Url.encode(new Uint8Array(tag)));
40
50
  });
41
- /** Verifies one proof without exposing timing-sensitive string comparison. */
51
+ /** Verifies one proof with the HMAC verification of Web Crypto, which compares in constant time. */
42
52
  export const verifyPreviewRendererProof = Effect.fn("AksaraContracts.verifyPreviewRendererProof")(function* (input) {
43
- const expected = yield* computePreviewRendererProof(input);
44
- const actualBytes = Buffer.from(input.proof, "base64url");
45
- const expectedBytes = Buffer.from(expected, "base64url");
46
- if (timingSafeEqual(actualBytes, expectedBytes)) {
53
+ const key = yield* importPreviewRendererKey(input.secret);
54
+ const message = new TextEncoder().encode(canonicalizePreviewRendererAuth(input));
55
+ const tag = yield* Effect.fromResult(Base64Url.decode(input.proof)).pipe(Effect.orDie);
56
+ const valid = yield* Effect.tryPromise({
57
+ catch: () => new PreviewRendererAuthError({ reason: "compute" }),
58
+ try: () => globalThis.crypto.subtle.verify("HMAC", key, tag, message),
59
+ });
60
+ if (valid) {
47
61
  return;
48
62
  }
49
63
  return yield* new PreviewRendererAuthError({ reason: "invalid" });
@@ -6,7 +6,9 @@ import type { ProgramCounts } from "#contracts/program/snapshot/spec";
6
6
  declare const ProgramDigestError_base: Schema.Class<ProgramDigestError, Schema.TaggedStruct<"ProgramDigestError", {
7
7
  readonly code: Schema.Literals<readonly ["count", "integrity", "key", "order", "parent", "program", "route", "root", "slug"]>;
8
8
  readonly identity: Schema.String;
9
- }>, import("effect/Cause").YieldableError>;
9
+ }>, import("effect/Cause").YieldableError & {
10
+ readonly brand: unique symbol;
11
+ }>;
10
12
  /** An aggregate program stream is incomplete, duplicated, or tampered. */
11
13
  export declare class ProgramDigestError extends ProgramDigestError_base {
12
14
  }
@@ -1,6 +1,5 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Array as Arr, Effect, MutableHashMap, MutableHashSet, Option, Schema, Stream, } from "effect";
3
- import { Sha256HashSchema } from "#contracts/ids";
2
+ import { DigestStream } from "#contracts/hash/stream";
4
3
  import { curriculumNamespace, } from "#contracts/program/curriculum";
5
4
  import { ProgramRowHashError, verifyProgramSnapshotRowHash, } from "#contracts/program/snapshot/hash";
6
5
  import { canonicalizeProgramSnapshotRow, } from "#contracts/program/snapshot/row";
@@ -50,7 +49,7 @@ function isExactProgramRoot(row, program) {
50
49
  /** Keeps current locale closure, identity, and digest state in one replay. */
51
50
  class ProgramDigestState {
52
51
  #activeAppLocales;
53
- #hash = createHash("sha256").update(`${DIGEST_DOMAIN}\n`);
52
+ #stream = new DigestStream();
54
53
  #nodes = MutableHashSet.empty();
55
54
  #paths = MutableHashSet.empty();
56
55
  #programs = MutableHashMap.empty();
@@ -62,9 +61,10 @@ class ProgramDigestState {
62
61
  curriculumRowCount = 0;
63
62
  programRowCount = 0;
64
63
  sitemapCount = 0;
65
- /** Initializes one isolated replay under the signed active locale set. */
64
+ /** Starts one isolated replay under the signed active locale set. */
66
65
  constructor(activeAppLocales) {
67
66
  this.#activeAppLocales = activeAppLocales;
67
+ this.#stream.add(`${DIGEST_DOMAIN}\n`);
68
68
  }
69
69
  /** Returns source-independent count evidence collected from accepted rows. */
70
70
  counts() {
@@ -112,12 +112,11 @@ class ProgramDigestState {
112
112
  }),
113
113
  }));
114
114
  }
115
- /** Consumes the complete canonical stream digest. */
115
+ /** Digests the complete canonical stream once. */
116
116
  digest() {
117
- return Effect.try({
118
- catch: () => new ProgramRowHashError({ scope: "digest" }),
119
- try: () => Sha256HashSchema.make(`sha256:${this.#hash.digest("hex")}`),
120
- });
117
+ return this.#stream
118
+ .digest()
119
+ .pipe(Effect.mapError(() => new ProgramRowHashError({ scope: "digest" })));
121
120
  }
122
121
  /** Adds one catalog row before any current curriculum records. */
123
122
  #addProgram(record) {
@@ -185,15 +184,11 @@ class ProgramDigestState {
185
184
  }
186
185
  /** Adds canonical current record bytes and their authenticated row hash. */
187
186
  #updateDigest(record) {
188
- return Effect.try({
189
- catch: () => new ProgramRowHashError({ scope: "digest" }),
190
- try: () => {
191
- this.#hash
192
- .update(canonicalizeProgramSnapshotRow(record))
193
- .update("\0")
194
- .update(record.rowHash)
195
- .update("\n");
196
- },
187
+ return Effect.sync(() => {
188
+ this.#stream.add(canonicalizeProgramSnapshotRow(record));
189
+ this.#stream.add("\0");
190
+ this.#stream.add(record.rowHash);
191
+ this.#stream.add("\n");
197
192
  });
198
193
  }
199
194
  }
@@ -210,10 +205,7 @@ const updateProgramDigest = Effect.fn("AksaraContracts.updateProgramDigest")(fun
210
205
  });
211
206
  /** Digests a complete current program snapshot under its active locale set. */
212
207
  export const digestProgramRows = Effect.fn("AksaraContracts.digestProgramRows")(function* (input) {
213
- const state = yield* Effect.try({
214
- catch: () => new ProgramRowHashError({ scope: "digest" }),
215
- try: () => new ProgramDigestState(input.activeAppLocales),
216
- });
208
+ const state = new ProgramDigestState(input.activeAppLocales);
217
209
  yield* input.rows.pipe(Stream.runForEach((record) => updateProgramDigest(state, record)));
218
210
  yield* state.validateComplete(input.expected);
219
211
  const rowDigest = yield* state.digest();
@@ -1,13 +1,17 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { type ProgramSnapshotRow } from "#contracts/program/snapshot/row";
3
3
  import { type ProgramSnapshot, type ProgramSnapshotFacts } from "#contracts/program/snapshot/spec";
4
- declare const ProgramSnapshotHashError_base: Schema.Class<ProgramSnapshotHashError, Schema.TaggedStruct<"ProgramSnapshotHashError", {}>, import("effect/Cause").YieldableError>;
4
+ declare const ProgramSnapshotHashError_base: Schema.Class<ProgramSnapshotHashError, Schema.TaggedStruct<"ProgramSnapshotHashError", {}>, import("effect/Cause").YieldableError & {
5
+ readonly brand: unique symbol;
6
+ }>;
5
7
  /** Node could not compute a deterministic program snapshot identity. */
6
8
  export declare class ProgramSnapshotHashError extends ProgramSnapshotHashError_base {
7
9
  }
8
10
  declare const ProgramRowHashError_base: Schema.Class<ProgramRowHashError, Schema.TaggedStruct<"ProgramRowHashError", {
9
11
  readonly scope: Schema.Literals<readonly ["digest", "row"]>;
10
- }>, import("effect/Cause").YieldableError>;
12
+ }>, import("effect/Cause").YieldableError & {
13
+ readonly brand: unique symbol;
14
+ }>;
11
15
  /** Node could not compute one deterministic program row identity. */
12
16
  export declare class ProgramRowHashError extends ProgramRowHashError_base {
13
17
  }