@nakafa/aksara-contracts 0.49.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 (105) 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 +251 -213
  7. package/dist/assessment/item.d.ts +44 -7
  8. package/dist/assessment/item.js +19 -9
  9. package/dist/assessment/joint.d.ts +62 -0
  10. package/dist/assessment/joint.js +85 -0
  11. package/dist/assessment/paper.d.ts +22 -2
  12. package/dist/assessment/profile.d.ts +6 -0
  13. package/dist/assessment/scoring.d.ts +55 -2
  14. package/dist/assessment/scoring.js +63 -8
  15. package/dist/assessment/stimulus.d.ts +3 -3
  16. package/dist/assessment/stimulus.js +2 -2
  17. package/dist/errors.d.ts +3 -1
  18. package/dist/graph/family.d.ts +6 -2
  19. package/dist/graph/identity.d.ts +3 -1
  20. package/dist/hash/digest.d.ts +10 -0
  21. package/dist/hash/digest.js +40 -0
  22. package/dist/hash/stream.d.ts +12 -0
  23. package/dist/hash/stream.js +27 -0
  24. package/dist/hash/text.d.ts +3 -1
  25. package/dist/hash/text.js +2 -15
  26. package/dist/locale.d.ts +9 -0
  27. package/dist/locale.js +25 -1
  28. package/dist/preview/auth.d.ts +4 -2
  29. package/dist/preview/auth.js +26 -12
  30. package/dist/program/snapshot/digest.d.ts +3 -1
  31. package/dist/program/snapshot/digest.js +14 -22
  32. package/dist/program/snapshot/hash.d.ts +6 -2
  33. package/dist/program/snapshot/hash.js +10 -21
  34. package/dist/projection/digest.d.ts +11 -9
  35. package/dist/projection/digest.js +23 -32
  36. package/dist/projection/hash.d.ts +222 -2
  37. package/dist/projection/hash.js +6 -8
  38. package/dist/projection/verify.d.ts +16 -6
  39. package/dist/question/item.d.ts +3 -1
  40. package/dist/question/item.js +3 -1
  41. package/dist/quran/notes.d.ts +3 -1
  42. package/dist/quran/provenance.d.ts +6 -2
  43. package/dist/quran/provenance.js +8 -15
  44. package/dist/quran/snapshot/digest.d.ts +9 -5
  45. package/dist/quran/snapshot/digest.js +33 -41
  46. package/dist/quran/snapshot/hash.d.ts +3 -1
  47. package/dist/quran/snapshot/hash.js +9 -15
  48. package/dist/quran/snapshot/row/hash.d.ts +3 -1
  49. package/dist/quran/snapshot/row/hash.js +2 -8
  50. package/dist/release/digest.d.ts +10 -8
  51. package/dist/release/digest.js +22 -31
  52. package/dist/release/hash.d.ts +3 -1
  53. package/dist/release/hash.js +3 -8
  54. package/dist/release/items.d.ts +25 -9
  55. package/dist/release/items.js +12 -3
  56. package/dist/release/policy.d.ts +3 -1
  57. package/dist/release/result/digest.d.ts +23 -13
  58. package/dist/release/result/digest.js +20 -29
  59. package/dist/release/rollback/digest.d.ts +16 -10
  60. package/dist/release/rollback/digest.js +25 -32
  61. package/dist/release/route/digest.d.ts +10 -8
  62. package/dist/release/route/digest.js +22 -31
  63. package/dist/release/route/verify.d.ts +16 -6
  64. package/dist/release/route/verify.js +8 -2
  65. package/dist/release/snapshot/evidence/requirement.d.ts +3 -1
  66. package/dist/release/snapshot/evidence/tryout.d.ts +1 -1
  67. package/dist/release/snapshot/evidence/tryout.js +1 -1
  68. package/dist/release/snapshot/evidence.d.ts +1 -1
  69. package/dist/release/snapshot/verify.d.ts +19 -7
  70. package/dist/release/snapshot/verify.js +20 -18
  71. package/dist/release/verify.d.ts +9 -3
  72. package/dist/renderer/compatibility.d.ts +6 -2
  73. package/dist/renderer/compatibility.js +3 -1
  74. package/dist/renderer/contract.d.ts +9 -3
  75. package/dist/renderer/contract.js +3 -1
  76. package/dist/runtime/error.d.ts +3 -1
  77. package/dist/runtime/protected/verify.d.ts +1 -1
  78. package/dist/runtime/verify.d.ts +2 -2
  79. package/dist/runtime/verify.js +2 -1
  80. package/dist/signature/key.d.ts +21 -0
  81. package/dist/signature/key.js +104 -0
  82. package/dist/signature/spec.d.ts +18 -6
  83. package/dist/signature/spec.js +16 -4
  84. package/dist/transport/request.d.ts +728 -728
  85. package/dist/transport/response.d.ts +26 -26
  86. package/dist/tryout/canonical.d.ts +11 -1
  87. package/dist/tryout/canonical.js +6 -10
  88. package/dist/tryout/closure/accounting.d.ts +3 -1
  89. package/dist/tryout/digest.d.ts +12 -6
  90. package/dist/tryout/digest.js +21 -14
  91. package/dist/tryout/hash/catalog.d.ts +228 -3
  92. package/dist/tryout/hash/catalog.js +5 -7
  93. package/dist/tryout/hash/content.d.ts +113 -2
  94. package/dist/tryout/hash/content.js +10 -8
  95. package/dist/tryout/hash/placement.d.ts +236 -5
  96. package/dist/tryout/hash/placement.js +7 -8
  97. package/dist/tryout/runtime/hash.d.ts +3 -1
  98. package/dist/tryout/runtime/hash.js +3 -1
  99. package/dist/tryout/runtime/source.d.ts +3 -1
  100. package/dist/tryout/runtime/verify.d.ts +13 -5
  101. package/dist/tryout/runtime/verify.js +1 -1
  102. package/dist/tryout/scoring.d.ts +3 -1
  103. package/dist/tryout/snapshot/hash.d.ts +45 -4
  104. package/dist/tryout/snapshot/hash.js +9 -7
  105. package/package.json +22 -2
