@uglyunicorn/pie 0.1.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.
@@ -0,0 +1,111 @@
1
+ ---
2
+ description: Use Bun instead of Node.js, npm, pnpm, or vite.
3
+ globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
4
+ alwaysApply: false
5
+ ---
6
+
7
+ Default to using Bun instead of Node.js.
8
+
9
+ - Use `bun <file>` instead of `node <file>` or `ts-node <file>`
10
+ - Use `bun test` instead of `jest` or `vitest`
11
+ - Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
12
+ - Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
13
+ - Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
14
+ - Use `bunx <package> <command>` instead of `npx <package> <command>`
15
+ - Bun automatically loads .env, so don't use dotenv.
16
+
17
+ ## APIs
18
+
19
+ - `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
20
+ - `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
21
+ - `Bun.redis` for Redis. Don't use `ioredis`.
22
+ - `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
23
+ - `WebSocket` is built-in. Don't use `ws`.
24
+ - Prefer `Bun.file` over `node:fs`'s readFile/writeFile
25
+ - Bun.$`ls` instead of execa.
26
+
27
+ ## Testing
28
+
29
+ Use `bun test` to run tests.
30
+
31
+ ```ts#index.test.ts
32
+ import { test, expect } from "bun:test";
33
+
34
+ test("hello world", () => {
35
+ expect(1).toBe(1);
36
+ });
37
+ ```
38
+
39
+ ## Frontend
40
+
41
+ Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
42
+
43
+ Server:
44
+
45
+ ```ts#index.ts
46
+ import index from "./index.html"
47
+
48
+ Bun.serve({
49
+ routes: {
50
+ "/": index,
51
+ "/api/users/:id": {
52
+ GET: (req) => {
53
+ return new Response(JSON.stringify({ id: req.params.id }));
54
+ },
55
+ },
56
+ },
57
+ // optional websocket support
58
+ websocket: {
59
+ open: (ws) => {
60
+ ws.send("Hello, world!");
61
+ },
62
+ message: (ws, message) => {
63
+ ws.send(message);
64
+ },
65
+ close: (ws) => {
66
+ // handle close
67
+ }
68
+ },
69
+ development: {
70
+ hmr: true,
71
+ console: true,
72
+ }
73
+ })
74
+ ```
75
+
76
+ HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
77
+
78
+ ```html#index.html
79
+ <html>
80
+ <body>
81
+ <h1>Hello, world!</h1>
82
+ <script type="module" src="./frontend.tsx"></script>
83
+ </body>
84
+ </html>
85
+ ```
86
+
87
+ With the following `frontend.tsx`:
88
+
89
+ ```tsx#frontend.tsx
90
+ import React from "react";
91
+ import { createRoot } from "react-dom/client";
92
+
93
+ // import .css files directly and it works
94
+ import './index.css';
95
+
96
+ const root = createRoot(document.body);
97
+
98
+ export default function Frontend() {
99
+ return <h1>Hello, world!</h1>;
100
+ }
101
+
102
+ root.render(<Frontend />);
103
+ ```
104
+
105
+ Then, run index.ts
106
+
107
+ ```sh
108
+ bun --hot ./index.ts
109
+ ```
110
+
111
+ For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`.
@@ -0,0 +1,36 @@
1
+ name: Coverage
2
+
3
+ on:
4
+ push:
5
+ branches: ["main", "feature/*"]
6
+ pull_request:
7
+
8
+ concurrency:
9
+ group: ${{ github.workflow }}-${{ github.ref }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ coverage:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Checkout
17
+ uses: actions/checkout@v4
18
+
19
+ - name: Setup Bun
20
+ uses: oven-sh/setup-bun@v2
21
+ with:
22
+ bun-version: latest
23
+
24
+ - name: Install dependencies
25
+ run: bun install --frozen-lockfile
26
+
27
+ - name: Run tests with coverage (LCOV)
28
+ run: bun test --coverage --coverage-reporter=lcov
29
+
30
+ - name: Upload coverage to Codecov
31
+ uses: codecov/codecov-action@v5
32
+ with:
33
+ files: ./coverage/lcov.info
34
+ fail_ci_if_error: true
35
+ token: ${{ secrets.CODECOV_TOKEN }}
36
+ slug: uglyunicorn-eh/pie
@@ -0,0 +1,79 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches: ["main"]
6
+
7
+ concurrency:
8
+ group: ${{ github.workflow }}-${{ github.ref }}
9
+ cancel-in-progress: true
10
+
11
+ jobs:
12
+ release:
13
+ runs-on: ubuntu-latest
14
+ permissions:
15
+ contents: write
16
+ id-token: write
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+
20
+ - name: Setup Bun
21
+ uses: oven-sh/setup-bun@v2
22
+ with:
23
+ bun-version: latest
24
+
25
+ - name: Install deps
26
+ run: bun install --frozen-lockfile
27
+
28
+ - name: Read version from package.json
29
+ id: pkg
30
+ run: |
31
+ VERSION=$(bun --print 'require("./package.json").version')
32
+ echo "version=${VERSION}" >> $GITHUB_OUTPUT
33
+ echo "tag=v${VERSION}" >> $GITHUB_OUTPUT
34
+
35
+ - name: Check if tag exists
36
+ id: tagcheck
37
+ run: |
38
+ if git rev-parse "${{ steps.pkg.outputs.tag }}" >/dev/null 2>&1; then
39
+ echo "exists=true" >> $GITHUB_OUTPUT
40
+ else
41
+ echo "exists=false" >> $GITHUB_OUTPUT
42
+ fi
43
+
44
+ - name: Build
45
+ if: steps.tagcheck.outputs.exists == 'false'
46
+ run: bun run build
47
+
48
+ - name: Create tag
49
+ if: steps.tagcheck.outputs.exists == 'false'
50
+ run: |
51
+ git config user.name github-actions
52
+ git config user.email github-actions@github.com
53
+ git tag ${{ steps.pkg.outputs.tag }}
54
+ git push origin ${{ steps.pkg.outputs.tag }}
55
+
56
+ - name: Capture merge commit message
57
+ id: msg
58
+ run: |
59
+ TITLE=$(git log -1 --pretty=%s)
60
+ BODY=$(git log -1 --pretty=%b)
61
+ echo "title=${TITLE}" >> $GITHUB_OUTPUT
62
+ printf "%s" "$BODY" > body.txt
63
+
64
+ - name: Create GitHub Release
65
+ if: steps.tagcheck.outputs.exists == 'false'
66
+ uses: softprops/action-gh-release@v2
67
+ with:
68
+ tag_name: ${{ steps.pkg.outputs.tag }}
69
+ name: ${{ steps.pkg.outputs.tag }}
70
+ body_path: body.txt
71
+ env:
72
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
73
+
74
+ - name: Publish to npm
75
+ if: steps.tagcheck.outputs.exists == 'false'
76
+ env:
77
+ NPM_CONFIG_TOKEN: ${{ secrets.NPM_TOKEN }}
78
+ run: |
79
+ bun publish -p --access public
@@ -0,0 +1,62 @@
1
+ name: Test
2
+
3
+ on:
4
+ pull_request:
5
+ branches: ["**"]
6
+ push:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout code
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Setup Bun
18
+ uses: oven-sh/setup-bun@v1
19
+ with:
20
+ bun-version: latest
21
+
22
+ - name: Install dependencies
23
+ run: bun install
24
+
25
+ - name: Run tests with coverage
26
+ run: bun test --coverage > coverage.txt 2>&1
27
+
28
+ - name: Display coverage
29
+ run: cat coverage.txt
30
+
31
+ - name: Upload coverage results
32
+ uses: actions/upload-artifact@v4
33
+ with:
34
+ name: coverage-report
35
+ path: coverage.txt
36
+ retention-days: 1
37
+
38
+ - name: Build
39
+ run: bun run build
40
+
41
+ coverage:
42
+ runs-on: ubuntu-latest
43
+ needs: test
44
+
45
+ steps:
46
+ - name: Download coverage results
47
+ uses: actions/download-artifact@v4
48
+ with:
49
+ name: coverage-report
50
+
51
+ - name: Check 100% coverage
52
+ run: |
53
+ cat coverage.txt
54
+
55
+ # Extract coverage percentage and check if it's 100%
56
+ if ! grep -E "All files\s+\|\s+.+\s+\|\s+100\.00" coverage.txt; then
57
+ echo "❌ Coverage is not 100%"
58
+ echo "Please ensure all code is covered by tests"
59
+ exit 1
60
+ fi
61
+
62
+ echo "✅ Coverage is 100%"
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ out
3
+ dist
4
+ coverage
5
+ *.tgz
6
+ bun.lock
package/.prettierrc ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "semi": true,
3
+ "singleQuote": false,
4
+ "tabWidth": 2,
5
+ "trailingComma": "es5",
6
+ "printWidth": 100
7
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ugly Unicorn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # π
2
+
3
+ Protected Information Envelope — Schema-validated envelopes using [HPKE](https://www.rfc-editor.org/rfc/rfc9180.html).
4
+
5
+ [![codecov](https://codecov.io/gh/uglyunicorn-eh/pie/graph/badge.svg?token=yBE5KPG0WI)](https://codecov.io/gh/uglyunicorn-eh/pie)
6
+
7
+ Validate payloads with your schema, seal with a public key, and open with the matching private key. Supports retranslation (decrypt with one key, re-encrypt with another) so the original key cannot open the new envelope.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ bun add @uglyunicorn/pie valibot
13
+ # or: npm install @uglyunicorn/pie valibot
14
+ ```
15
+
16
+ ## Example (Valibot)
17
+
18
+ ```ts
19
+ import * as v from "valibot";
20
+
21
+ import { envelope, type EnvelopeContext } from "@uglyunicorn/pie/valibot";
22
+ import { createCipherSuite, envelopeContext } from "@uglyunicorn/pie/crypto";
23
+
24
+ const userProfileSchema = (ctx: EnvelopeContext) =>
25
+ v.objectAsync({
26
+ identity: envelope(
27
+ v.object({
28
+ name: v.string(),
29
+ email: v.string(),
30
+ }),
31
+ ctx
32
+ ),
33
+ height: v.number(),
34
+ weight: v.number(),
35
+ });
36
+
37
+ const userProfile = {
38
+ identity: {
39
+ name: "John Doe",
40
+ email: "john.doe@example.com",
41
+ },
42
+ height: 180,
43
+ weight: 70,
44
+ };
45
+
46
+ const suite = createCipherSuite();
47
+ const keyPair = await suite.GenerateKeyPair(true);
48
+
49
+ const encryptContext = envelopeContext({ out: keyPair });
50
+
51
+ const sealed = await v.parseAsync(userProfileSchema(encryptContext), userProfile);
52
+ console.log(sealed);
53
+ ```
54
+
55
+ Output:
56
+
57
+ ```json
58
+ {
59
+ "identity": {
60
+ "ct": "2DPxSEdZWSQo-C6vh3hlxUeGvZQmoDNW6vQt_Y5V9Gp1mu_MaVG7m4HKJ6OtTwxqGnQlv9ZThZkvUe6JVEZmmmug",
61
+ "enc": "BDQSbUX5SI9R70VMDnOHyNh9DEm5a9J4gvPNjD28-FHV45Q9z-C1JUReIE9llMaalakhvL_lV5gA-e8WIm_lv38"
62
+ },
63
+ "height": 180,
64
+ "weight": 70
65
+ }
66
+ ```
package/body.txt ADDED
@@ -0,0 +1,5 @@
1
+ * Add CI workflows, build scripts, and schema/readme updates
2
+
3
+ * fix: standardize YAML formatting and improve coverage check regex
4
+
5
+ * docs: add Codecov badge to README for coverage tracking
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@uglyunicorn/pie",
3
+ "version": "0.1.0",
4
+ "module": "src/index.ts",
5
+ "type": "module",
6
+ "scripts": {
7
+ "build": "bun run scripts/build.ts && bun run build:types",
8
+ "build:types": "tsc --project tsconfig.build.json",
9
+ "format": "prettier --write .",
10
+ "format:check": "prettier --check .",
11
+ "test": "bun test",
12
+ "test:coverage": "bun test --coverage"
13
+ },
14
+ "exports": {
15
+ ".": "./src/index.ts",
16
+ "./crypto": "./src/crypto/index.ts",
17
+ "./valibot": "./src/schema/valibot.ts"
18
+ },
19
+ "devDependencies": {
20
+ "@types/bun": "latest",
21
+ "@valibot/to-json-schema": "^1.5.0",
22
+ "prettier": "^3.8.1"
23
+ },
24
+ "peerDependencies": {
25
+ "typescript": "^5",
26
+ "valibot": "^1.2.0"
27
+ },
28
+ "dependencies": {
29
+ "@standard-schema/spec": "^1.1.0",
30
+ "hpke": "^1.0.3"
31
+ }
32
+ }
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env bun
2
+
3
+ const builds = [
4
+ { entry: "src/index.ts", outdir: "dist" },
5
+ { entry: "src/crypto/index.ts", outdir: "dist/crypto" },
6
+ { entry: "src/schema/valibot.ts", outdir: "dist/schema" },
7
+ ] as const;
8
+
9
+ for (const { entry, outdir } of builds) {
10
+ const result = await Bun.build({
11
+ entrypoints: [entry],
12
+ outdir,
13
+ target: "node",
14
+ });
15
+
16
+ if (!result.success) {
17
+ console.error(`Failed to build ${entry}`);
18
+ process.exit(1);
19
+ }
20
+ }
@@ -0,0 +1,126 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import {
3
+ type Key,
4
+ type KeyPair,
5
+ CipherSuite,
6
+ KEM_DHKEM_P256_HKDF_SHA256,
7
+ KDF_HKDF_SHA256,
8
+ AEAD_AES_128_GCM,
9
+ } from "hpke";
10
+
11
+ import { decodeBuffer, deserialize, encodeBuffer, serialize } from "../lib/utils";
12
+ import type { CipherContext, DecipherContext, RetranslateContext } from "..";
13
+
14
+ export class HpkeEnvelopeError extends Error {}
15
+
16
+ export interface Envelope {
17
+ ct: string;
18
+ enc: string;
19
+ }
20
+
21
+ export function createCipherSuite(): CipherSuite {
22
+ return new CipherSuite(KEM_DHKEM_P256_HKDF_SHA256, KDF_HKDF_SHA256, AEAD_AES_128_GCM);
23
+ }
24
+
25
+ /**
26
+ * Encrypts data using HPKE.
27
+ *
28
+ * The function validates the data against the schema
29
+ * and then encrypts the data using the public key.
30
+ *
31
+ * @param data - The data to encrypt.
32
+ * @param publicKey - The public key to use for encryption.
33
+ * @returns The encrypted envelope.
34
+ */
35
+ export async function sealEnvelope<T>(
36
+ schema: StandardSchemaV1<T>,
37
+ data: T,
38
+ publicKey: Key
39
+ ): Promise<Envelope> {
40
+ const suite = createCipherSuite();
41
+
42
+ const validated = await schema["~standard"].validate(data);
43
+ if (validated.issues) {
44
+ throw new HpkeEnvelopeError("Unable to seal envelope: invalid payload", {
45
+ cause: validated.issues,
46
+ });
47
+ }
48
+
49
+ const { ciphertext, encapsulatedSecret } = await suite.Seal(
50
+ publicKey,
51
+ serialize(validated.value)
52
+ );
53
+
54
+ return { ct: encodeBuffer(ciphertext), enc: encodeBuffer(encapsulatedSecret) };
55
+ }
56
+
57
+ /**
58
+ * Decrypts data using HPKE.
59
+ *
60
+ * The function decrypts the data using the private key and then validates the
61
+ * data against the schema.
62
+ *
63
+ * @param envelope - The envelope to decrypt.
64
+ * @param privateKey - The private key to use for decryption.
65
+ * @returns The decrypted data.
66
+ */
67
+ export async function openEnvelope<T>(
68
+ schema: StandardSchemaV1<T>,
69
+ envelope: Envelope,
70
+ privateKey: Key
71
+ ): Promise<T> {
72
+ const suite = createCipherSuite();
73
+
74
+ const plaintext = await suite.Open(
75
+ privateKey,
76
+ decodeBuffer(envelope.enc),
77
+ decodeBuffer(envelope.ct)
78
+ );
79
+
80
+ const payload = deserialize(plaintext);
81
+
82
+ const validated = await schema["~standard"].validate(payload);
83
+ if (validated.issues) {
84
+ throw new HpkeEnvelopeError("Unable to open envelope: invalid payload", {
85
+ cause: validated.issues,
86
+ });
87
+ }
88
+
89
+ return validated.value;
90
+ }
91
+
92
+ export function envelopeContext(opts: { out: Pick<KeyPair, "publicKey"> }): CipherContext<Envelope>;
93
+
94
+ export function envelopeContext(opts: {
95
+ in: Pick<KeyPair, "privateKey">;
96
+ }): DecipherContext<Envelope>;
97
+
98
+ export function envelopeContext(opts: {
99
+ in: Pick<KeyPair, "privateKey">;
100
+ out: Pick<KeyPair, "publicKey">;
101
+ }): RetranslateContext<Envelope>;
102
+
103
+ export function envelopeContext(): undefined;
104
+
105
+ export function envelopeContext(opts?: any) {
106
+ if (opts?.in && opts?.out) {
107
+ return {
108
+ open: (schema, envelope) => openEnvelope(schema, envelope, opts.in.privateKey),
109
+ seal: (schema, data) => sealEnvelope(schema, data, opts.out.publicKey),
110
+ } as RetranslateContext<Envelope>;
111
+ }
112
+
113
+ if (opts?.in) {
114
+ return {
115
+ open: (schema, envelope) => openEnvelope(schema, envelope, opts.in.privateKey),
116
+ } as DecipherContext<Envelope>;
117
+ }
118
+
119
+ if (opts?.out) {
120
+ return {
121
+ seal: (schema, data) => sealEnvelope(schema, data, opts.out.publicKey),
122
+ } as CipherContext<Envelope>;
123
+ }
124
+
125
+ return undefined;
126
+ }
@@ -0,0 +1 @@
1
+ export { createCipherSuite, envelopeContext } from "./hpke";
package/src/index.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+
3
+ export interface CipherContext<E> {
4
+ seal: SealEnvelope<E>;
5
+ }
6
+
7
+ export interface DecipherContext<E> {
8
+ open: OpenEnvelope<E>;
9
+ }
10
+
11
+ export interface RetranslateContext<E> {
12
+ open: OpenEnvelope<E>;
13
+ seal: SealEnvelope<E>;
14
+ }
15
+
16
+ export interface RepeatContext {}
17
+
18
+ export type EnvelopeContext<E> =
19
+ | CipherContext<E>
20
+ | DecipherContext<E>
21
+ | RetranslateContext<E>
22
+ | RepeatContext;
23
+
24
+ /**
25
+ * Envelope schema field.
26
+ */
27
+ export interface Envelope<T, E> {
28
+ /**
29
+ * Seals data into an envelope.
30
+ * @param schema - The schema of the data.
31
+ * @param ctx - The options for the envelope.
32
+ * @returns The sealed envelope.
33
+ */
34
+ (schema: StandardSchemaV1<T>, ctx: CipherContext<E>): StandardSchemaV1<T, E>;
35
+
36
+ /**
37
+ * Unseals data from an envelope.
38
+ * @param schema - The schema of the data.
39
+ * @param ctx - The options for the envelope.
40
+ * @returns The unsealed data.
41
+ */
42
+ (schema: StandardSchemaV1<T>, ctx: DecipherContext<E>): StandardSchemaV1<E, T>;
43
+
44
+ /**
45
+ * Retranslates data between two envelopes. Decrypts the data with the decipher
46
+ * and re-encrypts the data with the cipher.
47
+ * @param schema - The schema of the data.
48
+ * @param ctx - The options for the envelope.
49
+ * @returns The retranslated data.
50
+ */
51
+ (schema: StandardSchemaV1<T>, ctx: RetranslateContext<E>): StandardSchemaV1<E>;
52
+
53
+ /**
54
+ * Repeats the envelope without modifying the data.
55
+ *
56
+ * @param schema - The schema of the data.
57
+ * @param ctx - The options for the envelope.
58
+ * @returns The repeated envelope.
59
+ */
60
+ (schema: StandardSchemaV1<T>, ctx: RepeatContext): StandardSchemaV1<E>;
61
+
62
+ /**
63
+ * Returns the schema without modifying the data.
64
+ * @param schema - The schema of the data.
65
+ * @returns The schema without modifying the data.
66
+ */
67
+ (schema: StandardSchemaV1<T>, ctx?: undefined): StandardSchemaV1<T>;
68
+ }
69
+
70
+ /**
71
+ * Seals data into an envelope.
72
+ */
73
+ export interface SealEnvelope<E> {
74
+ <T>(schema: StandardSchemaV1<T>, data: T): Promise<E>;
75
+ }
76
+
77
+ /**
78
+ * Opens an envelope.
79
+ */
80
+ export interface OpenEnvelope<E> {
81
+ <T>(schema: StandardSchemaV1<T>, envelope: E): Promise<T>;
82
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Encodes a Uint8Array to a base64url string.
3
+ *
4
+ * @param data - The data to encode.
5
+ * @returns The encoded data.
6
+ */
7
+ export function encodeBuffer(data: Uint8Array): string {
8
+ return data.toBase64({
9
+ alphabet: "base64url",
10
+ omitPadding: true,
11
+ });
12
+ }
13
+
14
+ /**
15
+ * Decodes a base64url string to Uint8Array.
16
+ *
17
+ * @param encoded - The encoded data.
18
+ * @returns The decoded data.
19
+ */
20
+ export function decodeBuffer(encoded: string): Uint8Array {
21
+ return new Uint8Array(Buffer.from(encoded, "base64url"));
22
+ }
23
+
24
+ /**
25
+ * Serializes data to a Uint8Array.
26
+ *
27
+ * @param data - The data to serialize.
28
+ * @returns The serialized data.
29
+ */
30
+ export function serialize(data: unknown): Uint8Array {
31
+ return new TextEncoder().encode(JSON.stringify(data));
32
+ }
33
+
34
+ /**
35
+ * Deserializes data from a Uint8Array.
36
+ *
37
+ * @param data - The data to deserialize.
38
+ * @returns The deserialized data.
39
+ */
40
+ export function deserialize(data: Uint8Array): unknown {
41
+ return JSON.parse(new TextDecoder().decode(data));
42
+ }
@@ -0,0 +1,77 @@
1
+ import * as v from "valibot";
2
+
3
+ import { type EnvelopeContext as EnvelopeContextType } from "..";
4
+
5
+ import type { CipherContext, DecipherContext, RetranslateContext, RepeatContext } from "..";
6
+
7
+ type AnySchema<I> =
8
+ | v.BaseSchema<I, unknown, v.BaseIssue<I>>
9
+ | v.BaseSchemaAsync<I, unknown, v.BaseIssue<I>>;
10
+
11
+ const envelopeSchema = v.object({
12
+ ct: v.string(),
13
+ enc: v.string(),
14
+ });
15
+
16
+ export type Envelope = v.InferOutput<typeof envelopeSchema>;
17
+
18
+ export type EnvelopeContext = EnvelopeContextType<Envelope>;
19
+
20
+ export function envelope<T>(
21
+ schema: AnySchema<T>,
22
+ ctx: CipherContext<Envelope>
23
+ ): v.BaseSchema<T, Envelope, v.BaseIssue<T>>;
24
+
25
+ export function envelope<T>(
26
+ schema: AnySchema<T>,
27
+ ctx: DecipherContext<Envelope>
28
+ ): v.BaseSchema<Envelope, T, v.BaseIssue<Envelope>>;
29
+
30
+ export function envelope<T>(
31
+ schema: AnySchema<T>,
32
+ ctx: RetranslateContext<Envelope>
33
+ ): v.BaseSchema<Envelope, Envelope, v.BaseIssue<Envelope>>;
34
+
35
+ export function envelope<T>(
36
+ schema: AnySchema<T>,
37
+ ctx: RepeatContext
38
+ ): v.BaseSchema<Envelope, Envelope, v.BaseIssue<Envelope>>;
39
+
40
+ export function envelope<T>(schema: AnySchema<T>): v.BaseSchema<T, T, v.BaseIssue<T>>;
41
+
42
+ export function envelope<T>(
43
+ schema: AnySchema<T>,
44
+ ctx?:
45
+ | CipherContext<Envelope>
46
+ | DecipherContext<Envelope>
47
+ | RetranslateContext<Envelope>
48
+ | RepeatContext
49
+ ) {
50
+ if (ctx === undefined) {
51
+ return schema;
52
+ }
53
+
54
+ if ("open" in ctx && "seal" in ctx) {
55
+ return v.pipeAsync(
56
+ envelopeSchema,
57
+ v.transformAsync((envelope) => ctx.open(schema, envelope)),
58
+ v.transformAsync((payload) => ctx.seal(schema, payload))
59
+ );
60
+ }
61
+
62
+ if ("open" in ctx) {
63
+ return v.pipeAsync(
64
+ envelopeSchema,
65
+ v.transformAsync((envelope) => ctx.open(schema, envelope))
66
+ );
67
+ }
68
+
69
+ if ("seal" in ctx) {
70
+ return v.pipeAsync(
71
+ schema,
72
+ v.transformAsync((message) => ctx.seal(schema, message))
73
+ );
74
+ }
75
+
76
+ return envelopeSchema;
77
+ }
@@ -0,0 +1,78 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import * as v from "valibot";
3
+ import { toJsonSchema } from "@valibot/to-json-schema";
4
+ import {
5
+ createCipherSuite,
6
+ envelopeContext,
7
+ HpkeEnvelopeError,
8
+ openEnvelope,
9
+ sealEnvelope,
10
+ } from "../../src/crypto/hpke";
11
+ import { envelope } from "../../src/schema/valibot";
12
+ import { decodeBuffer } from "../../src/lib/utils";
13
+
14
+ const KEY_MATERIAL = "ylQcrQJlfa-BxdTtWZDLpGKZ3X0XwxCuVBeiCG2q06U";
15
+ const payloadSchema = v.object({ message: v.string() });
16
+ type Payload = v.InferOutput<typeof payloadSchema>;
17
+
18
+ const suite = createCipherSuite();
19
+ const keyPair = await suite.DeriveKeyPair(decodeBuffer(KEY_MATERIAL), true);
20
+
21
+ describe("hpke", () => {
22
+ test("seal/open and validation branches", async () => {
23
+ const sealed = await sealEnvelope(payloadSchema, { message: "hi" }, keyPair.publicKey);
24
+ expect(await openEnvelope(payloadSchema, sealed, keyPair.privateKey)).toEqual({
25
+ message: "hi",
26
+ });
27
+ await expect(
28
+ sealEnvelope(payloadSchema, { message: 123 } as unknown as Payload, keyPair.publicKey)
29
+ ).rejects.toThrow(HpkeEnvelopeError);
30
+ const strictSchema = v.object({ message: v.pipe(v.string(), v.minLength(100)) });
31
+ await expect(openEnvelope(strictSchema, sealed, keyPair.privateKey)).rejects.toThrow(
32
+ HpkeEnvelopeError
33
+ );
34
+ });
35
+ test("envelopeContext with no opts returns undefined", () => {
36
+ expect(envelopeContext()).toBeUndefined();
37
+ });
38
+ test("envelopeContext and envelope() branches", () => {
39
+ const decipher = envelopeContext({ in: keyPair });
40
+ const cipher = envelopeContext({ out: keyPair });
41
+ const retranslate = envelopeContext({ in: keyPair, out: keyPair });
42
+ expect(envelope(payloadSchema, decipher)).toBeDefined();
43
+ expect(envelope(payloadSchema, cipher)).toBeDefined();
44
+ expect(envelope(payloadSchema, retranslate)).toBeDefined();
45
+ expect(toJsonSchema(envelope(payloadSchema))).toMatchInlineSnapshot(`
46
+ {
47
+ "$schema": "http://json-schema.org/draft-07/schema#",
48
+ "properties": {
49
+ "message": {
50
+ "type": "string",
51
+ },
52
+ },
53
+ "required": [
54
+ "message",
55
+ ],
56
+ "type": "object",
57
+ }
58
+ `);
59
+ expect(toJsonSchema(envelope(payloadSchema, {}))).toMatchInlineSnapshot(`
60
+ {
61
+ "$schema": "http://json-schema.org/draft-07/schema#",
62
+ "properties": {
63
+ "ct": {
64
+ "type": "string",
65
+ },
66
+ "enc": {
67
+ "type": "string",
68
+ },
69
+ },
70
+ "required": [
71
+ "ct",
72
+ "enc",
73
+ ],
74
+ "type": "object",
75
+ }
76
+ `);
77
+ });
78
+ });
@@ -0,0 +1,21 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { decodeBuffer, deserialize, encodeBuffer, serialize } from "../../src/lib/utils";
3
+
4
+ describe("utils", () => {
5
+ test("encode/decode roundtrip", () => {
6
+ expect(encodeBuffer(new Uint8Array())).toBe("");
7
+ expect(encodeBuffer(new TextEncoder().encode("hello"))).toBe("aGVsbG8");
8
+ expect(decodeBuffer("")).toEqual(new Uint8Array());
9
+ expect(new TextDecoder().decode(decodeBuffer("aGVsbG8"))).toBe("hello");
10
+ expect(decodeBuffer(encodeBuffer(new Uint8Array([1, 2, 3])))).toEqual(
11
+ new Uint8Array([1, 2, 3])
12
+ );
13
+ });
14
+ test("serialize/deserialize roundtrip", () => {
15
+ expect(new TextDecoder().decode(serialize({ message: "hello" }))).toBe('{"message":"hello"}');
16
+ expect(deserialize(new TextEncoder().encode('{"message":"hello"}'))).toEqual({
17
+ message: "hello",
18
+ });
19
+ expect(deserialize(serialize({ message: "hi", n: 42 }))).toEqual({ message: "hi", n: 42 });
20
+ });
21
+ });
@@ -0,0 +1,96 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import * as v from "valibot";
3
+ import { toJsonSchema } from "@valibot/to-json-schema";
4
+
5
+ import {
6
+ createCipherSuite,
7
+ envelopeContext,
8
+ openEnvelope,
9
+ sealEnvelope,
10
+ } from "../../src/crypto/hpke";
11
+ import { envelope } from "../../src/schema/valibot";
12
+ import { decodeBuffer } from "../../src/lib/utils";
13
+
14
+ const KEY_MATERIAL = "ylQcrQJlfa-BxdTtWZDLpGKZ3X0XwxCuVBeiCG2q06U";
15
+ const payloadSchema = v.object({ message: v.string() });
16
+
17
+ const suite = createCipherSuite();
18
+ const keyPair = await suite.DeriveKeyPair(decodeBuffer(KEY_MATERIAL), true);
19
+ const keyPair2 = await suite.GenerateKeyPair(true);
20
+
21
+ describe("envelope (valibot)", () => {
22
+ test("no ctx returns schema as-is", () => {
23
+ const result = envelope(payloadSchema);
24
+ expect(result).toBe(payloadSchema);
25
+ expect(toJsonSchema(result)).toMatchObject({
26
+ type: "object",
27
+ properties: { message: { type: "string" } },
28
+ required: ["message"],
29
+ });
30
+ });
31
+
32
+ test("empty ctx (repeat) returns envelope schema", () => {
33
+ const result = envelope(payloadSchema, {});
34
+ expect(toJsonSchema(result)).toMatchObject({
35
+ type: "object",
36
+ properties: { ct: { type: "string" }, enc: { type: "string" } },
37
+ required: ["ct", "enc"],
38
+ });
39
+ });
40
+
41
+ test("cipher context: schema seals payload to envelope", async () => {
42
+ const cipher = envelopeContext({ out: keyPair });
43
+ const sealedSchema = envelope(payloadSchema, cipher);
44
+ const payload = { message: "secret" };
45
+ const sealed = await v.parseAsync(sealedSchema, payload);
46
+ expect(sealed).toHaveProperty("ct");
47
+ expect(sealed).toHaveProperty("enc");
48
+ expect(sealed.ct).toBeTruthy();
49
+ expect(sealed.enc).toBeTruthy();
50
+ const plain = { ct: String(sealed.ct), enc: String(sealed.enc) };
51
+ const opened = await openEnvelope(payloadSchema, plain, keyPair.privateKey);
52
+ expect(opened).toEqual(payload);
53
+ });
54
+
55
+ test("decipher context: schema opens envelope to payload", async () => {
56
+ const decipher = envelopeContext({ in: keyPair });
57
+ const openedSchema = envelope(payloadSchema, decipher);
58
+ const sealed = await sealEnvelope(payloadSchema, { message: "hello" }, keyPair.publicKey);
59
+ const opened = await v.parseAsync(openedSchema, sealed);
60
+ expect(opened).toEqual({ message: "hello" });
61
+ });
62
+
63
+ test("retranslate context: envelope to envelope", async () => {
64
+ const retranslate = envelopeContext({ in: keyPair, out: keyPair });
65
+ const retranslateSchema = envelope(payloadSchema, retranslate);
66
+ const sealed = await sealEnvelope(payloadSchema, { message: "relay" }, keyPair.publicKey);
67
+ const result = await v.parseAsync(retranslateSchema, sealed);
68
+ expect(result).toHaveProperty("ct");
69
+ expect(result).toHaveProperty("enc");
70
+ const plain = { ct: String(result.ct), enc: String(result.enc) };
71
+ const opened = await openEnvelope(payloadSchema, plain, keyPair.privateKey);
72
+ expect(opened).toEqual({ message: "relay" });
73
+ });
74
+
75
+ test("retranslate: result is encrypted with out key, not original key", async () => {
76
+ const sealed = await sealEnvelope(payloadSchema, { message: "secret" }, keyPair.publicKey);
77
+ const retranslate = envelopeContext({ in: keyPair, out: keyPair2 });
78
+ const retranslateSchema = envelope(payloadSchema, retranslate);
79
+ const result = await v.parseAsync(retranslateSchema, sealed);
80
+ const plain = { ct: String(result.ct), enc: String(result.enc) };
81
+ expect(await openEnvelope(payloadSchema, plain, keyPair2.privateKey)).toEqual({
82
+ message: "secret",
83
+ });
84
+ await expect(openEnvelope(payloadSchema, plain, keyPair.privateKey)).rejects.toThrow();
85
+ });
86
+
87
+ test("envelope schema validates ct and enc", async () => {
88
+ const repeatSchema = envelope(payloadSchema, {});
89
+ await expect(v.parseAsync(repeatSchema, { ct: "x", enc: "y" })).resolves.toEqual({
90
+ ct: "x",
91
+ enc: "y",
92
+ });
93
+ await expect(v.parseAsync(repeatSchema, { ct: 1, enc: "y" })).rejects.toThrow();
94
+ await expect(v.parseAsync(repeatSchema, {})).rejects.toThrow();
95
+ });
96
+ });
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "declarationMap": true,
6
+ "emitDeclarationOnly": true,
7
+ "outDir": "./dist",
8
+ "noEmit": false
9
+ },
10
+ "include": ["src/**/*"],
11
+ "exclude": ["tests", "dist", "node_modules"]
12
+ }
13
+
package/tsconfig.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+ "noImplicitOverride": true,
23
+
24
+ // Some stricter flags (disabled by default)
25
+ "noUnusedLocals": false,
26
+ "noUnusedParameters": false,
27
+ "noPropertyAccessFromIndexSignature": false
28
+ }
29
+ }