@particle-academy/fancy-service-token 0.0.0-stage → 0.0.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/AGENTS.md ADDED
@@ -0,0 +1,67 @@
1
+ # Using @particle-academy/fancy-service-token — guide for agents
2
+
3
+ How an agent installs and uses this package in a consumer app. What the package
4
+ is, is in [README.md](./README.md). Notes for working ON this repo's code are in
5
+ [CONTRIBUTING.md](./CONTRIBUTING.md).
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @particle-academy/fancy-service-token
11
+ ```
12
+
13
+ - **Node:** `>=22`. Zero runtime dependencies.
14
+ - The signer is the Laravel package `particle-academy/fancy-service-token`; this
15
+ package only verifies. A Python verifier is `fancy-service-token` on PyPI.
16
+
17
+ ## Find it on the Fancy MCP server
18
+
19
+ The catalog server is `https://ui.particle.academy/mcp` (streamable HTTP, no API
20
+ key; MCP id `fancy-ui`). This package is not yet listed there; it appears once
21
+ published. Find it then with `search-backend-packages` (stack `node`).
22
+
23
+ ## API essentials
24
+
25
+ ```ts
26
+ import { Verifier, serviceTokenMiddleware, currentRequestId } from "@particle-academy/fancy-service-token";
27
+
28
+ const verifier = new Verifier({
29
+ keys: [{ kid: "k2026b", secret: Buffer.from(process.env.SERVICE_TOKEN_KEY!, "hex") }],
30
+ audience: "ocr-sidecar",
31
+ issuer: "laravel-app",
32
+ });
33
+
34
+ app.use(serviceTokenMiddleware({ verifier, log: (e) => logger[e.level](e) })); // before any body parser
35
+ ```
36
+
37
+ - `Verifier.verify(token, now?)` returns `{ ok: true, claims }` or
38
+ `{ ok: false, reason }` and never throws.
39
+ - `serviceTokenMiddleware({ verifier, header, exemptPaths, log })` is
40
+ connect-style `(req, res, next)`: Express, Connect, Polka and bare `node:http`
41
+ all take it. Default header `x-fancy-service-token`.
42
+ - The verified request id is on `req.serviceToken.requestId`, and
43
+ `currentRequestId()` returns it anywhere inside `next()`.
44
+ - `REASONS` is the fixed set of refusal reasons: `missing`, `malformed`,
45
+ `bad_signature`, `expired`, `not_yet_valid`, `wrong_audience`, `replayed`.
46
+ A refusal is `401` with `{"error": "service_token_refused", "reason": "..."}`.
47
+ - Options and defaults (`clockSkew`, `maxLifetime`, `maxTokenBytes`,
48
+ `requireNonce`, `minKeyBytes`, `replayStore`, `clock`) are in the README's
49
+ Configuration table.
50
+
51
+ ## Traps
52
+
53
+ - **Mount the middleware BEFORE any body parser.** It decides from headers alone;
54
+ a parser mounted first reads the body of a request that should be refused.
55
+ - **Secrets must be at least `minKeyBytes` (32) bytes** and passed as bytes
56
+ (`Uint8Array` / `Buffer`), not a string.
57
+ - **`MemoryReplayStore` is per process.** With several processes, supply a
58
+ shared store (anything with `add(key, expiresAt, now): boolean`). A full store
59
+ refuses (`replayed`); `replayStore: null` turns replay checks off.
60
+ - **Key rotation:** sign with the new key in Laravel; here hold both and give
61
+ the old one `acceptUntil` (unix seconds, inclusive).
62
+ - **Stream callbacks** such as `req.on("data")` run outside the request's async
63
+ context; read `req.serviceToken` there, not `currentRequestId()`.
64
+ - **`exemptPaths` are exact path matches** (query string ignored), meant for a
65
+ health check.
66
+ - **A duplicated token header is `malformed`.**
67
+ - **Pre-1.0:** breaking changes land in MINOR releases.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@particle-academy/fancy-service-token` are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ **Pre-1.0, breaking changes land in MINOR releases.** Read those entries before
9
+ upgrading.
10
+
11
+ ## [Unreleased]
12
+
13
+ ## [0.1.0] - 2026-11-18
14
+
15
+ First release (CC-fancy-0030).
16
+
17
+ ### Added
18
+
19
+ - **`Verifier`** for `fst1` service tokens: HMAC-SHA256 with `node:crypto`
20
+ (`createHmac`, `timingSafeEqual`), no JWT library, zero runtime dependencies.
21
+ `verify()` never throws and refuses with one reason from a fixed set:
22
+ `missing`, `malformed`, `bad_signature`, `expired`, `not_yet_valid`,
23
+ `wrong_audience`, `replayed`.
24
+ - **Key rotation:** a previous key with `acceptUntil` is accepted until then,
25
+ and is `bad_signature` after.
26
+ - **Every limit is configurable, with secure defaults:** `clockSkew` 10 s,
27
+ `maxLifetime` 300 s, `maxTokenBytes` 1024, `requireNonce` on, keys of at
28
+ least 32 bytes, and a per-process `MemoryReplayStore` (100,000 entries, fails
29
+ closed when full).
30
+ - **`serviceTokenMiddleware`**, connect-style, for Express, Connect, Polka and
31
+ bare `node:http`: refuses with `401` from the headers alone, never reading the
32
+ body and never calling `next()`; sets `Connection: close` on a refusal.
33
+ - **The verified request id** on `req.serviceToken` and in `currentRequestId()`
34
+ (AsyncLocalStorage), plus structured `log` events that never carry a token,
35
+ nonce or secret.
36
+ - **Shared conformance fixtures** (`conformance/service-token-v1.json`), the
37
+ same bytes as the PHP and Python legs, pinned by SHA-256; and a sabotage sweep
38
+ in CI.
39
+
40
+ ### Changed
41
+
42
+ - **CI: the lab-certificate gate verifies against the lab's rotated key list.**
43
+ The lab's first signing key is retired: certificates it already issued still
44
+ verify, and nothing new it signs ever can. Consumers do nothing.
45
+
46
+ - **Docs:** `AGENTS.md` is now the guide to using this package (install, how to find it on the Fancy MCP catalog server once it is listed, API essentials, traps), and it ships in the package. The contributor notes it held moved to `CONTRIBUTING.md`, and `CLAUDE.md` is now a symlink to it. The README points to the MCP server and to `AGENTS.md`. No code changed; nothing to do.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Particle Academy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,168 @@
1
- # Temporary Holding Version
1
+ # @particle-academy/fancy-service-token
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
+ Verify Fancy service tokens in a Node sidecar. A Laravel app signs a
4
+ short-lived token on every request it makes to its sidecar
5
+ ([`particle-academy/fancy-service-token`](https://github.com/Particle-Academy/fancy-service-token));
6
+ this package checks it **before the request body is read** and refuses every
7
+ other caller with a named reason.
8
+
9
+ - The verifier mirror of the PHP signer and the Python verifier
10
+ ([`fancy-service-token`](https://github.com/Particle-Academy/fancy-service-token-py) on PyPI).
11
+ All three run the same fixture file byte for byte.
12
+ - HMAC-SHA256 with `node:crypto` only (`createHmac`, `timingSafeEqual`). No JWT
13
+ library, no cryptography of our own, zero runtime dependencies.
14
+ - Refusals carry one reason from a fixed set, never exception text; nothing it
15
+ logs contains a token, a nonce or a secret.
16
+
17
+ <!-- fancy-agents-note:start -->
18
+ > **For agents.** This package is not listed on the Fancy MCP catalog server
19
+ > yet. The server, `https://ui.particle.academy/mcp` (streamable HTTP, no API key; MCP id
20
+ > `fancy-ui`), lists the released Fancy packages with install commands and
21
+ > docs. How an agent installs and uses this package is in [AGENTS.md](https://github.com/Particle-Academy/fancy-service-token-js/blob/main/AGENTS.md).
22
+ <!-- fancy-agents-note:end -->
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ npm install @particle-academy/fancy-service-token
28
+ ```
29
+
30
+ Node 22 or later.
31
+
32
+ ## Use
33
+
34
+ ```ts
35
+ import express from "express";
36
+ import { Verifier, serviceTokenMiddleware, currentRequestId } from "@particle-academy/fancy-service-token";
37
+
38
+ const verifier = new Verifier({
39
+ keys: [{ kid: "k2026b", secret: Buffer.from(process.env.SERVICE_TOKEN_KEY!, "hex") }],
40
+ audience: "ocr-sidecar",
41
+ issuer: "laravel-app",
42
+ });
43
+
44
+ const app = express();
45
+ app.use(serviceTokenMiddleware({ verifier, log: (e) => logger[e.level](e) })); // BEFORE any body parser
46
+ app.use(express.json());
47
+
48
+ app.post("/ocr", (req, res) => {
49
+ const { requestId } = req.serviceToken!;
50
+ });
51
+ ```
52
+
53
+ The middleware is connect-style `(req, res, next)`, so Express, Connect, Polka
54
+ and a bare `node:http` handler all take it. **Mount it before any body parser**:
55
+ it decides from `req.headers` alone and, on a refusal, never reads the body and
56
+ never calls `next()`. The refusal also sets `Connection: close`, so the unread
57
+ body is not parsed as a next request on the socket.
58
+
59
+ `Verifier.verify(token, now?)` works without the middleware too, and never
60
+ throws: it returns `{ ok: true, claims }` or `{ ok: false, reason }`.
61
+
62
+ ## Refusals
63
+
64
+ `401`, `Cache-Control: no-store`, `WWW-Authenticate: FancyServiceToken error="<reason>"`:
65
+
66
+ ```json
67
+ {"error": "service_token_refused", "reason": "expired"}
68
+ ```
69
+
70
+ | reason | means |
71
+ |---|---|
72
+ | `missing` | no token header, or an empty one |
73
+ | `malformed` | not a well-formed `fst1` token, longer than `maxTokenBytes`, a lifetime above `maxLifetime`, no nonce while `requireNonce` is on, or the header sent twice |
74
+ | `bad_signature` | HMAC mismatch, unknown key id, a previous key past its grace window, or an issuer other than the configured one |
75
+ | `expired` | `now >= exp + clockSkew` |
76
+ | `not_yet_valid` | `now + clockSkew < iat` |
77
+ | `wrong_audience` | signed correctly, for a different sidecar |
78
+ | `replayed` | the nonce was already accepted (or the replay store is full: it fails closed) |
79
+
80
+ ## Request id
81
+
82
+ The caller's request id is signed into the token. After verification it is on
83
+ `req.serviceToken.requestId` and, for code running inside `next()` (including
84
+ after an `await`), in `currentRequestId()`. Stream event callbacks such as
85
+ `req.on("data")` are emitted from the socket's own async context, so read
86
+ `req.serviceToken` there. The `log` option receives `{ level, message, reason?,
87
+ requestId?, errorClass? }` events.
88
+
89
+ ## Configuration
90
+
91
+ | option | default | |
92
+ |---|---|---|
93
+ | `keys` | required | `{ kid, secret: Uint8Array, acceptUntil? }`; secrets of at least `minKeyBytes` |
94
+ | `audience` | required | this sidecar's name |
95
+ | `issuer` | required | the Laravel app's name |
96
+ | `clockSkew` | `10` | seconds of tolerance on both ends |
97
+ | `maxLifetime` | `300` | the longest `exp - iat` accepted |
98
+ | `maxTokenBytes` | `1024` | checked before any parsing |
99
+ | `requireNonce` | `true` | |
100
+ | `minKeyBytes` | `32` | |
101
+ | `replayStore` | `new MemoryReplayStore()` | anything with `add(key, expiresAt, now): boolean`; `null` turns replay checks off |
102
+ | `clock` | `Date.now` | milliseconds |
103
+
104
+ `serviceTokenMiddleware({ verifier, header = "x-fancy-service-token", exemptPaths = [], log })`.
105
+ `exemptPaths` are exact path matches (the query string is ignored), for a health
106
+ check. `MemoryReplayStore(maxEntries = 100_000)` is per process; run several
107
+ processes and you need a shared store.
108
+
109
+ ### Key rotation
110
+
111
+ Sign with the new key in Laravel; here, hold both and give the old one an
112
+ `acceptUntil` (unix seconds, inclusive):
113
+
114
+ ```ts
115
+ keys: [{ kid: "k2026b", secret: next }, { kid: "k2026a", secret: previous, acceptUntil: 1793000030 }]
116
+ ```
117
+
118
+ ## The token format (`fst1`)
119
+
120
+ ```
121
+ fst1.<payload>.<signature>
122
+ ```
123
+
124
+ - `payload` is the **unpadded base64url** (RFC 4648 section 5) of seven ASCII
125
+ fields joined by a single LF (`0x0A`), in this order, with no trailing LF:
126
+
127
+ | # | field | grammar |
128
+ |---|---|---|
129
+ | 1 | `kid` key id | 1-64 of `[A-Za-z0-9._-]` |
130
+ | 2 | `iss` issuer | 1-128 of `[A-Za-z0-9._:/-]` |
131
+ | 3 | `aud` audience | 1-128 of `[A-Za-z0-9._:/-]` |
132
+ | 4 | `iat` issued at | unix seconds, decimal, 1-12 digits, no leading zero |
133
+ | 5 | `exp` expires at | as `iat`; must be greater than `iat` |
134
+ | 6 | `rid` request id | 1-128 of `[A-Za-z0-9._:-]` |
135
+ | 7 | `nonce` | empty, or 16-128 of `[A-Za-z0-9_-]` |
136
+
137
+ - `signature` is the unpadded base64url of
138
+ `HMAC-SHA256(secret, ASCII("fst1." + payload))`: 32 bytes, so 43 characters.
139
+ - base64url must be **canonical**: right alphabet, no padding, no whitespace,
140
+ and the unused low bits of the last character clear.
141
+ - Sent in one header, `X-Fancy-Service-Token` by default.
142
+
143
+ Checks run in this order and stop at the first failure (the fixtures pin it):
144
+
145
+ 1. absent or empty: `missing`
146
+ 2. longer than `maxTokenBytes`: `malformed`
147
+ 3. not three dot-separated parts, prefix not `fst1`, signature not 43
148
+ characters, either part not canonical base64url: `malformed`
149
+ 4. payload not ASCII, not seven fields, a field outside its grammar,
150
+ `exp <= iat`, `exp - iat > maxLifetime`, or no nonce while one is required:
151
+ `malformed`
152
+ 5. unknown `kid`, HMAC mismatch (constant time), a previous key past
153
+ `acceptUntil`, or `iss` not the configured issuer: `bad_signature`
154
+ 6. `aud` not this sidecar: `wrong_audience`
155
+ 7. `now + clockSkew < iat`: `not_yet_valid`
156
+ 8. `now >= exp + clockSkew`: `expired`
157
+ 9. nonce already recorded: `replayed`. Recorded only here, so a token refused
158
+ for an earlier reason never spends one.
159
+
160
+ ## Conformance
161
+
162
+ `conformance/service-token-v1.json` is the shared fixture file, generated in
163
+ `fancy-service-token-py` from the format definition alone and copied here byte
164
+ for byte; the suite pins its SHA-256.
165
+
166
+ ## License
167
+
168
+ MIT