@@ -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 }))));
package/dist/locale.d.ts CHANGED
@@ -13,6 +13,15 @@ export declare function makeAppLocale<const Code extends AppLocaleCode>(code: Co
13
13
  /** Language delivered by content whose language may differ from the app shell. */
14
14
  export declare const DeliveryLanguageSchema: Schema.brand<Schema.Literals<readonly ["en", "id", "de"]>, "@NakafaAI/AksaraDeliveryLanguage">;
15
15
  export type DeliveryLanguage = typeof DeliveryLanguageSchema.Type;
16
+ /**
17
+ * A language of one assessment text, as a BCP 47 tag in its canonical form, such
18
+ * as `ar`, `de-CH`, or `zh-Hant-TW`. Unlike `DeliveryLanguageSchema`, it is not
19
+ * limited to the app locales, so a school can write in any language. The
20
+ * direction of a text is not stored: the renderer takes it from the script of
21
+ * each text.
22
+ */
23
+ export declare const ContentLanguageSchema: Schema.brand<Schema.String, "@NakafaAI/AksaraContentLanguage">;
24
+ export type ContentLanguage = typeof ContentLanguageSchema.Type;
16
25
  /** Locale identity of one immutable compiled content artifact. */
17
26
  export declare const ArtifactLocaleSchema: Schema.brand<Schema.Literals<readonly ["en", "id", "de"]>, "@NakafaAI/AksaraArtifactLocale">;
18
27
  export type ArtifactLocale = typeof ArtifactLocaleSchema.Type;
package/dist/locale.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Schema } from "effect";
1
+ import { Array as Arr, Option, Schema } from "effect";
2
2
  import { hasCanonicalOrder } from "#contracts/canonical";
3
3
  /** Stable locale codes supported by the current Aksara contract. */
4
4
  export const AppLocaleCodeSchema = Schema.Literals(["en", "id", "de"]);
@@ -16,6 +16,30 @@ export function makeAppLocale(code) {
16
16
  }
17
17
  /** Language delivered by content whose language may differ from the app shell. */
18
18
  export const DeliveryLanguageSchema = AppLocaleCodeSchema.pipe(Schema.brand("@NakafaAI/AksaraDeliveryLanguage"));
