@rindle/affinity 0.6.3
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 +201 -0
- package/README.md +27 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +138 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -0
- package/src/index.ts +190 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# @rindle/affinity
|
|
2
|
+
|
|
3
|
+
The TypeScript twin of the `rindle-affinity` Rust crate: mint and verify the **follower-affinity
|
|
4
|
+
ticket** — the HMAC-signed placement token that pins a browser session to one follower machine so
|
|
5
|
+
its live-query ws stream and its api-server-issued lease co-locate. Used by the local dev-edge and
|
|
6
|
+
any JS-side verify; production daemons mint/verify with the Rust crate.
|
|
7
|
+
|
|
8
|
+
A ticket is `aff.<base64url(payload)>.<base64url(hmac_sha256(base64url(payload), key))>`. `mint` here
|
|
9
|
+
is **byte-for-byte identical** to the crate for the same input (pinned by a shared frozen test
|
|
10
|
+
vector), so a Rust-minted ticket verifies here and vice-versa. It is **placement, not
|
|
11
|
+
authorization**: a forged ticket only aims a connection at a machine, granting no data access.
|
|
12
|
+
|
|
13
|
+
Full docs — regional followers and the Fly-edge routing this drives:
|
|
14
|
+
**[rindle.sh/docs/cloud-scaling](https://rindle.sh/docs/cloud-scaling)** · for agents:
|
|
15
|
+
[llms.txt](https://rindle.sh/llms.txt)
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { mint, verify } from "@rindle/affinity";
|
|
19
|
+
|
|
20
|
+
const ticket = mint(
|
|
21
|
+
{ app, mid, region, sub: clientId, iat: now, exp: now + 3600, gen: 0 },
|
|
22
|
+
process.env.RINDLE_AFFINITY_KEY!,
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
const result = verify(ticket, [currentKey, previousKey], { app, now, minGen: 0 });
|
|
26
|
+
if (result.ok) routeTo(result.payload.mid);
|
|
27
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** The token namespace marker — the first dot-segment of every ticket. */
|
|
2
|
+
export declare const TICKET_PREFIX = "aff";
|
|
3
|
+
/** The base ws subprotocol offered alongside the `aff.*` ticket; the daemon echoes it on the 101. */
|
|
4
|
+
export declare const WS_SUBPROTOCOL = "rindle.v1";
|
|
5
|
+
/** The api-server → fleet control-plane header carrying the ticket on `/materialize` and `/query`. */
|
|
6
|
+
export declare const HEADER_NAME = "Rindle-Affinity";
|
|
7
|
+
/**
|
|
8
|
+
* The signed ticket body. Field order here is the canonical mint order — it is exactly the compact
|
|
9
|
+
* JSON that gets base64url-encoded and signed, so it must match the Rust `Payload` struct order.
|
|
10
|
+
*/
|
|
11
|
+
export interface Payload {
|
|
12
|
+
/** Fly app id the ticket is scoped to. */
|
|
13
|
+
app: string;
|
|
14
|
+
/** Fly machine id — the placement target (`fly-replay: instance=<mid>`). */
|
|
15
|
+
mid: string;
|
|
16
|
+
/** Fly region code of `mid`. */
|
|
17
|
+
region: string;
|
|
18
|
+
/** Subject: the connection identity (clientInstanceId). */
|
|
19
|
+
sub: string;
|
|
20
|
+
/** Issued-at, unix seconds (informational). */
|
|
21
|
+
iat: number;
|
|
22
|
+
/** Expiry, unix seconds. `verify` rejects once `now > exp`. */
|
|
23
|
+
exp: number;
|
|
24
|
+
/** Generation minted under; a fleet-wide bump drains older tickets. */
|
|
25
|
+
gen: number;
|
|
26
|
+
}
|
|
27
|
+
/** What {@link verify} holds a ticket against, supplied by the verifier. */
|
|
28
|
+
export interface Expect {
|
|
29
|
+
/** The verifier's app id; must equal `payload.app`. */
|
|
30
|
+
app: string;
|
|
31
|
+
/** Current wall-clock, unix seconds. `exp < now` ⇒ rejected. */
|
|
32
|
+
now: number;
|
|
33
|
+
/** Minimum accepted generation; `gen < minGen` ⇒ rejected. `0` accepts any. */
|
|
34
|
+
minGen: number;
|
|
35
|
+
}
|
|
36
|
+
/** Why a ticket failed {@link verify}. Every variant is a terminal reject (fall back to re-pin). */
|
|
37
|
+
export type VerifyError = "malformed" | "bad-signature" | "wrong-app" | "expired" | "stale-generation";
|
|
38
|
+
/** {@link verify}'s result: the authenticated payload, or a reason. */
|
|
39
|
+
export type VerifyResult = {
|
|
40
|
+
readonly ok: true;
|
|
41
|
+
readonly payload: Payload;
|
|
42
|
+
} | {
|
|
43
|
+
readonly ok: false;
|
|
44
|
+
readonly error: VerifyError;
|
|
45
|
+
};
|
|
46
|
+
type Key = string | Uint8Array;
|
|
47
|
+
/**
|
|
48
|
+
* Mint a ticket over `payload`, signed with `key`. Deterministic (no randomness): the same
|
|
49
|
+
* `(payload, key)` always yields the same token. The compact JSON is built in the fixed field order
|
|
50
|
+
* so the bytes match the Rust crate's `serde_json` compact output.
|
|
51
|
+
*/
|
|
52
|
+
export declare function mint(payload: Payload, key: Key): string;
|
|
53
|
+
/**
|
|
54
|
+
* Verify `token` against `keys` (current first, then rotation-window predecessors) and `expect`.
|
|
55
|
+
* The HMAC is checked (constant-time) over the transmitted base64url payload segment before the
|
|
56
|
+
* payload is parsed, so a tampered payload fails as `bad-signature`, never as a parse of attacker
|
|
57
|
+
* bytes.
|
|
58
|
+
*/
|
|
59
|
+
export declare function verify(token: string, keys: readonly Key[], expect: Expect): VerifyResult;
|
|
60
|
+
/**
|
|
61
|
+
* Extract the `aff.*` ticket from a `Sec-WebSocket-Protocol` header value (a comma list, e.g.
|
|
62
|
+
* `rindle.v1, aff.<…>`). Returns the raw ticket segment for {@link verify}, or `null`. Does not verify.
|
|
63
|
+
*/
|
|
64
|
+
export declare function wsSubprotocolTicket(header: string): string | null;
|
|
65
|
+
/** Whether the header offers the base {@link WS_SUBPROTOCOL} — the daemon must echo it on the 101. */
|
|
66
|
+
export declare function wsOffersBase(header: string): boolean;
|
|
67
|
+
/** Extract the ticket from a {@link HEADER_NAME} value. Returns the raw segment, or `null`. */
|
|
68
|
+
export declare function headerTicket(value: string): string | null;
|
|
69
|
+
export {};
|
|
70
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAkBA,0EAA0E;AAC1E,eAAO,MAAM,aAAa,QAAQ,CAAC;AAEnC,qGAAqG;AACrG,eAAO,MAAM,cAAc,cAAc,CAAC;AAE1C,sGAAsG;AACtG,eAAO,MAAM,WAAW,oBAAoB,CAAC;AAE7C;;;GAGG;AACH,MAAM,WAAW,OAAO;IACtB,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,4EAA4E;IAC5E,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,2DAA2D;IAC3D,GAAG,EAAE,MAAM,CAAC;IACZ,+CAA+C;IAC/C,GAAG,EAAE,MAAM,CAAC;IACZ,+DAA+D;IAC/D,GAAG,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,4EAA4E;AAC5E,MAAM,WAAW,MAAM;IACrB,uDAAuD;IACvD,GAAG,EAAE,MAAM,CAAC;IACZ,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;IACZ,+EAA+E;IAC/E,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,oGAAoG;AACpG,MAAM,MAAM,WAAW,GACnB,WAAW,GACX,eAAe,GACf,WAAW,GACX,SAAS,GACT,kBAAkB,CAAC;AAEvB,uEAAuE;AACvE,MAAM,MAAM,YAAY,GACpB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAChD;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAA;CAAE,CAAC;AAExD,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAY/B;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,GAAG,MAAM,CAavD;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,YAAY,CAoBxF;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAMjE;AAED,sGAAsG;AACtG,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED,+FAA+F;AAC/F,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGzD"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Follower-affinity tickets — the TypeScript twin of the `rindle-affinity` Rust crate
|
|
2
|
+
// (`rust/rindle-affinity/src/lib.rs`; `designs/FOLLOWER-AFFINITY-DESIGN.md` §3, §9). Used by the
|
|
3
|
+
// local dev-edge (S4) and any JS-side verify; the daemon mints/verifies with the Rust crate.
|
|
4
|
+
//
|
|
5
|
+
// # Byte-compatibility
|
|
6
|
+
//
|
|
7
|
+
// A ticket is `aff.<base64url(payload)>.<base64url(hmac_sha256(base64url(payload), key))>` where
|
|
8
|
+
// `payload` is COMPACT JSON with the field order below. `mint` here produces byte-for-byte the same
|
|
9
|
+
// token as the Rust crate for the same input — pinned by the shared `frozenTestVector` in the tests
|
|
10
|
+
// (mirrored from the crate's `frozen_test_vector`). Because `verify` authenticates the transmitted
|
|
11
|
+
// base64url payload segment BEFORE parsing it, a Rust-minted ticket verifies here and vice-versa
|
|
12
|
+
// regardless of either side's JSON handling.
|
|
13
|
+
//
|
|
14
|
+
// Placement, not authorization (design §3, §9): a forged ticket only *aims* a connection at a
|
|
15
|
+
// machine, granting no data access. The key is a symmetric per-fleet secret.
|
|
16
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
17
|
+
/** The token namespace marker — the first dot-segment of every ticket. */
|
|
18
|
+
export const TICKET_PREFIX = "aff";
|
|
19
|
+
/** The base ws subprotocol offered alongside the `aff.*` ticket; the daemon echoes it on the 101. */
|
|
20
|
+
export const WS_SUBPROTOCOL = "rindle.v1";
|
|
21
|
+
/** The api-server → fleet control-plane header carrying the ticket on `/materialize` and `/query`. */
|
|
22
|
+
export const HEADER_NAME = "Rindle-Affinity";
|
|
23
|
+
const B64URL = /^[A-Za-z0-9_-]+$/;
|
|
24
|
+
function keyBytes(key) {
|
|
25
|
+
return typeof key === "string" ? new TextEncoder().encode(key) : key;
|
|
26
|
+
}
|
|
27
|
+
function b64url(bytes) {
|
|
28
|
+
return Buffer.from(bytes).toString("base64url");
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Mint a ticket over `payload`, signed with `key`. Deterministic (no randomness): the same
|
|
32
|
+
* `(payload, key)` always yields the same token. The compact JSON is built in the fixed field order
|
|
33
|
+
* so the bytes match the Rust crate's `serde_json` compact output.
|
|
34
|
+
*/
|
|
35
|
+
export function mint(payload, key) {
|
|
36
|
+
const json = JSON.stringify({
|
|
37
|
+
app: payload.app,
|
|
38
|
+
mid: payload.mid,
|
|
39
|
+
region: payload.region,
|
|
40
|
+
sub: payload.sub,
|
|
41
|
+
iat: payload.iat,
|
|
42
|
+
exp: payload.exp,
|
|
43
|
+
gen: payload.gen,
|
|
44
|
+
});
|
|
45
|
+
const payloadB64 = Buffer.from(json, "utf8").toString("base64url");
|
|
46
|
+
const sig = createHmac("sha256", keyBytes(key)).update(payloadB64).digest();
|
|
47
|
+
return `${TICKET_PREFIX}.${payloadB64}.${b64url(sig)}`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Verify `token` against `keys` (current first, then rotation-window predecessors) and `expect`.
|
|
51
|
+
* The HMAC is checked (constant-time) over the transmitted base64url payload segment before the
|
|
52
|
+
* payload is parsed, so a tampered payload fails as `bad-signature`, never as a parse of attacker
|
|
53
|
+
* bytes.
|
|
54
|
+
*/
|
|
55
|
+
export function verify(token, keys, expect) {
|
|
56
|
+
const parts = splitToken(token);
|
|
57
|
+
if (!parts)
|
|
58
|
+
return { ok: false, error: "malformed" };
|
|
59
|
+
const [payloadB64, sigB64] = parts;
|
|
60
|
+
if (!B64URL.test(payloadB64) || !B64URL.test(sigB64))
|
|
61
|
+
return { ok: false, error: "malformed" };
|
|
62
|
+
const sig = Buffer.from(sigB64, "base64url");
|
|
63
|
+
const msg = Buffer.from(payloadB64, "utf8");
|
|
64
|
+
const matches = keys.some((k) => {
|
|
65
|
+
const mac = createHmac("sha256", keyBytes(k)).update(msg).digest();
|
|
66
|
+
return mac.length === sig.length && timingSafeEqual(mac, sig);
|
|
67
|
+
});
|
|
68
|
+
if (!matches)
|
|
69
|
+
return { ok: false, error: "bad-signature" };
|
|
70
|
+
const payload = parsePayload(payloadB64);
|
|
71
|
+
if (!payload)
|
|
72
|
+
return { ok: false, error: "malformed" };
|
|
73
|
+
if (payload.app !== expect.app)
|
|
74
|
+
return { ok: false, error: "wrong-app" };
|
|
75
|
+
if (expect.now > payload.exp)
|
|
76
|
+
return { ok: false, error: "expired" };
|
|
77
|
+
if (payload.gen < expect.minGen)
|
|
78
|
+
return { ok: false, error: "stale-generation" };
|
|
79
|
+
return { ok: true, payload };
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Extract the `aff.*` ticket from a `Sec-WebSocket-Protocol` header value (a comma list, e.g.
|
|
83
|
+
* `rindle.v1, aff.<…>`). Returns the raw ticket segment for {@link verify}, or `null`. Does not verify.
|
|
84
|
+
*/
|
|
85
|
+
export function wsSubprotocolTicket(header) {
|
|
86
|
+
for (const raw of header.split(",")) {
|
|
87
|
+
const p = raw.trim();
|
|
88
|
+
if (isTicketShape(p))
|
|
89
|
+
return p;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
/** Whether the header offers the base {@link WS_SUBPROTOCOL} — the daemon must echo it on the 101. */
|
|
94
|
+
export function wsOffersBase(header) {
|
|
95
|
+
return header.split(",").some((p) => p.trim() === WS_SUBPROTOCOL);
|
|
96
|
+
}
|
|
97
|
+
/** Extract the ticket from a {@link HEADER_NAME} value. Returns the raw segment, or `null`. */
|
|
98
|
+
export function headerTicket(value) {
|
|
99
|
+
const v = value.trim();
|
|
100
|
+
return isTicketShape(v) ? v : null;
|
|
101
|
+
}
|
|
102
|
+
/** A syntactic ticket = `aff.<seg>.<seg>` with non-empty segments. Cheap prefilter, like the crate. */
|
|
103
|
+
function isTicketShape(s) {
|
|
104
|
+
return splitToken(s) !== null;
|
|
105
|
+
}
|
|
106
|
+
/** Split into (payloadB64, sigB64), validating the `aff.` prefix and exact 3-segment shape. */
|
|
107
|
+
function splitToken(token) {
|
|
108
|
+
const parts = token.split(".");
|
|
109
|
+
if (parts.length !== 3)
|
|
110
|
+
return null;
|
|
111
|
+
const [prefix, payloadB64, sigB64] = parts;
|
|
112
|
+
if (prefix !== TICKET_PREFIX || payloadB64.length === 0 || sigB64.length === 0)
|
|
113
|
+
return null;
|
|
114
|
+
return [payloadB64, sigB64];
|
|
115
|
+
}
|
|
116
|
+
function parsePayload(payloadB64) {
|
|
117
|
+
let value;
|
|
118
|
+
try {
|
|
119
|
+
value = JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf8"));
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
if (typeof value !== "object" || value === null)
|
|
125
|
+
return null;
|
|
126
|
+
const p = value;
|
|
127
|
+
if (typeof p.app !== "string" ||
|
|
128
|
+
typeof p.mid !== "string" ||
|
|
129
|
+
typeof p.region !== "string" ||
|
|
130
|
+
typeof p.sub !== "string" ||
|
|
131
|
+
typeof p.iat !== "number" ||
|
|
132
|
+
typeof p.exp !== "number" ||
|
|
133
|
+
typeof p.gen !== "number") {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
return { app: p.app, mid: p.mid, region: p.region, sub: p.sub, iat: p.iat, exp: p.exp, gen: p.gen };
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,iGAAiG;AACjG,6FAA6F;AAC7F,EAAE;AACF,uBAAuB;AACvB,EAAE;AACF,iGAAiG;AACjG,oGAAoG;AACpG,oGAAoG;AACpG,mGAAmG;AACnG,iGAAiG;AACjG,6CAA6C;AAC7C,EAAE;AACF,8FAA8F;AAC9F,6EAA6E;AAE7E,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1D,0EAA0E;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAEnC,qGAAqG;AACrG,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAE1C,sGAAsG;AACtG,MAAM,CAAC,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAgD7C,MAAM,MAAM,GAAG,kBAAkB,CAAC;AAElC,SAAS,QAAQ,CAAC,GAAQ;IACxB,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,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4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/rindle-sh/rindle.git",
|
|
8
|
+
"directory": "packages/affinity"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"description": "Follower-affinity ticket: mint/verify the HMAC placement token, byte-compatible with the rindle-affinity Rust crate.",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"@rindle/source": "./src/index.ts",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^22.10.0",
|
|
29
|
+
"typescript": "^5.7.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.build.json",
|
|
33
|
+
"typecheck": "tsc --noEmit",
|
|
34
|
+
"test": "tsc --noEmit && node --conditions=@rindle/source --test test/*.test.ts"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// Follower-affinity tickets — the TypeScript twin of the `rindle-affinity` Rust crate
|
|
2
|
+
// (`rust/rindle-affinity/src/lib.rs`; `designs/FOLLOWER-AFFINITY-DESIGN.md` §3, §9). Used by the
|
|
3
|
+
// local dev-edge (S4) and any JS-side verify; the daemon mints/verifies with the Rust crate.
|
|
4
|
+
//
|
|
5
|
+
// # Byte-compatibility
|
|
6
|
+
//
|
|
7
|
+
// A ticket is `aff.<base64url(payload)>.<base64url(hmac_sha256(base64url(payload), key))>` where
|
|
8
|
+
// `payload` is COMPACT JSON with the field order below. `mint` here produces byte-for-byte the same
|
|
9
|
+
// token as the Rust crate for the same input — pinned by the shared `frozenTestVector` in the tests
|
|
10
|
+
// (mirrored from the crate's `frozen_test_vector`). Because `verify` authenticates the transmitted
|
|
11
|
+
// base64url payload segment BEFORE parsing it, a Rust-minted ticket verifies here and vice-versa
|
|
12
|
+
// regardless of either side's JSON handling.
|
|
13
|
+
//
|
|
14
|
+
// Placement, not authorization (design §3, §9): a forged ticket only *aims* a connection at a
|
|
15
|
+
// machine, granting no data access. The key is a symmetric per-fleet secret.
|
|
16
|
+
|
|
17
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
18
|
+
|
|
19
|
+
/** The token namespace marker — the first dot-segment of every ticket. */
|
|
20
|
+
export const TICKET_PREFIX = "aff";
|
|
21
|
+
|
|
22
|
+
/** The base ws subprotocol offered alongside the `aff.*` ticket; the daemon echoes it on the 101. */
|
|
23
|
+
export const WS_SUBPROTOCOL = "rindle.v1";
|
|
24
|
+
|
|
25
|
+
/** The api-server → fleet control-plane header carrying the ticket on `/materialize` and `/query`. */
|
|
26
|
+
export const HEADER_NAME = "Rindle-Affinity";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The signed ticket body. Field order here is the canonical mint order — it is exactly the compact
|
|
30
|
+
* JSON that gets base64url-encoded and signed, so it must match the Rust `Payload` struct order.
|
|
31
|
+
*/
|
|
32
|
+
export interface Payload {
|
|
33
|
+
/** Fly app id the ticket is scoped to. */
|
|
34
|
+
app: string;
|
|
35
|
+
/** Fly machine id — the placement target (`fly-replay: instance=<mid>`). */
|
|
36
|
+
mid: string;
|
|
37
|
+
/** Fly region code of `mid`. */
|
|
38
|
+
region: string;
|
|
39
|
+
/** Subject: the connection identity (clientInstanceId). */
|
|
40
|
+
sub: string;
|
|
41
|
+
/** Issued-at, unix seconds (informational). */
|
|
42
|
+
iat: number;
|
|
43
|
+
/** Expiry, unix seconds. `verify` rejects once `now > exp`. */
|
|
44
|
+
exp: number;
|
|
45
|
+
/** Generation minted under; a fleet-wide bump drains older tickets. */
|
|
46
|
+
gen: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What {@link verify} holds a ticket against, supplied by the verifier. */
|
|
50
|
+
export interface Expect {
|
|
51
|
+
/** The verifier's app id; must equal `payload.app`. */
|
|
52
|
+
app: string;
|
|
53
|
+
/** Current wall-clock, unix seconds. `exp < now` ⇒ rejected. */
|
|
54
|
+
now: number;
|
|
55
|
+
/** Minimum accepted generation; `gen < minGen` ⇒ rejected. `0` accepts any. */
|
|
56
|
+
minGen: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Why a ticket failed {@link verify}. Every variant is a terminal reject (fall back to re-pin). */
|
|
60
|
+
export type VerifyError =
|
|
61
|
+
| "malformed"
|
|
62
|
+
| "bad-signature"
|
|
63
|
+
| "wrong-app"
|
|
64
|
+
| "expired"
|
|
65
|
+
| "stale-generation";
|
|
66
|
+
|
|
67
|
+
/** {@link verify}'s result: the authenticated payload, or a reason. */
|
|
68
|
+
export type VerifyResult =
|
|
69
|
+
| { readonly ok: true; readonly payload: Payload }
|
|
70
|
+
| { readonly ok: false; readonly error: VerifyError };
|
|
71
|
+
|
|
72
|
+
type Key = string | Uint8Array;
|
|
73
|
+
|
|
74
|
+
const B64URL = /^[A-Za-z0-9_-]+$/;
|
|
75
|
+
|
|
76
|
+
function keyBytes(key: Key): Uint8Array {
|
|
77
|
+
return typeof key === "string" ? new TextEncoder().encode(key) : key;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function b64url(bytes: Uint8Array): string {
|
|
81
|
+
return Buffer.from(bytes).toString("base64url");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Mint a ticket over `payload`, signed with `key`. Deterministic (no randomness): the same
|
|
86
|
+
* `(payload, key)` always yields the same token. The compact JSON is built in the fixed field order
|
|
87
|
+
* so the bytes match the Rust crate's `serde_json` compact output.
|
|
88
|
+
*/
|
|
89
|
+
export function mint(payload: Payload, key: Key): string {
|
|
90
|
+
const json = JSON.stringify({
|
|
91
|
+
app: payload.app,
|
|
92
|
+
mid: payload.mid,
|
|
93
|
+
region: payload.region,
|
|
94
|
+
sub: payload.sub,
|
|
95
|
+
iat: payload.iat,
|
|
96
|
+
exp: payload.exp,
|
|
97
|
+
gen: payload.gen,
|
|
98
|
+
});
|
|
99
|
+
const payloadB64 = Buffer.from(json, "utf8").toString("base64url");
|
|
100
|
+
const sig = createHmac("sha256", keyBytes(key)).update(payloadB64).digest();
|
|
101
|
+
return `${TICKET_PREFIX}.${payloadB64}.${b64url(sig)}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Verify `token` against `keys` (current first, then rotation-window predecessors) and `expect`.
|
|
106
|
+
* The HMAC is checked (constant-time) over the transmitted base64url payload segment before the
|
|
107
|
+
* payload is parsed, so a tampered payload fails as `bad-signature`, never as a parse of attacker
|
|
108
|
+
* bytes.
|
|
109
|
+
*/
|
|
110
|
+
export function verify(token: string, keys: readonly Key[], expect: Expect): VerifyResult {
|
|
111
|
+
const parts = splitToken(token);
|
|
112
|
+
if (!parts) return { ok: false, error: "malformed" };
|
|
113
|
+
const [payloadB64, sigB64] = parts;
|
|
114
|
+
if (!B64URL.test(payloadB64) || !B64URL.test(sigB64)) return { ok: false, error: "malformed" };
|
|
115
|
+
|
|
116
|
+
const sig = Buffer.from(sigB64, "base64url");
|
|
117
|
+
const msg = Buffer.from(payloadB64, "utf8");
|
|
118
|
+
const matches = keys.some((k) => {
|
|
119
|
+
const mac = createHmac("sha256", keyBytes(k)).update(msg).digest();
|
|
120
|
+
return mac.length === sig.length && timingSafeEqual(mac, sig);
|
|
121
|
+
});
|
|
122
|
+
if (!matches) return { ok: false, error: "bad-signature" };
|
|
123
|
+
|
|
124
|
+
const payload = parsePayload(payloadB64);
|
|
125
|
+
if (!payload) return { ok: false, error: "malformed" };
|
|
126
|
+
if (payload.app !== expect.app) return { ok: false, error: "wrong-app" };
|
|
127
|
+
if (expect.now > payload.exp) return { ok: false, error: "expired" };
|
|
128
|
+
if (payload.gen < expect.minGen) return { ok: false, error: "stale-generation" };
|
|
129
|
+
return { ok: true, payload };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Extract the `aff.*` ticket from a `Sec-WebSocket-Protocol` header value (a comma list, e.g.
|
|
134
|
+
* `rindle.v1, aff.<…>`). Returns the raw ticket segment for {@link verify}, or `null`. Does not verify.
|
|
135
|
+
*/
|
|
136
|
+
export function wsSubprotocolTicket(header: string): string | null {
|
|
137
|
+
for (const raw of header.split(",")) {
|
|
138
|
+
const p = raw.trim();
|
|
139
|
+
if (isTicketShape(p)) return p;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Whether the header offers the base {@link WS_SUBPROTOCOL} — the daemon must echo it on the 101. */
|
|
145
|
+
export function wsOffersBase(header: string): boolean {
|
|
146
|
+
return header.split(",").some((p) => p.trim() === WS_SUBPROTOCOL);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Extract the ticket from a {@link HEADER_NAME} value. Returns the raw segment, or `null`. */
|
|
150
|
+
export function headerTicket(value: string): string | null {
|
|
151
|
+
const v = value.trim();
|
|
152
|
+
return isTicketShape(v) ? v : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A syntactic ticket = `aff.<seg>.<seg>` with non-empty segments. Cheap prefilter, like the crate. */
|
|
156
|
+
function isTicketShape(s: string): boolean {
|
|
157
|
+
return splitToken(s) !== null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Split into (payloadB64, sigB64), validating the `aff.` prefix and exact 3-segment shape. */
|
|
161
|
+
function splitToken(token: string): [string, string] | null {
|
|
162
|
+
const parts = token.split(".");
|
|
163
|
+
if (parts.length !== 3) return null;
|
|
164
|
+
const [prefix, payloadB64, sigB64] = parts;
|
|
165
|
+
if (prefix !== TICKET_PREFIX || payloadB64.length === 0 || sigB64.length === 0) return null;
|
|
166
|
+
return [payloadB64, sigB64];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function parsePayload(payloadB64: string): Payload | null {
|
|
170
|
+
let value: unknown;
|
|
171
|
+
try {
|
|
172
|
+
value = JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf8"));
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
if (typeof value !== "object" || value === null) return null;
|
|
177
|
+
const p = value as Record<string, unknown>;
|
|
178
|
+
if (
|
|
179
|
+
typeof p.app !== "string" ||
|
|
180
|
+
typeof p.mid !== "string" ||
|
|
181
|
+
typeof p.region !== "string" ||
|
|
182
|
+
typeof p.sub !== "string" ||
|
|
183
|
+
typeof p.iat !== "number" ||
|
|
184
|
+
typeof p.exp !== "number" ||
|
|
185
|
+
typeof p.gen !== "number"
|
|
186
|
+
) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
return { app: p.app, mid: p.mid, region: p.region, sub: p.sub, iat: p.iat, exp: p.exp, gen: p.gen };
|
|
190
|
+
}
|