@joe-broadhead/opencode-mem 0.9.14 → 0.11.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/CHANGELOG.md +1856 -0
- package/README.md +15 -7
- package/SECURITY.md +3 -1
- package/docs/agent-instructions.md +1 -1
- package/docs/agent-protocol.md +7 -7
- package/docs/permissions.md +16 -0
- package/package.json +8921 -1070
- package/shared/page-paths.js +44 -0
- package/skills/mem.pages/SKILL.md +3 -1
- package/skills/mem.usage/SKILL.md +15 -15
- package/src/action-grant-keys.js +159 -0
- package/src/action-grant.js +439 -0
- package/src/actions.js +1690 -0
- package/src/backend/records.js +25 -2
- package/src/backend/v3.js +76 -22
- package/src/call-shapes.js +17 -16
- package/src/collector-lock.js +533 -62
- package/src/collector-service.js +153 -26
- package/src/collector.js +623 -30
- package/src/config.js +88 -7
- package/src/connect.js +106 -8
- package/src/credentials.js +123 -25
- package/src/events.js +174 -3
- package/src/forget-turn.js +141 -0
- package/src/host-refusal.js +78 -0
- package/src/index.js +209 -22
- package/src/jobs/host.js +557 -0
- package/src/ops/codes.js +110 -0
- package/src/ops/copy-lineage.js +42 -0
- package/src/ops/index.js +28 -0
- package/src/ops/space-ops.js +1936 -0
- package/src/outlinks.js +103 -0
- package/src/p2-reservation.js +151 -0
- package/src/permissions.js +30 -0
- package/src/plugins/descriptor.js +62 -0
- package/src/plugins/discovery.js +318 -0
- package/src/plugins/grants.js +178 -0
- package/src/plugins/locate.js +319 -0
- package/src/plugins/manifest.js +1162 -0
- package/src/plugins/source-contract/index.js +34 -0
- package/src/plugins/source-contract/policy.js +102 -0
- package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
- package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
- package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
- package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
- package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
- package/src/plugins/source-contract/vendor/broker-client.js +93 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/plugins/source-contract/vendor/cursor.js +26 -0
- package/src/plugins/source-contract/vendor/descriptor.js +34 -0
- package/src/plugins/source-contract/vendor/events.js +257 -0
- package/src/plugins/source-contract/vendor/index.js +10 -0
- package/src/plugins/source-contract/vendor/params.js +22 -0
- package/src/plugins/source-contract/vendor/permission.js +28 -0
- package/src/plugins/source-contract/vendor/pick.js +22 -0
- package/src/plugins/source-contract/vendor/read.js +29 -0
- package/src/plugins/source-contract/vendor/registry.js +23 -0
- package/src/plugins/source-contract/vendor/schema.js +17 -0
- package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
- package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
- package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
- package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
- package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
- package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
- package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
- package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
- package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
- package/src/plugins/source-contract/vendor/schemas.js +19 -0
- package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
- package/src/plugins/verify.js +56 -0
- package/src/protocol.js +11 -6
- package/src/recall.js +92 -5
- package/src/records.js +61 -2
- package/src/requests.js +216 -0
- package/src/runtime.js +89 -7
- package/src/setup-time.js +68 -0
- package/src/skills.js +230 -8
- package/src/source-ids.js +25 -0
- package/src/sources/declaration.js +365 -0
- package/src/sources/reads.js +772 -0
- package/src/sources/rpc.js +151 -0
- package/src/sources.js +389 -92
- package/src/spaces.js +283 -11
- package/src/spool.js +61 -4
- package/src/stated.js +10 -5
- package/src/storable.js +139 -0
- package/src/tools/commitments.js +74 -23
- package/src/tools/held-write.js +46 -19
- package/src/tools/index.js +28 -0
- package/src/tools/ingest.js +38 -2
- package/src/tools/memory.js +56 -25
- package/src/tools/page.js +212 -95
- package/src/tools/recall.js +218 -4
- package/src/tools/share.js +42 -3
- package/src/tools/shared.js +84 -6
- package/src/tools/space-lifecycle.js +278 -0
- package/src/tools/spaces.js +381 -30
- package/src/tools/status.js +9 -2
- package/src/tools/wiki.js +231 -116
- package/src/util.js +110 -6
- package/src/vendor/source-contract/README.md +24 -0
- package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
- package/src/vendor/source-contract/VENDOR.json +81 -0
- package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/vendor/source-contract/cursor.js +26 -0
- package/src/vendor/source-contract/events.js +257 -0
- package/src/vendor/source-contract/registry.js +23 -0
- package/src/vendor/source-contract/tools-rpc.js +42 -0
- package/src/views/access-reads.js +256 -0
- package/src/views/communities.js +77 -0
- package/src/views/contracts.js +1082 -23
- package/src/views/inbox-bytes.js +103 -0
- package/src/views/profile.js +31 -0
- package/src/views/receipt.js +26 -1
- package/src/views/records-reads.js +520 -41
- package/src/views/rpc.js +153 -25
- package/src/views/shape.js +8 -5
- package/src/views/write-state.js +89 -0
- package/src/wiki-ingest.js +215 -0
- package/src/wiki-state.js +228 -0
- package/views/pages.html +2 -2
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The verified-caller action grant (`jelly-act+jwt`), claims spec v1:
|
|
3
|
+
* docs/design/adr-verified-caller-grants.md §4.1, §4.2 and §4.4. A host signs
|
|
4
|
+
* one grant per click with its own Ed25519 key, over the digest of the exact
|
|
5
|
+
* input it is asked to apply. Memory verifies it against public keys read from
|
|
6
|
+
* a file.
|
|
7
|
+
*
|
|
8
|
+
* One library, several callers: the plugin, the records service, control and
|
|
9
|
+
* the gateway each vendor a byte-identical copy (`npm run check:copies`), and
|
|
10
|
+
* each service that applies an act keeps its own replay ledger. This file is
|
|
11
|
+
* therefore self-contained: `node:crypto` only, no imports from the service
|
|
12
|
+
* that carries it, and no I/O. The key file's reading is `action-grant-keys`.
|
|
13
|
+
*
|
|
14
|
+
* A check that fails returns `{ok: false, code}` with one of the §4.9 codes.
|
|
15
|
+
* Nothing from the claims is read before the signature verifies, and nothing
|
|
16
|
+
* about the token is logged: a verifier that explains why it refused is a
|
|
17
|
+
* verifier that tells an attacker which byte to change.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash, createPublicKey, verify as verifySignature } from "node:crypto"
|
|
20
|
+
|
|
21
|
+
/** The package and target every act of this service is bound to (§4.1). */
|
|
22
|
+
export const GRANT_AUDIENCE = "@joe-broadhead/opencode-mem#engine"
|
|
23
|
+
/** The header `typ` Jelly's host writes, unless its key entry names another. */
|
|
24
|
+
export const GRANT_TYP = "jelly-act+jwt"
|
|
25
|
+
/** A grant is at most this many bytes: the size Jelly's relay allows (§4.1). */
|
|
26
|
+
export const MAX_GRANT_BYTES = 4096
|
|
27
|
+
/** The input is at most this many bytes of canonical JSON, and this deep (§4.4). */
|
|
28
|
+
export const MAX_INPUT_BYTES = 64 * 1024
|
|
29
|
+
export const MAX_INPUT_DEPTH = 16
|
|
30
|
+
/** A key file is refused whole past these limits (§4.3). */
|
|
31
|
+
export const MAX_KEYS_BYTES = 4 * 1024 * 1024
|
|
32
|
+
export const MAX_KEYS = 10_000
|
|
33
|
+
/** A grant's lifetime, and the skew allowed each way (§4.1). */
|
|
34
|
+
export const MAX_LIFETIME_SECONDS = 60
|
|
35
|
+
export const CLOCK_SKEW_SECONDS = 5
|
|
36
|
+
/** The route classes a host signs, weakest first. `view` never authorises an act. */
|
|
37
|
+
export const GRANT_CLASSES = Object.freeze({ chat: 1, local: 2 })
|
|
38
|
+
/**
|
|
39
|
+
* The identity issuer of an API key or a console session (§4.5). A grant acts
|
|
40
|
+
* only for a member of a host-signed identity, so a key entry that binds itself
|
|
41
|
+
* to this issuer would turn every API key into a caller that can carry one: the
|
|
42
|
+
* file is refused.
|
|
43
|
+
*/
|
|
44
|
+
export const API_KEY_ISSUER = "better-auth"
|
|
45
|
+
/** The JSON types an act may declare for one of its input keys. */
|
|
46
|
+
export const INPUT_TYPES = Object.freeze(["string", "integer", "boolean", "object", "array", "null"])
|
|
47
|
+
|
|
48
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/
|
|
49
|
+
const BASE64URL_43 = /^[A-Za-z0-9_-]{43}$/
|
|
50
|
+
/** A pulled_at that names an instant: the date, the time, and a zone. */
|
|
51
|
+
const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/
|
|
52
|
+
const JTI = /^[A-Za-z0-9_-]{22,128}$/
|
|
53
|
+
const KEY_ALG = "EdDSA"
|
|
54
|
+
const KEY_CRV = "Ed25519"
|
|
55
|
+
const KEY_KTY = "OKP"
|
|
56
|
+
|
|
57
|
+
/** Why a value cannot be canonicalised: a lone surrogate, or a number that is not a safe integer. */
|
|
58
|
+
export class InputNotCanonical extends Error {
|
|
59
|
+
constructor(message) {
|
|
60
|
+
super(message)
|
|
61
|
+
this.name = "InputNotCanonical"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// §4.2 Canonicalisation and the input digest
|
|
67
|
+
|
|
68
|
+
/** The canonical JSON of an action input, byte for byte what the host signed. */
|
|
69
|
+
export function canonicalJson(value) {
|
|
70
|
+
// A missing input is `null` (§4.2 rule 4).
|
|
71
|
+
return writeCanonical(value === undefined ? null : value, 1)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function writeCanonical(value, depth) {
|
|
75
|
+
if (depth > MAX_INPUT_DEPTH) throw new InputNotCanonical(`the input is nested deeper than ${MAX_INPUT_DEPTH}`)
|
|
76
|
+
if (value === null) return "null"
|
|
77
|
+
if (typeof value === "boolean") return value ? "true" : "false"
|
|
78
|
+
if (typeof value === "number") {
|
|
79
|
+
// Only safe integers: ECMAScript's number formatting never matters, so this
|
|
80
|
+
// is RFC 8785 for the inputs Memory accepts (§4.2).
|
|
81
|
+
if (!Number.isSafeInteger(value)) throw new InputNotCanonical("a number in the input is not a safe integer")
|
|
82
|
+
return JSON.stringify(value)
|
|
83
|
+
}
|
|
84
|
+
if (typeof value === "string") return JSON.stringify(checkString(value))
|
|
85
|
+
if (typeof value !== "object" || value === undefined) throw new InputNotCanonical(`an input value of type ${typeof value} cannot be canonicalised`)
|
|
86
|
+
if (Array.isArray(value)) {
|
|
87
|
+
const items = value.map((item) => {
|
|
88
|
+
if (item === undefined) throw new InputNotCanonical("an array in the input holds undefined")
|
|
89
|
+
return writeCanonical(item, depth + 1)
|
|
90
|
+
})
|
|
91
|
+
return `[${items.join(",")}]`
|
|
92
|
+
}
|
|
93
|
+
const prototype = Object.getPrototypeOf(value)
|
|
94
|
+
if (prototype !== Object.prototype && prototype !== null) throw new InputNotCanonical("an input object is not a plain JSON object")
|
|
95
|
+
// Members whose value is undefined are absent, as JSON.stringify writes them,
|
|
96
|
+
// and keys sort by UTF-16 code unit, which is what `<` on strings compares.
|
|
97
|
+
const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort()
|
|
98
|
+
return `{${keys.map((key) => `${JSON.stringify(checkString(key))}:${writeCanonical(value[key], depth + 1)}`).join(",")}}`
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A string may hold no lone surrogate: JSON.stringify escapes one, and JCS forbids one. */
|
|
102
|
+
function checkString(value) {
|
|
103
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
104
|
+
const unit = value.charCodeAt(index)
|
|
105
|
+
if (unit < 0xd800 || unit > 0xdfff) continue
|
|
106
|
+
if (unit > 0xdbff) throw new InputNotCanonical("a string in the input holds a lone surrogate")
|
|
107
|
+
const next = value.charCodeAt(index + 1)
|
|
108
|
+
if (!(next >= 0xdc00 && next <= 0xdfff)) throw new InputNotCanonical("a string in the input holds a lone surrogate")
|
|
109
|
+
index += 1
|
|
110
|
+
}
|
|
111
|
+
return value
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The grant's `in`: base64url, without padding, of SHA-256 over the UTF-8 bytes
|
|
116
|
+
* of the canonical input. A missing input is `null` (§4.2).
|
|
117
|
+
*
|
|
118
|
+
* @throws {InputNotCanonical} for a lone surrogate or a number that is not a safe integer
|
|
119
|
+
*/
|
|
120
|
+
export function actionInputDigest(input) {
|
|
121
|
+
return createHash("sha256").update(canonicalJson(input), "utf8").digest("base64url")
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// §4.3 The key file (its reading from disk is action-grant-keys)
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The RFC 7638 thumbprint of a public key: SHA-256 over the required members
|
|
129
|
+
* `crv`, `kty` and `x` in lexicographic order, base64url. It is the grant's
|
|
130
|
+
* `kid` and the key file's `kid`, so a key file entry names itself.
|
|
131
|
+
*/
|
|
132
|
+
export function keyThumbprint(jwk) {
|
|
133
|
+
if (!jwk || typeof jwk !== "object") throw new TypeError("keyThumbprint: a JWK is required")
|
|
134
|
+
const members = ['"crv"', '"kty"', '"x"'].map((name) => {
|
|
135
|
+
const value = jwk[name.slice(1, -1)]
|
|
136
|
+
if (typeof value !== "string" || !value) throw new TypeError(`keyThumbprint: the JWK has no ${name}`)
|
|
137
|
+
return `${name}:${JSON.stringify(value)}`
|
|
138
|
+
})
|
|
139
|
+
return createHash("sha256").update(`{${members.join(",")}}`, "utf8").digest("base64url")
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Parse and validate a key file (§4.3): the hosts' public keys and the members
|
|
144
|
+
* that bind each to the identity issuer whose subjects its grants name.
|
|
145
|
+
*
|
|
146
|
+
* The whole file is refused when it is not valid JSON, holds a private member
|
|
147
|
+
* `d`, repeats a `kid`, carries a `kid` that is not the key's thumbprint, holds
|
|
148
|
+
* a key that is not Ed25519, or is over 4 MiB or 10,000 keys.
|
|
149
|
+
*
|
|
150
|
+
* @param {string} text the file's text
|
|
151
|
+
* @param {{ audience?: string }} [options]
|
|
152
|
+
* @returns {{ ok: true, entries: Array<object>, pulledAt: number | null } | { ok: false, error: string }}
|
|
153
|
+
*/
|
|
154
|
+
export function parseActionKeys(text, { audience = GRANT_AUDIENCE } = {}) {
|
|
155
|
+
if (typeof text !== "string") return refuseKeys("the key file is not text")
|
|
156
|
+
if (Buffer.byteLength(text, "utf8") > MAX_KEYS_BYTES) return refuseKeys(`the key file is over ${MAX_KEYS_BYTES} bytes`)
|
|
157
|
+
let parsed
|
|
158
|
+
try {
|
|
159
|
+
parsed = JSON.parse(text)
|
|
160
|
+
} catch {
|
|
161
|
+
return refuseKeys("the key file is not valid JSON")
|
|
162
|
+
}
|
|
163
|
+
if (!isPlainObject(parsed) || !Array.isArray(parsed.keys)) return refuseKeys('the key file is not {"keys": [...]}')
|
|
164
|
+
if (hasPrivateMember(parsed)) return refuseKeys("the key file holds a private member d")
|
|
165
|
+
if (parsed.keys.length > MAX_KEYS) return refuseKeys(`the key file holds more than ${MAX_KEYS} keys`)
|
|
166
|
+
// The puller stamps when it last wrote the file (§4.3); the age limit reads
|
|
167
|
+
// it, so a date the file cannot name is refused rather than guessed. Only a
|
|
168
|
+
// full ISO 8601 timestamp with a zone names an instant: "2026" is a year,
|
|
169
|
+
// not a time, and would read as one the age limit can trust.
|
|
170
|
+
let pulledAt = null
|
|
171
|
+
if (parsed.pulled_at !== undefined) {
|
|
172
|
+
if (typeof parsed.pulled_at !== "string" || !ISO_TIMESTAMP.test(parsed.pulled_at) || !Number.isFinite(Date.parse(parsed.pulled_at))) {
|
|
173
|
+
return refuseKeys("the key file's pulled_at is not a full ISO 8601 timestamp with a zone")
|
|
174
|
+
}
|
|
175
|
+
pulledAt = Date.parse(parsed.pulled_at)
|
|
176
|
+
}
|
|
177
|
+
const entries = []
|
|
178
|
+
const seen = new Set()
|
|
179
|
+
for (const raw of parsed.keys) {
|
|
180
|
+
const entry = parseActionKey(raw, audience)
|
|
181
|
+
if (!entry.ok) return entry
|
|
182
|
+
if (seen.has(entry.value.kid)) return refuseKeys(`the key file repeats the kid ${entry.value.kid}`)
|
|
183
|
+
seen.add(entry.value.kid)
|
|
184
|
+
entries.push(entry.value)
|
|
185
|
+
}
|
|
186
|
+
return { ok: true, entries, pulledAt }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function refuseKeys(error) {
|
|
190
|
+
return { ok: false, error }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function hasPrivateMember(value, depth = 0) {
|
|
194
|
+
if (!value || typeof value !== "object" || depth > 4) return false
|
|
195
|
+
if (!Array.isArray(value) && Object.hasOwn(value, "d")) return true
|
|
196
|
+
return Object.values(value).some((child) => hasPrivateMember(child, depth + 1))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function isPlainObject(value) {
|
|
200
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function textOf(value, max = 128) {
|
|
204
|
+
return typeof value === "string" && value.length >= 1 && value.length <= max ? value : null
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** One entry of the key file, with the public key built and checked by Node. */
|
|
208
|
+
function parseActionKey(raw, audience) {
|
|
209
|
+
if (!isPlainObject(raw)) return refuseKeys("a key entry is not an object")
|
|
210
|
+
const where = typeof raw.kid === "string" ? ` (${raw.kid.slice(0, 64)})` : ""
|
|
211
|
+
if (raw.kty !== KEY_KTY || raw.crv !== KEY_CRV) return refuseKeys(`a key entry is not ${KEY_KTY}/${KEY_CRV}${where}`)
|
|
212
|
+
if (typeof raw.x !== "string" || !BASE64URL_43.test(raw.x)) return refuseKeys(`a key entry's x is not 43 base64url characters${where}`)
|
|
213
|
+
if (raw.alg !== undefined && raw.alg !== KEY_ALG) return refuseKeys(`a key entry's alg is not ${KEY_ALG}${where}`)
|
|
214
|
+
if (raw.use !== undefined && raw.use !== "sig") return refuseKeys('a key entry\'s use is not "sig"')
|
|
215
|
+
const iss = textOf(raw.iss)
|
|
216
|
+
if (!iss) return refuseKeys(`a key entry has no iss, or one that is not 1 to 128 characters${where}`)
|
|
217
|
+
const mbrIss = textOf(raw.mbr_iss)
|
|
218
|
+
if (!mbrIss) return refuseKeys(`a key entry has no mbr_iss, or one that is not 1 to 128 characters${where}`)
|
|
219
|
+
// §4.5: an API key or a console session never carries a grant, so no key may
|
|
220
|
+
// bind itself to that issuer.
|
|
221
|
+
if (mbrIss.toLowerCase() === API_KEY_ISSUER) {
|
|
222
|
+
return refuseKeys(`a key entry names mbr_iss ${API_KEY_ISSUER}: an API key never carries a grant`)
|
|
223
|
+
}
|
|
224
|
+
if (raw.aud !== undefined && !textOf(raw.aud)) return refuseKeys(`a key entry's aud is not 1 to 128 characters${where}`)
|
|
225
|
+
if (raw.typ !== undefined && !textOf(raw.typ)) return refuseKeys(`a key entry's typ is not 1 to 128 characters${where}`)
|
|
226
|
+
if (raw.extra_input !== undefined && (!Array.isArray(raw.extra_input) || raw.extra_input.some((key) => !textOf(key)))) {
|
|
227
|
+
return refuseKeys(`a key entry's extra_input is not a list of input keys${where}`)
|
|
228
|
+
}
|
|
229
|
+
// Jelly's answer 7: `jellySpeaker` is the only key a host adds before it
|
|
230
|
+
// signs. An entry that would let another key ride along is refused whole.
|
|
231
|
+
if (Array.isArray(raw.extra_input) && raw.extra_input.some((key) => key !== "jellySpeaker")) {
|
|
232
|
+
return refuseKeys(`a key entry's extra_input names a key a host does not add${where}`)
|
|
233
|
+
}
|
|
234
|
+
const thumbprint = keyThumbprint(raw)
|
|
235
|
+
if (raw.kid !== thumbprint) return refuseKeys("a key entry's kid is not the thumbprint of its key")
|
|
236
|
+
let key
|
|
237
|
+
try {
|
|
238
|
+
key = createPublicKey({ key: { kty: KEY_KTY, crv: KEY_CRV, x: raw.x }, format: "jwk" })
|
|
239
|
+
} catch {
|
|
240
|
+
return refuseKeys(`a key entry's x is not an Ed25519 public key${where}`)
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
ok: true,
|
|
244
|
+
value: {
|
|
245
|
+
kid: thumbprint,
|
|
246
|
+
iss,
|
|
247
|
+
mbrIss,
|
|
248
|
+
aud: textOf(raw.aud) ?? audience,
|
|
249
|
+
typ: textOf(raw.typ) ?? GRANT_TYP,
|
|
250
|
+
extraInput: Array.isArray(raw.extra_input) ? [...new Set(raw.extra_input)] : [],
|
|
251
|
+
key,
|
|
252
|
+
},
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// §4.4 The verifier
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Verify one grant for one act and one input.
|
|
261
|
+
*
|
|
262
|
+
* @param {object} options
|
|
263
|
+
* @param {unknown} options.grant the compact JWS the host signed
|
|
264
|
+
* @param {unknown} options.input the input the caller asks to apply
|
|
265
|
+
* @param {string} options.act the act being called
|
|
266
|
+
* @param {Record<string, { minClass?: "chat" | "local", inputKeys?: string[] }>} options.allowed
|
|
267
|
+
* the acts this service applies now, and each act's closed input schema
|
|
268
|
+
* @param {{ entries: Array<object> }} options.keys the loaded key file
|
|
269
|
+
* @param {string} [options.audience] this service's audience (§4.1)
|
|
270
|
+
* @param {number} [options.now] the clock, in seconds
|
|
271
|
+
* @returns {{ ok: true, claims: object, entry: object } | { ok: false, code: string, detail: string }}
|
|
272
|
+
*/
|
|
273
|
+
export function verifyActionGrant({ grant, input, act, allowed = {}, keys = null, audience = GRANT_AUDIENCE, now = Math.floor(Date.now() / 1000) } = {}) {
|
|
274
|
+
// 1. Size and shape.
|
|
275
|
+
if (typeof grant !== "string") return refuse("grant_malformed", "the grant is not a string")
|
|
276
|
+
if (Buffer.byteLength(grant, "utf8") > MAX_GRANT_BYTES) return refuse("grant_malformed", `the grant is over ${MAX_GRANT_BYTES} bytes`)
|
|
277
|
+
const parts = grant.split(".")
|
|
278
|
+
if (parts.length !== 3) return refuse("grant_malformed", "the grant is not three dot-separated parts")
|
|
279
|
+
const [headerPart, payloadPart, signaturePart] = parts
|
|
280
|
+
if (!BASE64URL.test(headerPart) || !BASE64URL.test(payloadPart)) return refuse("grant_malformed", "a grant part is not base64url")
|
|
281
|
+
if (!isStrictBase64url(headerPart) || !isStrictBase64url(payloadPart)) return refuse("grant_malformed", "a grant part is not canonical base64url")
|
|
282
|
+
// The signature's shape is checked after the header: `alg: none` carries an empty one.
|
|
283
|
+
if (signaturePart !== "" && (!BASE64URL.test(signaturePart) || !isStrictBase64url(signaturePart))) {
|
|
284
|
+
return refuse("grant_malformed", "the signature is not canonical base64url")
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// The input is read last, after the signature verifies: a caller with no key
|
|
288
|
+
// learns nothing about how inputs are handled. Its canonical form is at most
|
|
289
|
+
// 64 KiB of JSON, nested at most 16 deep (§4.4 step 1), and a lone surrogate
|
|
290
|
+
// or a number that is not a safe integer is step 10's business.
|
|
291
|
+
|
|
292
|
+
// 2. Header: exactly alg, typ and kid, so no `jwk`, `jku`, `x5u`, `x5c`, `crit` or `b64` can ride along.
|
|
293
|
+
const header = parsePart(headerPart)
|
|
294
|
+
if (!isPlainObject(header)) return refuse("grant_malformed", "the header is not a JSON object")
|
|
295
|
+
const headerKeys = Object.keys(header).sort()
|
|
296
|
+
if (headerKeys.length !== 3 || headerKeys[0] !== "alg" || headerKeys[1] !== "kid" || headerKeys[2] !== "typ") {
|
|
297
|
+
return refuse("grant_alg", "the header is not exactly alg, typ and kid")
|
|
298
|
+
}
|
|
299
|
+
if (header.alg !== KEY_ALG) return refuse("grant_alg", `alg is not ${KEY_ALG}`)
|
|
300
|
+
|
|
301
|
+
// 3. Key: from the file, never from the token.
|
|
302
|
+
const entries = Array.isArray(keys?.entries) ? keys.entries : []
|
|
303
|
+
if (entries.length === 0) return refuse("grant_unavailable", "no action key is loaded")
|
|
304
|
+
// §4.3: a file older than the operator's limit no longer verifies a grant.
|
|
305
|
+
// A revoked host must stop acting, and a stale pull must never look fresh.
|
|
306
|
+
if (keys?.stale === true) return refuse("grant_keys_stale", "the action key file is older than the allowed age")
|
|
307
|
+
if (typeof header.kid !== "string") return refuse("grant_malformed", "the header has no kid")
|
|
308
|
+
const entry = entries.find((candidate) => candidate.kid === header.kid)
|
|
309
|
+
if (!entry) return refuse("grant_unknown_key", "the kid is not in the key file")
|
|
310
|
+
if (header.typ !== entry.typ) return refuse("grant_alg", "the header's typ is not the key entry's")
|
|
311
|
+
|
|
312
|
+
// 4. Signature: Ed25519 over the ASCII bytes of header.payload, 64 bytes.
|
|
313
|
+
const signature = signaturePart === "" ? null : Buffer.from(signaturePart, "base64url")
|
|
314
|
+
if (!signature || signature.length !== 64) return refuse("grant_signature", "the signature is not 64 bytes")
|
|
315
|
+
let signed = false
|
|
316
|
+
try {
|
|
317
|
+
signed = verifySignature(null, Buffer.from(`${headerPart}.${payloadPart}`, "ascii"), entry.key, signature)
|
|
318
|
+
} catch {
|
|
319
|
+
signed = false
|
|
320
|
+
}
|
|
321
|
+
if (!signed) return refuse("grant_signature", "the signature does not verify")
|
|
322
|
+
|
|
323
|
+
// 5. Claim types.
|
|
324
|
+
const claims = parsePart(payloadPart)
|
|
325
|
+
if (!isPlainObject(claims)) return refuse("grant_malformed", "the payload is not a JSON object")
|
|
326
|
+
const claimProblem = claimTypeProblem(claims)
|
|
327
|
+
if (claimProblem) return refuse("grant_malformed", claimProblem)
|
|
328
|
+
|
|
329
|
+
// 6. Issuer and audience.
|
|
330
|
+
if (claims.iss !== entry.iss) return refuse("grant_issuer", "iss is not the key entry's host")
|
|
331
|
+
if (claims.aud !== entry.aud && claims.aud !== audience) return refuse("grant_audience", "aud is not this package's engine")
|
|
332
|
+
|
|
333
|
+
// 7. Time: at most 60 s, and within 5 s of this clock either way.
|
|
334
|
+
if (!(claims.exp - claims.iat > 0) || claims.exp - claims.iat > MAX_LIFETIME_SECONDS) return refuse("grant_time", `the lifetime is not 1 to ${MAX_LIFETIME_SECONDS} seconds`)
|
|
335
|
+
if (claims.iat > now + CLOCK_SKEW_SECONDS) return refuse("grant_time", "iat is in the future")
|
|
336
|
+
if (now > claims.exp + CLOCK_SKEW_SECONDS) return refuse("grant_expired", "the grant has expired")
|
|
337
|
+
|
|
338
|
+
// 8. Action: allowed here, and the one being called.
|
|
339
|
+
if (typeof act !== "string" || !Object.hasOwn(allowed, act)) return refuse("grant_action", "this act is not enabled")
|
|
340
|
+
if (claims.act !== act) return refuse("grant_action", "the grant is for another act")
|
|
341
|
+
|
|
342
|
+
// 9. Class: chat or local, meeting the act's minimum. view never authorises
|
|
343
|
+
// an act, and an act whose own declaration names another class is refused
|
|
344
|
+
// rather than read as the weakest one: a typo must fail closed.
|
|
345
|
+
const declaredClass = allowed[act]?.minClass
|
|
346
|
+
if (typeof declaredClass !== "string" || !Object.hasOwn(GRANT_CLASSES, declaredClass)) {
|
|
347
|
+
return refuse("grant_action", "the act's declared class is not one a grant can meet")
|
|
348
|
+
}
|
|
349
|
+
const minimum = GRANT_CLASSES[declaredClass]
|
|
350
|
+
const given = Object.hasOwn(GRANT_CLASSES, claims.cls) ? GRANT_CLASSES[claims.cls] : undefined
|
|
351
|
+
if (!given || given < minimum) return refuse("grant_class", "the grant's route class is weaker than the act needs")
|
|
352
|
+
|
|
353
|
+
// 10. Input: its canonical form, the act's closed schema, the host's extra
|
|
354
|
+
// keys, and the digest.
|
|
355
|
+
let canonical
|
|
356
|
+
try {
|
|
357
|
+
canonical = canonicalJson(input)
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (!(error instanceof InputNotCanonical)) throw error
|
|
360
|
+
return refuse(/nested deeper/.test(error.message) ? "grant_malformed" : "grant_input", error.message)
|
|
361
|
+
}
|
|
362
|
+
if (Buffer.byteLength(canonical, "utf8") > MAX_INPUT_BYTES) return refuse("grant_malformed", `the input is over ${MAX_INPUT_BYTES} bytes`)
|
|
363
|
+
const schema = inputKeysProblem(input, allowed[act]?.inputKeys, entry.extraInput)
|
|
364
|
+
if (schema) return refuse(schema.code, schema.detail)
|
|
365
|
+
if (claims.in !== createHash("sha256").update(canonical, "utf8").digest("base64url")) return refuse("grant_input", "the digest is not this input's")
|
|
366
|
+
|
|
367
|
+
return { ok: true, claims, entry }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function refuse(code, detail) {
|
|
371
|
+
return { ok: false, code, detail }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Strict base64url: no padding, and re-encoding gives the same string. */
|
|
375
|
+
function isStrictBase64url(value) {
|
|
376
|
+
if (typeof value !== "string" || value.length === 0 || !BASE64URL.test(value)) return false
|
|
377
|
+
return Buffer.from(value, "base64url").toString("base64url") === value
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function parsePart(value) {
|
|
381
|
+
try {
|
|
382
|
+
return JSON.parse(Buffer.from(value, "base64url").toString("utf8"))
|
|
383
|
+
} catch {
|
|
384
|
+
return undefined
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Every claim §4.1 requires, with its type; null when they are all there. */
|
|
389
|
+
function claimTypeProblem(claims) {
|
|
390
|
+
for (const [name, min, max] of [["iss", 1, 128], ["dev", 1, 128], ["mbr", 1, 128]]) {
|
|
391
|
+
if (typeof claims[name] !== "string" || claims[name].length < min || claims[name].length > max) return `${name} is not a string of ${min} to ${max} characters`
|
|
392
|
+
}
|
|
393
|
+
if (typeof claims.aud !== "string" || !claims.aud) return "aud is not a string"
|
|
394
|
+
if (typeof claims.act !== "string" || !claims.act) return "act is not a string"
|
|
395
|
+
if (typeof claims.in !== "string" || !BASE64URL_43.test(claims.in)) return "in is not 43 base64url characters"
|
|
396
|
+
if (claims.cls !== "chat" && claims.cls !== "local" && claims.cls !== "view") return "cls is not chat, local or view"
|
|
397
|
+
if (typeof claims.jti !== "string" || !JTI.test(claims.jti)) return "jti is not 22 to 128 base64url characters"
|
|
398
|
+
for (const name of ["iat", "exp"]) if (!Number.isSafeInteger(claims[name])) return `${name} is not a whole number of seconds`
|
|
399
|
+
return null
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* The input must hold only the act's declared keys and the keys the host added
|
|
404
|
+
* before signing (the entry's `extra_input`), and every declared key it holds
|
|
405
|
+
* must have the type the act declared for it. Which declared keys must be
|
|
406
|
+
* present is the act's own business (`run`), because some are conditional.
|
|
407
|
+
*
|
|
408
|
+
* @param {unknown} input
|
|
409
|
+
* @param {Record<string, string>} declared each input key and its JSON type
|
|
410
|
+
* @param {string[]} extraInput the keys the host adds before signing
|
|
411
|
+
* @returns {{ code: string, detail: string } | null}
|
|
412
|
+
*/
|
|
413
|
+
function inputKeysProblem(input, declared, extraInput) {
|
|
414
|
+
const schema = isPlainObject(declared) ? declared : {}
|
|
415
|
+
// A declared type this build does not know means the act cannot be applied as
|
|
416
|
+
// declared: refuse the act, never guess a permissive type.
|
|
417
|
+
for (const [name, type] of Object.entries(schema)) {
|
|
418
|
+
if (typeof type !== "string" || !INPUT_TYPES.includes(type)) return { code: "grant_action", detail: `the act declares ${name} with a type this build does not know` }
|
|
419
|
+
}
|
|
420
|
+
// A missing input is null (§4.2 rule 4): an act with no input has no keys.
|
|
421
|
+
if (input === null || input === undefined) return null
|
|
422
|
+
if (!isPlainObject(input)) return { code: "grant_input", detail: "the input is not an object" }
|
|
423
|
+
const permitted = new Set([...Object.keys(schema), ...extraInput])
|
|
424
|
+
for (const [key, value] of Object.entries(input)) {
|
|
425
|
+
if (!permitted.has(key)) return { code: "grant_input", detail: `the input holds ${key}, which the act does not declare` }
|
|
426
|
+
if (!Object.hasOwn(schema, key)) continue
|
|
427
|
+
if (!matchesType(value, schema[key])) return { code: "grant_input", detail: `${key} is not a ${schema[key]}` }
|
|
428
|
+
}
|
|
429
|
+
return null
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** One input value against its declared JSON type. */
|
|
433
|
+
function matchesType(value, type) {
|
|
434
|
+
if (type === "null") return value === null
|
|
435
|
+
if (type === "array") return Array.isArray(value)
|
|
436
|
+
if (type === "object") return isPlainObject(value)
|
|
437
|
+
if (type === "integer") return Number.isSafeInteger(value)
|
|
438
|
+
return typeof value === type
|
|
439
|
+
}
|