19
+ const CONTENT_LANGUAGE_BRAND = "@NakafaAI/AksaraContentLanguage";
20
+ /** Intl's canonical form of one language tag, or nothing when Intl rejects the tag. */
21
+ const canonicalLanguageTag = Option.liftThrowable((tag) => Intl.getCanonicalLocales(tag));
22
+ /**
23
+ * Explains why a string is not a content language. Intl must accept it, and it
24
+ * must already be the one canonical form that Intl writes for it. A tag that
25
+ * Intl rewrites names that form, so the author can correct it.
26
+ */
27
+ function contentLanguageIssue(tag) {
28
+ return Option.match(Option.flatMap(canonicalLanguageTag(tag), Arr.head), {
29
+ onNone: () => "Expected a well-formed BCP 47 language tag.",
30
+ onSome: (canonical) => canonical === tag
31
+ ? undefined
32
+ : `Expected the canonical language tag "${canonical}".`,
33
+ });
34
+ }
35
+ /**
36
+ * A language of one assessment text, as a BCP 47 tag in its canonical form, such
37
+ * as `ar`, `de-CH`, or `zh-Hant-TW`. Unlike `DeliveryLanguageSchema`, it is not
38
+ * limited to the app locales, so a school can write in any language. The
39
+ * direction of a text is not stored: the renderer takes it from the script of
40
+ * each text.
41
+ */
42
+ export const ContentLanguageSchema = Schema.String.pipe(Schema.check(Schema.makeFilter(contentLanguageIssue)), Schema.brand(CONTENT_LANGUAGE_BRAND));
19
43
  /** Locale identity of one immutable compiled content artifact. */
20
44
  export const ArtifactLocaleSchema = AppLocaleCodeSchema.pipe(Schema.brand("@NakafaAI/AksaraArtifactLocale"));
21
45
  /** Canonical locale order used by every active-locale subset. */
@@ -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
  }
@@ -1,6 +1,5 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Effect, Schema } from "effect";
3
- import { Sha256HashSchema } from "#contracts/ids";
2
+ import { hashText } from "#contracts/hash/text";
4
3
  import { CurriculumRouteRecordSchema, canonicalizeProgramSnapshotRow, LearningProgramRecordSchema, } from "#contracts/program/snapshot/row";
5
4
  import { PROGRAM_SNAPSHOT_FORMAT, ProgramSnapshotSchema, } from "#contracts/program/snapshot/spec";
6
5
  import { encodeJsonText } from "#contracts/text/json";
@@ -26,19 +25,14 @@ export function canonicalizeProgramSnapshot(input) {
26
25
  });
27
26
  }
28
27
  /** Creates the content-addressed identity of one complete program snapshot. */
29
- export const makeProgramSnapshot = Effect.fn("AksaraContracts.makeProgramSnapshot")((input) => Effect.try({
30
- catch: () => new ProgramSnapshotHashError(),
31
- try: () => {
32
- const snapshotId = Sha256HashSchema.make(`sha256:${createHash("sha256")
33
- .update(`${SNAPSHOT_DOMAIN}\n${canonicalizeProgramSnapshot(input)}`)
34
- .digest("hex")}`);
35
- return ProgramSnapshotSchema.make({
36
- ...input,
37
- format: PROGRAM_SNAPSHOT_FORMAT,
38
- snapshotId,
39
- });
40
- },
41
- }));
28
+ export const makeProgramSnapshot = Effect.fn("AksaraContracts.makeProgramSnapshot")(function* (input) {
29
+ const snapshotId = yield* hashText(`${SNAPSHOT_DOMAIN}\n${canonicalizeProgramSnapshot(input)}`).pipe(Effect.mapError(() => new ProgramSnapshotHashError()));
30
+ return ProgramSnapshotSchema.make({
31
+ ...input,
32
+ format: PROGRAM_SNAPSHOT_FORMAT,
33
+ snapshotId,
34
+ });
35
+ });
42
36
  /** Recomputes the content identity of one stored current snapshot. */
