@calque/grant 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # @calque/grant
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `calque serve` verifies Ed25519-signed dataset grants and mints none: your
4
+ application's backend signs them. `@calque/grant` is that backend's half, with
5
+ no dependency beyond `node:crypto`. It creates the signing key, mints grants
6
+ and tenant orders, and refuses every claim Calque's verifier would answer with
7
+ `401`. [`spec/dataset-grant-v1.md`](https://github.com/calque-sh/calque/blob/main/spec/dataset-grant-v1.md) is the
8
+ format it implements.
9
+
10
+ ```sh
11
+ npm install @calque/grant
12
+ ```
13
+
14
+ It is for a server. The signing key never reaches a browser, so nothing here
15
+ runs in one.
16
+
17
+ ## Create the key
18
+
19
+ ```sh
20
+ npx calque-grant keygen --key-file grant-key.pem --key-id app-1
21
+ ```
22
+
23
+ It writes the private key to `grant-key.pem` as PKCS#8 PEM, readable by its
24
+ owner only, and prints the value `calque serve --grant-verification-key-env`
25
+ reads:
26
+
27
+ ```json
28
+ { "keyId": "app-1", "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo" }
29
+ ```
30
+
31
+ Put that value in the environment variable the flag names, and the same
32
+ `publicKey` in the client's `grantVerificationKey`. Keep the key file in your
33
+ secret store. `keygen` never overwrites a file: a server configured with the
34
+ old key would refuse every grant signed with a new one.
35
+
36
+ In code, `generateSigningKey()` returns the same key as a `KeyObject`, as
37
+ PKCS#8 DER and PEM, and as the raw public key.
38
+
39
+ ## Mint a grant
40
+
41
+ ```ts
42
+ import { readFileSync } from "node:fs";
43
+ import { loadSigningKey, mintGrant } from "@calque/grant";
44
+
45
+ const key = loadSigningKey(readFileSync("grant-key.pem"));
46
+
47
+ const now = Math.floor(Date.now() / 1000);
48
+ const token = mintGrant(
49
+ {
50
+ keyId: "app-1",
51
+ audience: "app.example.com",
52
+ subject: user.id,
53
+ attributes: { tenant_id: { int8: "42" } },
54
+ authorizationGeneration: 1,
55
+ issuedAtUnixSeconds: now,
56
+ expiresAtUnixSeconds: now + 900,
57
+ commands: [{ collection: "tasks", operations: ["update"] }],
58
+ },
59
+ key,
60
+ );
61
+ ```
62
+
63
+ Return `token` from the page's `auth()` as `bearerToken`. A grant lasts at most
64
+ 900 seconds, so mint one per request, not per session.
65
+
66
+ `loadSigningKey` takes PEM text, PEM bytes or DER bytes, from PKCS#8 version 1
67
+ or 2. A key from `calque-dev-grant` is a version 2 document, and it loads on
68
+ every supported Node, because the package reads the seed from that layout
69
+ instead of leaving it to the OpenSSL Node bundles.
70
+
71
+ `mintGrant` throws `GrantRefused` instead of signing a grant `calque serve`
72
+ would answer with `401`:
73
+
74
+ - a validity window that is empty or longer than 900 seconds;
75
+ - an unknown claim, an empty audience, or one over 256 bytes;
76
+ - a key id that is empty, longer than 128 bytes, or holds a `.` or a character
77
+ outside printable ASCII;
78
+ - a subject or attribute name that is empty, longer than 512 bytes, or holds a
79
+ control character;
80
+ - more than 64 attributes, or a value outside its type;
81
+ - more than 64 command capabilities, a collection named twice, an empty or
82
+ repeated operation, or an operation other than `insert`, `update` and
83
+ `delete`;
84
+ - a payload over 4096 bytes.
85
+
86
+ It cannot check `authorizationGeneration` or the audience against a
87
+ deployment: those are the deployment's facts, so a grant for the wrong ones is
88
+ signed and then refused by `calque serve`.
89
+
90
+ `int8`, `bytes` and `uuid` attributes travel as strings, because a JavaScript
91
+ number cannot hold every 64-bit integer, and a tenant key that lost its low
92
+ bits would authorize the wrong rows. `int8` is a decimal integer, `bytes` is
93
+ hex, and `uuid` is exactly 32 hex digits with no hyphens.
94
+
95
+ ## Tenants
96
+
97
+ When a scope is partitioned by a grant attribute, each grant names one tenant
98
+ in that attribute, typed as the partition column is: an `int8` column takes
99
+ `{ int8: "42" }`, a `uuid` column takes 32 hex digits. A grant whose attribute
100
+ is missing or of another type is refused.
101
+
102
+ The backend can also warm, pin, unpin, inspect or evict a tenant.
103
+ `mintTenantOrder` signs such an order with the same key, under a signing domain
104
+ of its own so a browser's grant can never stand in for it, valid for at most
105
+ 300 seconds:
106
+
107
+ ```ts
108
+ import { mintTenantOrder } from "@calque/grant";
109
+
110
+ const order = mintTenantOrder(
111
+ {
112
+ keyId: "app-1",
113
+ audience: "app.example.com",
114
+ action: "warm",
115
+ tenant: { int8: "42" },
116
+ issuedAtUnixSeconds: now,
117
+ expiresAtUnixSeconds: now + 60,
118
+ },
119
+ key,
120
+ );
121
+ await fetch(`${calque}/v1/tenants`, {
122
+ method: "POST",
123
+ headers: { "content-type": "application/json" },
124
+ body: JSON.stringify({ order }),
125
+ });
126
+ ```
127
+
128
+ The answer is the tenant's state, `cold`, `preparing` or `warm`, with whether it
129
+ is pinned and, once it has an artifact, the age of its cut and its size.
130
+
131
+ Each order carries an `orderId`, 16 random bytes in base64url unless you pass
132
+ one of 16 to 64 base64url characters. Calque acts on an order once: the same
133
+ order posted again, before it expires or after a restart, is answered `409`
134
+ `REPLAYED`, so mint a new order for each request.
135
+
136
+ ## calque-grant mint
137
+
138
+ ```sh
139
+ npx calque-grant mint --key-file grant-key.pem --key-id app-1 \
140
+ --audience app.example.com --subject me --generation 1 \
141
+ --lifetime-seconds 900 --command tasks=update
142
+ ```
143
+
144
+ It prints one JSON document: the token, when it expires, the generation, the
145
+ commands and the verification-key value. It is for development and for
146
+ scripts; a backend mints in code.
147
+
148
+ | Flag | What it takes |
149
+ | --------------------------- | --------------------------------------------------------------------------------------------- |
150
+ | `--key-file <path>` | The signing key, PEM or DER, PKCS#8. |
151
+ | `--key-id <id>` | The id the grant and the verification key carry. |
152
+ | `--audience <audience>` | The audience `calque serve` was started with. |
153
+ | `--subject <subject>` | Who the grant is issued to. |
154
+ | `--generation <n>` | The authorization generation the grant is valid for. |
155
+ | `--lifetime-seconds <n>` | How long it is valid, at most 900. |
156
+ | `--attribute <n>=<t>:<v>` | A grant attribute; the type is `uuid`, `bytes`, `int8`, `int4`, `int2` or `bool`. Repeatable. |
157
+ | `--command <c>=<op>[+<op>]` | A write capability for a collection; without one the grant is read-only. Repeatable. |
158
+
159
+ `calque-grant` exits 0 on success, 1 when a grant is refused or a file cannot
160
+ be read or written, and 2 on a usage error.
161
+
162
+ ## Node versions
163
+
164
+ The package supports the Node releases with Node's October 2026 security
165
+ fixes: 26.12.1 or newer, 24.22.1 or newer on the 24 line, or 22.23.4 or newer
166
+ on the 22 line. It runs on Node 20 and newer, the first with
167
+ `String.prototype.isWellFormed`, which checks that text is well-formed
168
+ Unicode. It does not depend on the OpenSSL a Node bundles, and its tests pass
169
+ on Node 20, whose OpenSSL 3.0 cannot read a PKCS#8 version 2 key itself.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+ import { run } from "../dist/cli.js";
4
+
5
+ process.exitCode = run(process.argv.slice(2), {
6
+ stdout: process.stdout,
7
+ stderr: process.stderr,
8
+ nowUnixSeconds: () => Math.floor(Date.now() / 1000),
9
+ });
@@ -0,0 +1,73 @@
1
+ import { Buffer } from "node:buffer";
2
+ /** The only payload version Calque accepts. */
3
+ export declare const GRANT_VERSION = 1;
4
+ /**
5
+ * Prefixed to the payload bytes before signing, NUL byte included. A
6
+ * signature over the bare payload is refused.
7
+ */
8
+ export declare const GRANT_SIGNING_DOMAIN = "calque.dataset-grant.v1\0";
9
+ /** The longest validity window Calque accepts: 15 minutes. */
10
+ export declare const MAX_GRANT_LIFETIME_SECONDS: number;
11
+ declare const OPERATIONS: readonly ["insert", "update", "delete"];
12
+ /**
13
+ * One principal attribute in its wire form. `int8`, `bytes` and `uuid` travel
14
+ * as strings, because a JavaScript number cannot hold every 64-bit integer,
15
+ * and a tenant key that lost its low bits would authorize the wrong rows.
16
+ * `int8` is a decimal integer, `bytes` is hex, and `uuid` is exactly 32 hex
17
+ * digits with no hyphens.
18
+ */
19
+ export type GrantAttributeValue = {
20
+ readonly bool: boolean;
21
+ } | {
22
+ readonly int2: number;
23
+ } | {
24
+ readonly int4: number;
25
+ } | {
26
+ readonly int8: string;
27
+ } | {
28
+ readonly bytes: string;
29
+ } | {
30
+ readonly uuid: string;
31
+ };
32
+ export type GrantCommandOperation = (typeof OPERATIONS)[number];
33
+ /** One collection's write capability: exact names, no wildcard. */
34
+ export interface GrantCommandCapability {
35
+ readonly collection: string;
36
+ readonly operations: readonly GrantCommandOperation[];
37
+ }
38
+ /** Everything a grant states except its version, which is always 1. */
39
+ export interface DatasetGrantClaims {
40
+ readonly keyId: string;
41
+ readonly audience: string;
42
+ readonly subject: string;
43
+ readonly attributes: Readonly<Record<string, GrantAttributeValue>>;
44
+ readonly authorizationGeneration: number;
45
+ readonly issuedAtUnixSeconds: number;
46
+ readonly expiresAtUnixSeconds: number;
47
+ /** Absent or empty is a read-only grant, which authorizes no write. */
48
+ readonly commands?: readonly GrantCommandCapability[];
49
+ }
50
+ /** A claim Calque's verifier would refuse, refused before it is signed. */
51
+ export declare class GrantRefused extends Error {
52
+ constructor(message: string);
53
+ }
54
+ export declare function refuse(message: string): never;
55
+ export declare const utf8Bytes: (text: string) => number;
56
+ export declare function wellFormed(field: string, value: unknown): string;
57
+ export declare function keyId(value: unknown): string;
58
+ export declare function audience(value: unknown): string;
59
+ export declare function unsigned(field: string, value: unknown): number;
60
+ /** The attribute value's JSON, exactly as the Rust issuer writes it. */
61
+ export declare function attributeValue(attribute: string, value: unknown): string;
62
+ /**
63
+ * The signed payload, refused if Calque would refuse it.
64
+ *
65
+ * The verifier parses any JSON object with these fields, in any order and with
66
+ * any whitespace, because the signature covers whatever bytes were sent. These
67
+ * are the bytes the Rust issuer writes, so the frozen token vectors can check
68
+ * this package: fields in the order below, no whitespace, attributes sorted by
69
+ * their UTF-8 bytes, operations in the order given, and `commands` omitted
70
+ * when empty.
71
+ */
72
+ export declare function serializeClaims(claims: DatasetGrantClaims): Buffer;
73
+ export {};
package/dist/claims.js ADDED
@@ -0,0 +1,225 @@
1
+ import { Buffer } from "node:buffer";
2
+ /** The only payload version Calque accepts. */
3
+ export const GRANT_VERSION = 1;
4
+ /**
5
+ * Prefixed to the payload bytes before signing, NUL byte included. A
6
+ * signature over the bare payload is refused.
7
+ */
8
+ export const GRANT_SIGNING_DOMAIN = "calque.dataset-grant.v1\0";
9
+ /** The longest validity window Calque accepts: 15 minutes. */
10
+ export const MAX_GRANT_LIFETIME_SECONDS = 15 * 60;
11
+ const MAX_PAYLOAD_BYTES = 4 * 1024;
12
+ const MAX_KEY_ID_BYTES = 128;
13
+ const MAX_AUDIENCE_BYTES = 256;
14
+ const MAX_NAME_BYTES = 512;
15
+ const MAX_ATTRIBUTES = 64;
16
+ const MAX_COMMAND_CAPABILITIES = 64;
17
+ const MAX_COLLECTION_BYTES = 128;
18
+ const OPERATIONS = ["insert", "update", "delete"];
19
+ const CLAIMS = new Set([
20
+ "keyId",
21
+ "audience",
22
+ "subject",
23
+ "attributes",
24
+ "authorizationGeneration",
25
+ "issuedAtUnixSeconds",
26
+ "expiresAtUnixSeconds",
27
+ "commands",
28
+ ]);
29
+ /** A claim Calque's verifier would refuse, refused before it is signed. */
30
+ export class GrantRefused extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "GrantRefused";
34
+ }
35
+ }
36
+ export function refuse(message) {
37
+ throw new GrantRefused(message);
38
+ }
39
+ export const utf8Bytes = (text) => Buffer.byteLength(text, "utf8");
40
+ /** Rust's `u8::is_ascii_graphic`: `!` through `~`. */
41
+ const ASCII_GRAPHIC = /^[\x21-\x7e]+$/;
42
+ /** The same, without `.`, which separates a token's two halves. */
43
+ const KEY_ID = /^[\x21-\x2d\x2f-\x7e]+$/;
44
+ /** Rust's `char::is_control`, general category Cc. */
45
+ const CONTROL = /\p{Cc}/u;
46
+ export function wellFormed(field, value) {
47
+ if (typeof value !== "string" || !value.isWellFormed())
48
+ refuse(`${field} must be a string of well-formed Unicode`);
49
+ return value;
50
+ }
51
+ export function keyId(value) {
52
+ const text = wellFormed("keyId", value);
53
+ if (utf8Bytes(text) > MAX_KEY_ID_BYTES || !KEY_ID.test(text))
54
+ refuse(`keyId must be 1 to ${String(MAX_KEY_ID_BYTES)} printable ASCII characters other than "."`);
55
+ return text;
56
+ }
57
+ export function audience(value) {
58
+ const text = wellFormed("audience", value);
59
+ if (text === "" || utf8Bytes(text) > MAX_AUDIENCE_BYTES)
60
+ refuse(`audience must be 1 to ${String(MAX_AUDIENCE_BYTES)} bytes`);
61
+ return text;
62
+ }
63
+ /** A subject or an attribute name, as `authz::Principal::new` checks it. */
64
+ function name(field, value) {
65
+ const text = wellFormed(field, value);
66
+ if (text === "" || utf8Bytes(text) > MAX_NAME_BYTES || CONTROL.test(text))
67
+ refuse(`${field} must be 1 to ${String(MAX_NAME_BYTES)} bytes of UTF-8 with no control character`);
68
+ return text;
69
+ }
70
+ export function unsigned(field, value) {
71
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
72
+ refuse(`${field} must be a whole number from 0 to ${String(Number.MAX_SAFE_INTEGER)}`);
73
+ return value;
74
+ }
75
+ function integer(field, value, minimum, maximum) {
76
+ if (typeof value !== "number" ||
77
+ !Number.isInteger(value) ||
78
+ value < minimum ||
79
+ value > maximum)
80
+ refuse(`${field} must be a whole number from ${String(minimum)} to ${String(maximum)}`);
81
+ return value;
82
+ }
83
+ /** The attribute value's JSON, exactly as the Rust issuer writes it. */
84
+ export function attributeValue(attribute, value) {
85
+ const field = `attribute ${attribute}`;
86
+ if (typeof value !== "object" || value === null || Array.isArray(value))
87
+ refuse(`${field} must be an object naming one type`);
88
+ const entries = Object.entries(value);
89
+ const [entry] = entries;
90
+ if (entry === undefined || entries.length !== 1)
91
+ refuse(`${field} must name exactly one type`);
92
+ const [type, raw] = entry;
93
+ switch (type) {
94
+ case "bool":
95
+ if (typeof raw !== "boolean")
96
+ refuse(`${field} must be true or false`);
97
+ return `{"bool":${String(raw)}}`;
98
+ case "int2":
99
+ return `{"int2":${String(integer(field, raw, -32_768, 32_767))}}`;
100
+ case "int4":
101
+ return `{"int4":${String(integer(field, raw, -2_147_483_648, 2_147_483_647))}}`;
102
+ case "int8":
103
+ if (typeof raw !== "string" ||
104
+ !/^[+-]?[0-9]+$/.test(raw) ||
105
+ BigInt(raw) < -(2n ** 63n) ||
106
+ BigInt(raw) >= 2n ** 63n)
107
+ refuse(`${field} must be a decimal string within a signed 64-bit integer`);
108
+ return `{"int8":${JSON.stringify(raw)}}`;
109
+ case "bytes":
110
+ if (typeof raw !== "string" || !/^(?:[0-9a-fA-F]{2})*$/.test(raw))
111
+ refuse(`${field} must be hex with an even number of digits`);
112
+ return `{"bytes":${JSON.stringify(raw)}}`;
113
+ case "uuid":
114
+ if (typeof raw !== "string" || !/^[0-9a-fA-F]{32}$/.test(raw))
115
+ refuse(`${field} must be 32 hex digits with no hyphens`);
116
+ return `{"uuid":${JSON.stringify(raw)}}`;
117
+ default:
118
+ return refuse(`${field} has unknown type ${type}; the types are bool, int2, int4, int8, bytes and uuid`);
119
+ }
120
+ }
121
+ /**
122
+ * Sorted by their UTF-8 bytes, which is how a Rust `BTreeMap` orders them.
123
+ * `Array.prototype.sort` compares UTF-16 code units and disagrees above
124
+ * U+FFFF, and an object's own key order puts integer-like keys first.
125
+ */
126
+ function attributes(value) {
127
+ if (typeof value !== "object" || value === null || Array.isArray(value))
128
+ refuse("attributes must be an object, empty for none");
129
+ const entries = Object.entries(value);
130
+ if (entries.length > MAX_ATTRIBUTES)
131
+ refuse(`a grant carries at most ${String(MAX_ATTRIBUTES)} attributes, not ${String(entries.length)}`);
132
+ return entries
133
+ .map(([attribute, raw]) => ({
134
+ key: Buffer.from(name("attribute name", attribute), "utf8"),
135
+ json: `${JSON.stringify(attribute)}:${attributeValue(attribute, raw)}`,
136
+ }))
137
+ .sort((left, right) => Buffer.compare(left.key, right.key))
138
+ .map(({ json }) => json)
139
+ .join(",");
140
+ }
141
+ /**
142
+ * The write capability's JSON, or undefined when there is none, since the Rust
143
+ * issuer omits an empty `commands`.
144
+ */
145
+ function commands(value) {
146
+ if (value === undefined)
147
+ return undefined;
148
+ if (!Array.isArray(value))
149
+ refuse("commands must be a list");
150
+ if (value.length === 0)
151
+ return undefined;
152
+ if (value.length > MAX_COMMAND_CAPABILITIES)
153
+ refuse(`a grant carries at most ${String(MAX_COMMAND_CAPABILITIES)} command capabilities`);
154
+ const named = new Set();
155
+ const entries = value.map((capability) => {
156
+ if (typeof capability !== "object" || capability === null)
157
+ refuse("a command capability must be an object");
158
+ const fields = Object.keys(capability);
159
+ if (fields.length !== 2 ||
160
+ !fields.includes("collection") ||
161
+ !fields.includes("operations"))
162
+ refuse(`a command capability has exactly a collection and its operations, not ${fields.join(", ")}`);
163
+ const { collection, operations } = capability;
164
+ if (typeof collection !== "string" ||
165
+ collection.length > MAX_COLLECTION_BYTES ||
166
+ !ASCII_GRAPHIC.test(collection))
167
+ refuse(`a collection is 1 to ${String(MAX_COLLECTION_BYTES)} printable ASCII characters`);
168
+ if (named.has(collection))
169
+ refuse(`collection ${collection} is named twice`);
170
+ named.add(collection);
171
+ if (!Array.isArray(operations) || operations.length === 0)
172
+ refuse(`collection ${collection} names no operation; an empty set is refused, never read as every operation`);
173
+ const seen = new Set();
174
+ for (const operation of operations) {
175
+ if (!OPERATIONS.includes(operation))
176
+ refuse(`collection ${collection} names ${JSON.stringify(operation)}; the operations are insert, update and delete`);
177
+ if (seen.has(operation))
178
+ refuse(`collection ${collection} repeats ${String(operation)}`);
179
+ seen.add(operation);
180
+ }
181
+ return `{"collection":${JSON.stringify(collection)},"operations":${JSON.stringify(operations)}}`;
182
+ });
183
+ return `[${entries.join(",")}]`;
184
+ }
185
+ /**
186
+ * The signed payload, refused if Calque would refuse it.
187
+ *
188
+ * The verifier parses any JSON object with these fields, in any order and with
189
+ * any whitespace, because the signature covers whatever bytes were sent. These
190
+ * are the bytes the Rust issuer writes, so the frozen token vectors can check
191
+ * this package: fields in the order below, no whitespace, attributes sorted by
192
+ * their UTF-8 bytes, operations in the order given, and `commands` omitted
193
+ * when empty.
194
+ */
195
+ export function serializeClaims(claims) {
196
+ for (const field of Object.keys(claims))
197
+ if (!CLAIMS.has(field))
198
+ refuse(`${field} is not a grant claim; Calque refuses a payload with an unknown field`);
199
+ const issued = unsigned("issuedAtUnixSeconds", claims.issuedAtUnixSeconds);
200
+ const expires = unsigned("expiresAtUnixSeconds", claims.expiresAtUnixSeconds);
201
+ if (expires <= issued)
202
+ refuse("expiresAtUnixSeconds must be later than issuedAtUnixSeconds");
203
+ if (expires - issued > MAX_GRANT_LIFETIME_SECONDS)
204
+ refuse(`the validity window is ${String(expires - issued)} s; Calque refuses one longer than ${String(MAX_GRANT_LIFETIME_SECONDS)} s`);
205
+ const fields = [
206
+ `"version":${String(GRANT_VERSION)}`,
207
+ `"keyId":${JSON.stringify(keyId(claims.keyId))}`,
208
+ `"audience":${JSON.stringify(audience(claims.audience))}`,
209
+ `"subject":${JSON.stringify(name("subject", claims.subject))}`,
210
+ `"attributes":{${attributes(claims.attributes)}}`,
211
+ `"authorizationGeneration":${String(unsigned("authorizationGeneration", claims.authorizationGeneration))}`,
212
+ `"issuedAtUnixSeconds":${String(issued)}`,
213
+ `"expiresAtUnixSeconds":${String(expires)}`,
214
+ ];
215
+ const capabilities = commands(claims.commands);
216
+ if (capabilities !== undefined)
217
+ fields.push(`"commands":${capabilities}`);
218
+ const payload = Buffer.from(`{${fields.join(",")}}`, "utf8");
219
+ // Within this bound a token is at most 5,549 bytes, inside the verifier's
220
+ // 8 KiB token bound, so that one needs no check of its own.
221
+ if (payload.length > MAX_PAYLOAD_BYTES)
222
+ refuse(`the payload is ${String(payload.length)} bytes; Calque refuses one over ${String(MAX_PAYLOAD_BYTES)}`);
223
+ return payload;
224
+ }
225
+ //# sourceMappingURL=claims.js.map
@@ -0,0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OAAO,CAAC;AACjB,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ interface Output {
2
+ write(text: string): unknown;
3
+ }
4
+ /** What `run` needs from the process, so a test can stand in for it. */
5
+ export interface Environment {
6
+ readonly stdout: Output;
7
+ readonly stderr: Output;
8
+ readonly nowUnixSeconds: () => number;
9
+ }
10
+ /** Runs `calque-grant` over `argv` and returns its exit status. */
11
+ export declare function run(argv: readonly string[], io: Environment): number;
12
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,229 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import {} from "./claims.js";
5
+ import { generateSigningKey, loadSigningKey, verificationKeyEnvironment, } from "./key.js";
6
+ import { mintGrant } from "./mint.js";
7
+ const USAGE = `usage: calque-grant keygen --key-file <path> --key-id <id>
8
+ calque-grant mint --key-file <path> --key-id <id> --audience <audience>
9
+ --subject <subject> --generation <n> --lifetime-seconds <n>
10
+ [--attribute <name>=<type>:<value>]...
11
+ [--command <collection>=<operation>[+<operation>]]...
12
+ `;
13
+ const HELP = `${USAGE}
14
+ keygen Creates an Ed25519 signing key at --key-file, as PKCS#8 PEM readable
15
+ by owner only, and prints the {"keyId":...,"publicKey":...} value that
16
+ \`calque serve --grant-verification-key-env\` reads. It never overwrites
17
+ a file.
18
+
19
+ mint Signs one dataset grant with the key at --key-file and prints it as one
20
+ JSON document, with when it expires and the verification-key value.
21
+ --lifetime-seconds is at most 900. An attribute type is uuid (32 hex
22
+ digits), bytes (hex), int8, int4, int2 or bool. A command names a
23
+ collection and insert, update or delete; without one the grant is
24
+ read-only.
25
+
26
+ --key-file <path> the signing key, PEM or DER, PKCS#8
27
+ --key-id <id> the id the grant and the verification key carry
28
+ --audience <audience> the audience \`calque serve\` was started with
29
+ --subject <subject> who the grant is issued to
30
+ --generation <n> the authorization generation it is valid for
31
+ --lifetime-seconds <n> how long it is valid
32
+ --attribute <n>=<t>:<v> repeat for more than one
33
+ --command <c>=<op>[+<op>] repeat per collection
34
+ -h, --help print this text
35
+
36
+ Exit status: 0 on success, 1 when a grant is refused or a file cannot be read
37
+ or written, 2 on a usage error.
38
+ `;
39
+ class UsageError extends Error {
40
+ }
41
+ const WHOLE_NUMBER = /^[0-9]+$/u;
42
+ const SIGNED_NUMBER = /^[+-]?[0-9]+$/u;
43
+ /** `<name>=<type>:<value>`, in the vocabulary `calque-dev-grant` reads. */
44
+ function parseAttribute(argument) {
45
+ const equals = argument.indexOf("=");
46
+ const colon = argument.indexOf(":", equals + 1);
47
+ if (equals === -1 || colon === -1)
48
+ throw new UsageError(`--attribute ${argument} is not <name>=<type>:<value>`);
49
+ const name = argument.slice(0, equals);
50
+ const type = argument.slice(equals + 1, colon);
51
+ const value = argument.slice(colon + 1);
52
+ switch (type) {
53
+ case "uuid":
54
+ return [name, { uuid: value }];
55
+ case "bytes":
56
+ return [name, { bytes: value }];
57
+ case "int8":
58
+ return [name, { int8: value }];
59
+ case "int4":
60
+ case "int2":
61
+ if (!SIGNED_NUMBER.test(value))
62
+ throw new UsageError(`--attribute ${name} is not an ${type}`);
63
+ return [
64
+ name,
65
+ type === "int4" ? { int4: Number(value) } : { int2: Number(value) },
66
+ ];
67
+ case "bool":
68
+ if (value !== "true" && value !== "false")
69
+ throw new UsageError(`--attribute ${name} is not a bool`);
70
+ return [name, { bool: value === "true" }];
71
+ default:
72
+ throw new UsageError(`--attribute ${name} has unknown type ${type}`);
73
+ }
74
+ }
75
+ /** `<collection>=<operation>[+<operation>…]`; there is no wildcard. */
76
+ function parseCommand(argument) {
77
+ const equals = argument.indexOf("=");
78
+ if (equals === -1)
79
+ throw new UsageError(`--command ${argument} is not <collection>=<operation>[+…]`);
80
+ return {
81
+ collection: argument.slice(0, equals),
82
+ // `mintGrant` refuses an operation outside the three.
83
+ operations: argument
84
+ .slice(equals + 1)
85
+ .split("+"),
86
+ };
87
+ }
88
+ const OPTIONS = {
89
+ "key-file": { type: "string", multiple: true },
90
+ "key-id": { type: "string", multiple: true },
91
+ audience: { type: "string", multiple: true },
92
+ subject: { type: "string", multiple: true },
93
+ generation: { type: "string", multiple: true },
94
+ "lifetime-seconds": { type: "string", multiple: true },
95
+ attribute: { type: "string", multiple: true },
96
+ command: { type: "string", multiple: true },
97
+ help: { type: "boolean", short: "h" },
98
+ };
99
+ function parseFlags(argv) {
100
+ try {
101
+ return parseArgs({
102
+ args: [...argv],
103
+ options: OPTIONS,
104
+ strict: true,
105
+ allowPositionals: false,
106
+ }).values;
107
+ }
108
+ catch (error) {
109
+ throw new UsageError(error instanceof Error ? error.message : String(error));
110
+ }
111
+ }
112
+ function single(flags, name) {
113
+ const given = flags[name];
114
+ if (given === undefined)
115
+ throw new UsageError(`--${name} is required`);
116
+ if (given.length > 1)
117
+ throw new UsageError(`--${name} was given twice`);
118
+ const [value] = given;
119
+ if (value === undefined)
120
+ throw new UsageError(`--${name} is required`);
121
+ return value;
122
+ }
123
+ function wholeNumber(flags, name) {
124
+ const value = single(flags, name);
125
+ if (!WHOLE_NUMBER.test(value))
126
+ throw new UsageError(`--${name} must be a whole number`);
127
+ return Number(value);
128
+ }
129
+ function rejectOtherFlags(flags, allowed) {
130
+ for (const name of Object.keys(flags))
131
+ if (name !== "help" && !allowed.includes(name))
132
+ throw new UsageError(`unknown argument --${name}`);
133
+ }
134
+ function keygen(flags, io) {
135
+ rejectOtherFlags(flags, ["key-file", "key-id"]);
136
+ const path = single(flags, "key-file");
137
+ const id = single(flags, "key-id");
138
+ const { privateKey, pem } = generateSigningKey();
139
+ // Checked before anything is written, so a bad id leaves no key behind.
140
+ const environment = verificationKeyEnvironment(id, privateKey);
141
+ mkdirSync(dirname(path), { recursive: true });
142
+ try {
143
+ writeFileSync(path, pem, { flag: "wx", mode: 0o600 });
144
+ }
145
+ catch (error) {
146
+ if (error.code === "EEXIST")
147
+ throw new Error(`${path} exists, and keygen never overwrites a key: a server configured with the old one would refuse every grant signed with a new one`);
148
+ throw error;
149
+ }
150
+ io.stdout.write(`${environment}\n`);
151
+ }
152
+ const MINT_FLAGS = [
153
+ "key-file",
154
+ "key-id",
155
+ "audience",
156
+ "subject",
157
+ "generation",
158
+ "lifetime-seconds",
159
+ "attribute",
160
+ "command",
161
+ ];
162
+ function mint(flags, io) {
163
+ rejectOtherFlags(flags, MINT_FLAGS);
164
+ const attributes = {};
165
+ for (const argument of flags.attribute ?? []) {
166
+ const [name, attribute] = parseAttribute(argument);
167
+ if (Object.hasOwn(attributes, name))
168
+ throw new UsageError(`--attribute ${name} was given twice`);
169
+ attributes[name] = attribute;
170
+ }
171
+ const commands = (flags.command ?? []).map(parseCommand);
172
+ const keyId = single(flags, "key-id");
173
+ const subject = single(flags, "subject");
174
+ const generation = wholeNumber(flags, "generation");
175
+ const lifetime = wholeNumber(flags, "lifetime-seconds");
176
+ const audience = single(flags, "audience");
177
+ const keyFile = single(flags, "key-file");
178
+ const key = loadSigningKey(readFileSync(keyFile));
179
+ const issued = io.nowUnixSeconds();
180
+ const token = mintGrant({
181
+ keyId,
182
+ audience,
183
+ subject,
184
+ attributes,
185
+ authorizationGeneration: generation,
186
+ issuedAtUnixSeconds: issued,
187
+ expiresAtUnixSeconds: issued + lifetime,
188
+ commands,
189
+ }, key);
190
+ // The keys in the order `calque-dev-grant` prints them.
191
+ io.stdout.write(`${JSON.stringify({
192
+ authorizationGeneration: generation,
193
+ commands: commands.map(({ collection, operations }) => `${collection}:${operations.join("+")}`),
194
+ expiresAtUnixSeconds: issued + lifetime,
195
+ issuedAtUnixSeconds: issued,
196
+ subject,
197
+ token,
198
+ verificationKeyEnvironment: JSON.parse(verificationKeyEnvironment(keyId, key)),
199
+ }, null, 2)}\n`);
200
+ }
201
+ /** Runs `calque-grant` over `argv` and returns its exit status. */
202
+ export function run(argv, io) {
203
+ try {
204
+ const [command, ...rest] = argv;
205
+ if (command === undefined || command === "-h" || command === "--help") {
206
+ (command === undefined ? io.stderr : io.stdout).write(command === undefined ? USAGE : HELP);
207
+ return command === undefined ? 2 : 0;
208
+ }
209
+ if (command !== "keygen" && command !== "mint")
210
+ throw new UsageError(`unknown command ${command}`);
211
+ const flags = parseFlags(rest);
212
+ if (flags.help === true) {
213
+ io.stdout.write(HELP);
214
+ return 0;
215
+ }
216
+ (command === "keygen" ? keygen : mint)(flags, io);
217
+ return 0;
218
+ }
219
+ catch (error) {
220
+ const message = error instanceof Error ? error.message : String(error);
221
+ if (error instanceof UsageError) {
222
+ io.stderr.write(`calque-grant: ${message}\n${USAGE}`);
223
+ return 2;
224
+ }
225
+ io.stderr.write(`calque-grant: ${message}\n`);
226
+ return 1;
227
+ }
228
+ }
229
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAIN,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,0BAA0B,GAC3B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAatC,MAAM,KAAK,GAAG;;;;;CAKb,CAAC;AAEF,MAAM,IAAI,GAAG,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;CAyBpB,CAAC;AAEF,MAAM,UAAW,SAAQ,KAAK;CAAG;AAEjC,MAAM,YAAY,GAAG,WAAW,CAAC;AACjC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAEvC,2EAA2E;AAC3E,SAAS,cAAc,CAAC,QAAgB;IACtC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,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OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,MAAM;YAC5C,MAAM,IAAI,UAAU,CAAC,mBAAmB,OAAO,EAAE,CAAC,CAAC;QACrD,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACxB,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACtB,OAAO,CAAC,CAAC;QACX,CAAC;QACD,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvE,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;YAChC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,OAAO,KAAK,KAAK,EAAE,CAAC,CAAC;YACtD,OAAO,CAAC,CAAC;QACX,CAAC;QACD,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,OAAO,IAAI,CAAC,CAAC;QAC9C,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { GRANT_SIGNING_DOMAIN, GRANT_VERSION, GrantRefused, MAX_GRANT_LIFETIME_SECONDS, } from "./claims.js";
2
+ export type { DatasetGrantClaims, GrantAttributeValue, GrantCommandCapability, GrantCommandOperation, } from "./claims.js";
3
+ export { generateSigningKey, loadSigningKey, verificationKeyEnvironment, } from "./key.js";
4
+ export type { GeneratedSigningKey } from "./key.js";
5
+ export { MAX_TENANT_ORDER_LIFETIME_SECONDS, mintGrant, mintTenantOrder, TENANT_ORDER_SIGNING_DOMAIN, } from "./mint.js";
6
+ export type { TenantAction, TenantOrderClaims } from "./mint.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { GRANT_SIGNING_DOMAIN, GRANT_VERSION, GrantRefused, MAX_GRANT_LIFETIME_SECONDS, } from "./claims.js";
2
+ export { generateSigningKey, loadSigningKey, verificationKeyEnvironment, } from "./key.js";
3
+ export { MAX_TENANT_ORDER_LIFETIME_SECONDS, mintGrant, mintTenantOrder, TENANT_ORDER_SIGNING_DOMAIN, } from "./mint.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,YAAY,EACZ,0BAA0B,GAC3B,MAAM,aAAa,CAAC;AAOrB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,0BAA0B,GAC3B,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,iCAAiC,EACjC,SAAS,EACT,eAAe,EACf,2BAA2B,GAC5B,MAAM,WAAW,CAAC"}
package/dist/key.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { type KeyObject } from "node:crypto";
3
+ /** A fresh Ed25519 signing key, in every form a backend stores it in. */
4
+ export interface GeneratedSigningKey {
5
+ readonly privateKey: KeyObject;
6
+ /** The private key as a PKCS#8 version 1 DER document. */
7
+ readonly pkcs8: Buffer;
8
+ /** The same document as PEM text, which a secret store holds as a string. */
9
+ readonly pem: string;
10
+ /** The raw 32-byte public key in unpadded base64url. */
11
+ readonly publicKey: string;
12
+ }
13
+ export declare function ed25519(key: KeyObject): KeyObject;
14
+ /**
15
+ * A new Ed25519 key pair from the platform's random source. The private key is
16
+ * written as PKCS#8 version 1, which every Node that supports Ed25519 reads.
17
+ */
18
+ export declare function generateSigningKey(): GeneratedSigningKey;
19
+ /**
20
+ * The private key from a PKCS#8 Ed25519 document, as PEM text or DER bytes,
21
+ * version 1 or 2. `calque-grant keygen` writes PEM; `calque-dev-grant` writes
22
+ * DER, as version 2. A document of another kind of key is refused.
23
+ */
24
+ export declare function loadSigningKey(document: Uint8Array | string): KeyObject;
25
+ /**
26
+ * The `{"keyId":…,"publicKey":…}` value a deployment's
27
+ * `--grant-verification-key-env` variable holds for this key: the raw 32-byte
28
+ * public key, unpadded base64url.
29
+ */
30
+ export declare function verificationKeyEnvironment(id: string, key: KeyObject): string;
package/dist/key.js ADDED
@@ -0,0 +1,113 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, } from "node:crypto";
3
+ import { keyId } from "./claims.js";
4
+ export function ed25519(key) {
5
+ if (key.asymmetricKeyType !== "ed25519")
6
+ throw new TypeError(`a grant is signed with an Ed25519 key, not ${String(key.asymmetricKeyType)}`);
7
+ return key;
8
+ }
9
+ function rawPublicKey(key) {
10
+ const { x } = createPublicKey(key).export({ format: "jwk" });
11
+ if (x === undefined)
12
+ throw new TypeError("the key exported no public half");
13
+ return x;
14
+ }
15
+ /**
16
+ * A new Ed25519 key pair from the platform's random source. The private key is
17
+ * written as PKCS#8 version 1, which every Node that supports Ed25519 reads.
18
+ */
19
+ export function generateSigningKey() {
20
+ const { privateKey } = generateKeyPairSync("ed25519");
21
+ return {
22
+ privateKey,
23
+ pkcs8: privateKey.export({ format: "der", type: "pkcs8" }),
24
+ pem: privateKey.export({ format: "pem", type: "pkcs8" }).toString(),
25
+ publicKey: rawPublicKey(privateKey),
26
+ };
27
+ }
28
+ const PKCS8_V1_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
29
+ const PKCS8_V2_PREFIX = Buffer.from("3051020101300506032b657004220420", "hex");
30
+ const PKCS8_V2_PUBLIC_KEY_PREFIX = Buffer.from("812100", "hex");
31
+ const SEED_BYTES = 32;
32
+ const PKCS8_V2_BYTES = PKCS8_V2_PREFIX.length +
33
+ SEED_BYTES +
34
+ PKCS8_V2_PUBLIC_KEY_PREFIX.length +
35
+ SEED_BYTES;
36
+ function fromSeed(seed) {
37
+ return createPrivateKey({
38
+ key: Buffer.concat([PKCS8_V1_PREFIX, seed]),
39
+ format: "der",
40
+ type: "pkcs8",
41
+ });
42
+ }
43
+ /**
44
+ * The seed of an Ed25519 PKCS#8 version 2 document in the layout
45
+ * `calque-dev-grant` and ring write: the algorithm identifier, the seed, then
46
+ * the public key as the `[1]` field. Undefined for any other bytes. A public
47
+ * key that is not the seed's is refused.
48
+ */
49
+ function versionTwoSeed(der) {
50
+ if (der.length !== PKCS8_V2_BYTES)
51
+ return undefined;
52
+ const seedAt = PKCS8_V2_PREFIX.length;
53
+ const publicAt = seedAt + SEED_BYTES + PKCS8_V2_PUBLIC_KEY_PREFIX.length;
54
+ if (!der.subarray(0, seedAt).equals(PKCS8_V2_PREFIX) ||
55
+ !der
56
+ .subarray(seedAt + SEED_BYTES, publicAt)
57
+ .equals(PKCS8_V2_PUBLIC_KEY_PREFIX))
58
+ return undefined;
59
+ const seed = der.subarray(seedAt, seedAt + SEED_BYTES);
60
+ const embedded = der.subarray(publicAt).toString("base64url");
61
+ if (rawPublicKey(fromSeed(seed)) !== embedded)
62
+ throw new TypeError("the key document's public key is not the one its private key derives");
63
+ return seed;
64
+ }
65
+ function fromDer(der) {
66
+ // A version 2 document in the layout above is read from its seed on every
67
+ // Node, because OpenSSL before 3.5, which Node bundles up to 22.19 and
68
+ // 24.4, refuses version 2.
69
+ const seed = versionTwoSeed(der);
70
+ return seed === undefined
71
+ ? createPrivateKey({ key: der, format: "der", type: "pkcs8" })
72
+ : fromSeed(seed);
73
+ }
74
+ const PEM_LABEL = /^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+?)\s*-----END PRIVATE KEY-----\s*$/u;
75
+ /**
76
+ * The private key from a PKCS#8 Ed25519 document, as PEM text or DER bytes,
77
+ * version 1 or 2. `calque-grant keygen` writes PEM; `calque-dev-grant` writes
78
+ * DER, as version 2. A document of another kind of key is refused.
79
+ */
80
+ export function loadSigningKey(document) {
81
+ const bytes = typeof document === "string"
82
+ ? Buffer.from(document, "utf8")
83
+ : Buffer.from(document);
84
+ const text = bytes.toString("latin1").trimStart();
85
+ let key;
86
+ try {
87
+ if (text.startsWith("-----BEGIN")) {
88
+ const body = PEM_LABEL.exec(text)?.[1];
89
+ if (body === undefined)
90
+ throw new TypeError("the PEM document is not a PRIVATE KEY block of PKCS#8");
91
+ key = fromDer(Buffer.from(body.replace(/\s+/gu, ""), "base64"));
92
+ }
93
+ else {
94
+ key = fromDer(bytes);
95
+ }
96
+ }
97
+ catch (cause) {
98
+ throw new TypeError(`the document is not a PKCS#8 Ed25519 private key in PEM or DER: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
99
+ }
100
+ return ed25519(key);
101
+ }
102
+ /**
103
+ * The `{"keyId":…,"publicKey":…}` value a deployment's
104
+ * `--grant-verification-key-env` variable holds for this key: the raw 32-byte
105
+ * public key, unpadded base64url.
106
+ */
107
+ export function verificationKeyEnvironment(id, key) {
108
+ return JSON.stringify({
109
+ keyId: keyId(id),
110
+ publicKey: rawPublicKey(ed25519(key)),
111
+ });
112
+ }
113
+ //# sourceMappingURL=key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.js","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GAEpB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAapC,MAAM,UAAU,OAAO,CAAC,GAAc;IACpC,IAAI,GAAG,CAAC,iBAAiB,KAAK,SAAS;QACrC,MAAM,IAAI,SAAS,CACjB,8CAA8C,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE,CAC9E,CAAC;IACJ,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,Y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S,EAAE,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;KACtC,CAAC,CAAC;AACL,CAAC"}
package/dist/mint.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { type DatasetGrantClaims, type GrantAttributeValue } from "./claims.js";
3
+ /**
4
+ * Prefixed to a tenant order's payload before signing, so that neither a
5
+ * dataset grant nor a tenant order verifies as the other.
6
+ */
7
+ export declare const TENANT_ORDER_SIGNING_DOMAIN = "calque.tenant-order.v1\0";
8
+ /** The longest validity window Calque accepts for a tenant order: 5 minutes. */
9
+ export declare const MAX_TENANT_ORDER_LIFETIME_SECONDS: number;
10
+ /**
11
+ * `warm` prepares the tenant now, `pin` keeps it warm whatever its recency,
12
+ * `unpin` hands it back to recency, `state` changes nothing, and `evict` drops
13
+ * its artifact, pin and recency so its next open is cold.
14
+ */
15
+ export type TenantAction = "warm" | "pin" | "unpin" | "state" | "evict";
16
+ /** Everything a tenant order states except its version, which is always 1. */
17
+ export interface TenantOrderClaims {
18
+ readonly keyId: string;
19
+ readonly audience: string;
20
+ /**
21
+ * Unique to this order, which Calque acts on once: 16 to 64 base64url
22
+ * characters. Left out, it is 16 random bytes.
23
+ */
24
+ readonly orderId?: string;
25
+ readonly action: TenantAction;
26
+ /** The tenant, typed as the grant attribute that names it. */
27
+ readonly tenant: GrantAttributeValue;
28
+ readonly issuedAtUnixSeconds: number;
29
+ readonly expiresAtUnixSeconds: number;
30
+ }
31
+ /**
32
+ * `base64url(payload).base64url(signature)`, both unpadded, where the
33
+ * signature is Ed25519 over the domain, then the payload.
34
+ */
35
+ export declare function signUnder(domain: string, payload: Uint8Array, key: KeyObject): string;
36
+ /**
37
+ * A signed grant for exactly these claims, or a `GrantRefused` for claims
38
+ * Calque's verifier would answer with 401.
39
+ */
40
+ export declare function mintGrant(claims: DatasetGrantClaims, key: KeyObject): string;
41
+ /**
42
+ * The order the backend posts as `{"order": …}` to `POST /v1/tenants`, signed
43
+ * with the grant key. Only the backend holds that key, so a browser cannot
44
+ * warm, pin or inspect a tenant.
45
+ */
46
+ export declare function mintTenantOrder(claims: TenantOrderClaims, key: KeyObject): string;
package/dist/mint.js ADDED
@@ -0,0 +1,64 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { randomBytes, sign } from "node:crypto";
3
+ import { attributeValue, audience, GRANT_SIGNING_DOMAIN, keyId, refuse, serializeClaims, unsigned, } from "./claims.js";
4
+ import { ed25519 } from "./key.js";
5
+ /**
6
+ * Prefixed to a tenant order's payload before signing, so that neither a
7
+ * dataset grant nor a tenant order verifies as the other.
8
+ */
9
+ export const TENANT_ORDER_SIGNING_DOMAIN = "calque.tenant-order.v1\0";
10
+ /** The longest validity window Calque accepts for a tenant order: 5 minutes. */
11
+ export const MAX_TENANT_ORDER_LIFETIME_SECONDS = 5 * 60;
12
+ const TENANT_ACTIONS = new Set([
13
+ "warm",
14
+ "pin",
15
+ "unpin",
16
+ "state",
17
+ "evict",
18
+ ]);
19
+ /**
20
+ * `base64url(payload).base64url(signature)`, both unpadded, where the
21
+ * signature is Ed25519 over the domain, then the payload.
22
+ */
23
+ export function signUnder(domain, payload, key) {
24
+ if (key.type !== "private")
25
+ throw new TypeError("a grant is signed with a private key");
26
+ const signature = sign(null, Buffer.concat([Buffer.from(domain, "utf8"), payload]), ed25519(key));
27
+ return `${Buffer.from(payload).toString("base64url")}.${signature.toString("base64url")}`;
28
+ }
29
+ /**
30
+ * A signed grant for exactly these claims, or a `GrantRefused` for claims
31
+ * Calque's verifier would answer with 401.
32
+ */
33
+ export function mintGrant(claims, key) {
34
+ return signUnder(GRANT_SIGNING_DOMAIN, serializeClaims(claims), key);
35
+ }
36
+ /**
37
+ * The order the backend posts as `{"order": …}` to `POST /v1/tenants`, signed
38
+ * with the grant key. Only the backend holds that key, so a browser cannot
39
+ * warm, pin or inspect a tenant.
40
+ */
41
+ export function mintTenantOrder(claims, key) {
42
+ const { action } = claims;
43
+ if (!TENANT_ACTIONS.has(action))
44
+ refuse(`action ${JSON.stringify(action)} is not warm, pin, unpin, state or evict`);
45
+ const orderId = claims.orderId ?? randomBytes(16).toString("base64url");
46
+ if (!/^[A-Za-z0-9_-]{16,64}$/u.test(orderId))
47
+ refuse("orderId must be 16 to 64 base64url characters");
48
+ const issued = unsigned("issuedAtUnixSeconds", claims.issuedAtUnixSeconds);
49
+ const expires = unsigned("expiresAtUnixSeconds", claims.expiresAtUnixSeconds);
50
+ if (expires <= issued || expires - issued > MAX_TENANT_ORDER_LIFETIME_SECONDS)
51
+ refuse(`a tenant order is valid for 1 to ${String(MAX_TENANT_ORDER_LIFETIME_SECONDS)} s`);
52
+ const payload = [
53
+ `"version":1`,
54
+ `"keyId":${JSON.stringify(keyId(claims.keyId))}`,
55
+ `"audience":${JSON.stringify(audience(claims.audience))}`,
56
+ `"orderId":${JSON.stringify(orderId)}`,
57
+ `"action":${JSON.stringify(action)}`,
58
+ `"tenant":${attributeValue("tenant", claims.tenant)}`,
59
+ `"issuedAtUnixSeconds":${String(issued)}`,
60
+ `"expiresAtUnixSeconds":${String(expires)}`,
61
+ ].join(",");
62
+ return signUnder(TENANT_ORDER_SIGNING_DOMAIN, Buffer.from(`{${payload}}`, "utf8"), key);
63
+ }
64
+ //# sourceMappingURL=mint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mint.js","sourceRoot":"","sources":["../src/mint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,IAAI,EAAkB,MAAM,aAAa,CAAC;AAEhE,OAAO,EACL,cAAc,EACd,QAAQ,EACR,oBAAoB,EACpB,KAAK,EACL,MAAM,EACN,eAAe,EACf,QAAQ,GAGT,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAEnC;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,0BAA0B,CAAC;AAEtE,gFAAgF;AA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yB,CAAC,IAAI,CAAC,OAAO,CAAC;QAC1C,MAAM,CAAC,+CAA+C,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAC;IAC3E,MAAM,OAAO,GAAG,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC,oBAAoB,CAAC,CAAC;IAC9E,IAAI,OAAO,IAAI,MAAM,IAAI,OAAO,GAAG,MAAM,GAAG,iCAAiC;QAC3E,MAAM,CACJ,oCAAoC,MAAM,CAAC,iCAAiC,CAAC,IAAI,CAClF,CAAC;IACJ,MAAM,OAAO,GAAG;QACd,aAAa;QACb,WAAW,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;QAChD,cAAc,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE;QACzD,aAAa,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;QACtC,YAAY,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;QACpC,YAAY,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE;QACrD,yBAAyB,MAAM,CAAC,MAAM,CAAC,EAAE;QACzC,0BAA0B,MAAM,CAAC,OAAO,CAAC,EAAE;KAC5C,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACZ,OAAO,SAAS,CACd,2BAA2B,EAC3B,MAAM,CAAC,IAAI,CAAC,IAAI,OAAO,GAAG,EAAE,MAAM,CAAC,EACnC,GAAG,CACJ,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@calque/grant",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Signs Calque dataset grants and tenant orders from a Node backend, and creates the signing key; calque-grant is its command line.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/calque-sh/calque",
9
+ "directory": "client/packages/grant"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "engines": {
15
+ "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
16
+ },
17
+ "type": "module",
18
+ "bin": {
19
+ "calque-grant": "./bin/calque-grant.js"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "dist"
30
+ ],
31
+ "devDependencies": {
32
+ "@eslint/js": "^9.31.0",
33
+ "@types/node": "^24.0.0",
34
+ "eslint": "^9.31.0",
35
+ "jiti": "^2.7.0",
36
+ "prettier": "^3.6.0",
37
+ "typescript": "^5.8.0",
38
+ "typescript-eslint": "^8.38.0",
39
+ "vitest": "^4.1.0"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.build.json",
43
+ "format": "prettier --write .",
44
+ "lint": "eslint . --max-warnings 0 && prettier --check .",
45
+ "test": "vitest run",
46
+ "typecheck": "../../../node_modules/.bin/tsc -p tsconfig.json --noEmit"
47
+ }
6
48
  }