43
37
  export function verifyProgramSnapshotHash(snapshot) {
44
38
  const { format: _format, snapshotId: _snapshotId, ...facts } = snapshot;
@@ -46,12 +40,7 @@ export function verifyProgramSnapshotHash(snapshot) {
46
40
  }
47
41
  /** Hashes one current program or curriculum row. */
48
42
  function hashProgramRow(record) {
49
- return Effect.try({
50
- catch: () => new ProgramRowHashError({ scope: "row" }),
51
- try: () => Sha256HashSchema.make(`sha256:${createHash("sha256")
52
- .update(`${ROW_DOMAIN}\n${canonicalizeProgramSnapshotRow(record)}`)
53
- .digest("hex")}`),
54
- });
43
+ return hashText(`${ROW_DOMAIN}\n${canonicalizeProgramSnapshotRow(record)}`).pipe(Effect.mapError(() => new ProgramRowHashError({ scope: "row" })));
55
44
  }
56
45
  /** Creates one authenticated current program record. */
57
46
  export const makeProgramSnapshotRow = Effect.fn("AksaraContracts.makeProgramSnapshotRow")(function* (row) {
@@ -3,28 +3,30 @@ import { ReleaseIdSchema } from "#contracts/ids";
3
3
  import { type ContentProjection } from "#contracts/projection/spec";
4
4
  declare const ProjectionHashError_base: Schema.Class<ProjectionHashError, Schema.TaggedStruct<"ProjectionHashError", {
5
5
  readonly releaseId: Schema.brand<Schema.String, "@NakafaAI/AksaraReleaseId">;
6
- }>, import("effect/Cause").YieldableError>;
6
+ }>, import("effect/Cause").YieldableError & {
7
+ readonly brand: unique symbol;
8
+ }>;
7
9
  /** SHA-256 computation failed before projection integrity was established. */
8
10
  export declare class ProjectionHashError extends ProjectionHashError_base {
9
11
  }
10
- /** Keeps Node hash state private while exposing only canonical counters. */
12
+ /** Keeps the digest stream private while exposing only canonical counters. */
11
13
  declare class ProjectionDigestState {
12
14
  #private;
13
15
  count: number;
14
- /** Initializes a domain-separated incremental projection hash. */
16
+ /** Starts one domain-separated projection digest. */
15
17
  constructor();
16
18
  /** Adds one canonical projection to this invocation-owned digest. */
17
19
  update(projection: ContentProjection): void;
18
- /** Consumes the hash and returns its branded immutable identity. */
19
- digest(): string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">;
20
+ /** Digests the complete stream once and returns its branded immutable identity. */
21
+ digest(): Effect.Effect<string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">, import("effect/PlatformError").PlatformError, never>;
20
22
  }
21
23
  /** Creates a fresh domain-separated projection digest state. */
22
- export declare function createProjectionDigest(releaseId: typeof ReleaseIdSchema.Type): Effect.Effect<ProjectionDigestState, ProjectionHashError, never>;
24
+ export declare const createProjectionDigest: Effect.Effect<ProjectionDigestState, never, never>;
23
25
  /** Adds one canonical content projection to an incremental digest. */
24
- export declare function updateProjectionDigest(releaseId: typeof ReleaseIdSchema.Type, state: ProjectionDigestState, projection: ContentProjection): Effect.Effect<ProjectionDigestState, ProjectionHashError, never>;
25
- /** Finalizes one incremental projection digest with typed hash failures. */
26
+ export declare function updateProjectionDigest(state: ProjectionDigestState, projection: ContentProjection): Effect.Effect<ProjectionDigestState, never, never>;
27
+ /** Finalizes one projection digest with a typed hash failure. */
26
28
  export declare function finalizeProjectionDigest(releaseId: typeof ReleaseIdSchema.Type, state: ProjectionDigestState): Effect.Effect<string & import("effect/Brand").Brand<"@NakafaAI/AksaraSha256Hash">, ProjectionHashError, never>;
27
- /** Digests a projection stream without retaining its content bodies. */
29
+ /** Digests a projection stream. Its canonical bytes are held until one Web Crypto digest runs. */
28
30
  export declare const digestProjections: <E, R>(releaseId: string & import("effect/Brand").Brand<"@NakafaAI/AksaraReleaseId">, projections: Stream.Stream<{
29
31
  readonly appLocale: ("de" | "en" | "id") & import("effect/Brand").Brand<"@NakafaAI/AksaraAppLocale">;
30
32
  readonly articleRouteSlug: string & import("effect/Brand").Brand<"@NakafaAI/AksaraArticleRouteSlug">;
@@ -1,59 +1,50 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Effect, Schema, Stream } from "effect";
3
- import { ReleaseIdSchema, Sha256HashSchema, } from "#contracts/ids";
2
+ import { DigestStream } from "#contracts/hash/stream";
3
+ import { ReleaseIdSchema } from "#contracts/ids";
4
4
  import { canonicalizeContentProjection, } from "#contracts/projection/spec";
5
5
  const CONTENT_PROJECTION_DIGEST_DOMAIN = "nakafa.aksara.content-projections";
6
6
  /** SHA-256 computation failed before projection integrity was established. */
7
7
  export class ProjectionHashError extends Schema.TaggedError()("ProjectionHashError", { releaseId: ReleaseIdSchema }) {
8
8
  }
9
- /** Keeps Node hash state private while exposing only canonical counters. */
9
+ /** Keeps the digest stream private while exposing only canonical counters. */
10
10
  class ProjectionDigestState {
11
- #hash = createHash("sha256");
11
+ #stream = new DigestStream();
12
12
  count = 0;
13
- /** Initializes a domain-separated incremental projection hash. */
13
+ /** Starts one domain-separated projection digest. */
14
14
  constructor() {
15
- this.#hash.update(CONTENT_PROJECTION_DIGEST_DOMAIN);
16
- this.#hash.update("\n");
15
+ this.#stream.add(CONTENT_PROJECTION_DIGEST_DOMAIN);
16
+ this.#stream.add("\n");
17
17
  }
18
18
  /** Adds one canonical projection to this invocation-owned digest. */
19
19
  update(projection) {
20
- this.#hash.update(canonicalizeContentProjection(projection));
21
- this.#hash.update("\n");
20
+ this.#stream.add(canonicalizeContentProjection(projection));
21
+ this.#stream.add("\n");
22
22
  this.count += 1;
23
23
  }
24
- /** Consumes the hash and returns its branded immutable identity. */
24
+ /** Digests the complete stream once and returns its branded immutable identity. */
25
25
  digest() {
26
- return Sha256HashSchema.make(`sha256:${this.#hash.digest("hex")}`);
26
+ return this.#stream.digest();
27
27
  }
28
28
  }
29
29
  /** Creates a fresh domain-separated projection digest state. */
30
- export function createProjectionDigest(releaseId) {
31
- return Effect.try({
32
- catch: () => new ProjectionHashError({ releaseId }),
33
- try: () => new ProjectionDigestState(),
34
- });
35
- }
30
+ export const createProjectionDigest = Effect.sync(() => new ProjectionDigestState());
36
31
  /** Adds one canonical content projection to an incremental digest. */
37
- export function updateProjectionDigest(releaseId, state, projection) {
38
- return Effect.try({
39
- catch: () => new ProjectionHashError({ releaseId }),
40
- try: () => {
41
- state.update(projection);
42
- return state;
43
- },
32
+ export function updateProjectionDigest(state, projection) {
33
+ return Effect.sync(() => {
34
+ state.update(projection);
35
+ return state;
44
36
  });
45
37
  }
46
- /** Finalizes one incremental projection digest with typed hash failures. */
38
+ /** Finalizes one projection digest with a typed hash failure. */
47
39
  export function finalizeProjectionDigest(releaseId, state) {
48
- return Effect.try({
49
- catch: () => new ProjectionHashError({ releaseId }),
50
- try: () => state.digest(),
51
- });
40
+ return state
41
+ .digest()
42
+ .pipe(Effect.mapError(() => new ProjectionHashError({ releaseId })));
52
43
  }
53
- /** Digests a projection stream without retaining its content bodies. */
44
+ /** Digests a projection stream. Its canonical bytes are held until one Web Crypto digest runs. */
54
45
  export const digestProjections = Effect.fn("AksaraContracts.digestProjections")(function* (releaseId, projections) {
55
- const initial = yield* createProjectionDigest(releaseId);
56
- const state = yield* projections.pipe(Stream.runFoldEffect(() => initial, (current, projection) => updateProjectionDigest(releaseId, current, projection)));
46
+ const initial = yield* createProjectionDigest;
47
+ const state = yield* projections.pipe(Stream.runFoldEffect(() => initial, (current, projection) => updateProjectionDigest(current, projection)));
57
48
  const digest = yield* finalizeProjectionDigest(releaseId, state);
58
49
  return { count: state.count, digest };
59
50
  });