@sudoke/kernel 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/package.json +29 -4
- package/src/auth.ts +125 -0
- package/src/gate.ts +710 -0
- package/src/index.ts +26 -0
- package/src/mcp.ts +154 -0
- package/src/policy.ts +60 -0
- package/src/projections.ts +115 -0
- package/src/protocol.ts +51 -0
- package/src/queries.ts +176 -0
- package/src/registry.ts +235 -0
- package/src/state.ts +135 -0
- package/src/storage.ts +208 -0
- package/src/types.ts +121 -0
- package/src/visibility.ts +97 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sudoke/kernel",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "SUDOKE kernel — the 9-stage command gate, ledger, registries and async storage port behind every sudoke app",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"src"
|
|
8
|
+
],
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./src/index.ts",
|
|
15
|
+
"default": "./src/index.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"test": "node --import tsx --test test/*.test.ts"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
24
|
+
"jose": "^5.9.6",
|
|
25
|
+
"zod": "^3.23.8"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^22.10.2",
|
|
29
|
+
"typescript": "^5.7.2"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { SignJWT, jwtVerify } from 'jose'
|
|
2
|
+
import { scryptSync, randomBytes, timingSafeEqual, randomUUID, createHmac } from 'node:crypto'
|
|
3
|
+
import { storageOf, USER_STATUS_ACTIVE } from './storage.js'
|
|
4
|
+
import { resolveScopes } from './policy.js'
|
|
5
|
+
import type { Identity, Role } from './types.js'
|
|
6
|
+
|
|
7
|
+
export function hashPassword(password: string): string {
|
|
8
|
+
const salt = randomBytes(16).toString('hex')
|
|
9
|
+
return `${salt}:${scryptSync(password, salt, 32).toString('hex')}`
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function verifyPassword(password: string, stored: string): boolean {
|
|
13
|
+
const [salt, hash] = stored.split(':')
|
|
14
|
+
const calc = scryptSync(password, salt, 32)
|
|
15
|
+
const known = Buffer.from(hash, 'hex')
|
|
16
|
+
return calc.length === known.length && timingSafeEqual(calc, known)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function issueUserToken(userId: string): Promise<string> {
|
|
20
|
+
return new SignJWT({ sub: userId })
|
|
21
|
+
.setProtectedHeader({ alg: 'HS256' })
|
|
22
|
+
.setIssuedAt()
|
|
23
|
+
.setExpirationTime('12h')
|
|
24
|
+
.sign(storageOf().jwtSecret())
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Synchronous HS256 signing — used to issue delegation tokens inside command execution (pure crypto, no await needed). Cross-compatible with jose verification */
|
|
28
|
+
const b64url = (b: Buffer | string) => Buffer.from(b).toString('base64url')
|
|
29
|
+
function syncSignJWT(payload: Record<string, unknown>, expiresAt: Date, secret: Uint8Array): string {
|
|
30
|
+
const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))
|
|
31
|
+
const body = b64url(JSON.stringify({ ...payload, iat: Math.floor(Date.now() / 1000), exp: Math.floor(expiresAt.getTime() / 1000) }))
|
|
32
|
+
const sig = createHmac('sha256', Buffer.from(secret)).update(`${header}.${body}`).digest('base64url')
|
|
33
|
+
return `${header}.${body}.${sig}`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Delegation token — carries sub (delegator), act (acting subject name), del (delegation id) and scopes. identityFromToken verifies it */
|
|
37
|
+
export function issueDelegationToken(
|
|
38
|
+
d: { id: string; subjectId: string; name: string; scopes: string[] },
|
|
39
|
+
expiresAt: Date,
|
|
40
|
+
): string {
|
|
41
|
+
return syncSignJWT({ sub: d.subjectId, act: d.name, del: d.id, scopes: d.scopes }, expiresAt, storageOf().jwtSecret())
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function login(email: string, password: string) {
|
|
45
|
+
const user = await storageOf().userByEmail(email)
|
|
46
|
+
// fail-closed: only the explicitly active status may log in — unknown values never pass
|
|
47
|
+
if (!user || user.status !== USER_STATUS_ACTIVE || !verifyPassword(password, user.password)) return null
|
|
48
|
+
const token = await issueUserToken(user.id)
|
|
49
|
+
return { token, user: { id: user.id, email: user.email, name: user.name, role: user.role } }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Common unauthenticated refusal — the canonical stage-1 (identify) response. MCP identify rejections and REST 401s share this shape
|
|
53
|
+
* (a missing or invalid token signals reauthentication via code·recovery on every surface). */
|
|
54
|
+
export const unauthenticated = (reason: string) => ({
|
|
55
|
+
ok: false as const,
|
|
56
|
+
stage: 1,
|
|
57
|
+
stageName: 'identify',
|
|
58
|
+
reason,
|
|
59
|
+
code: 'auth.token_invalid',
|
|
60
|
+
recovery: { action: 'reauthenticate' as const },
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
/** Token → identity. Role/scope are re-read on every request (assignment changes apply immediately).
|
|
64
|
+
* Role→scope rules belong to the app policy — the auth infrastructure knows neither role vocabulary ('manager' etc.) nor assignment tables */
|
|
65
|
+
export async function loadIdentity(userId: string): Promise<Identity | null> {
|
|
66
|
+
const user = await storageOf().userById(userId)
|
|
67
|
+
// fail-closed: only the explicitly active status is an identity — unknown values never pass
|
|
68
|
+
if (!user || user.status !== USER_STATUS_ACTIVE) return null
|
|
69
|
+
return { userId: user.id, name: user.name, role: user.role as Role, scopes: await resolveScopes(user.role, user.id) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Execution-time identity recheck — re-reads current state from users·delegations (kernel-owned tables).
|
|
74
|
+
* Returns an identity reflecting role changes, deactivations, delegation revocations and expiries
|
|
75
|
+
* that happened between token verification and actual execution; null when invalid (unknown user,
|
|
76
|
+
* inactive, revoked or expired delegation, or a delegation not owned by this account). scopes (read-side
|
|
77
|
+
* assignment scope) keep the request-time value — write-permission recheck is recalculated by the gate
|
|
78
|
+
* (reauthorize) via scopesFor, only for scoped commands.
|
|
79
|
+
*/
|
|
80
|
+
export async function currentIdentityOf(identity: Identity): Promise<Identity | null> {
|
|
81
|
+
const user = await storageOf().userById(identity.userId)
|
|
82
|
+
// fail-closed: only the explicitly active status survives the execution-time recheck — unknown values never pass
|
|
83
|
+
if (!user || user.status !== USER_STATUS_ACTIVE) return null
|
|
84
|
+
const base: Identity = { userId: user.id, name: user.name, role: user.role as Role, scopes: identity.scopes }
|
|
85
|
+
if (!identity.delegation) return base
|
|
86
|
+
const d = await storageOf().delegationById(identity.delegation.id)
|
|
87
|
+
// Owner match — the delegation must belong to this account; an issuance-path mistake or a wrongly-minted
|
|
88
|
+
// token (someone else's sub attached to this delegation) is treated as invalid, same as revocation/expiry
|
|
89
|
+
if (!d || d.subject_id !== identity.userId || d.revoked_at || new Date(d.expires_at).getTime() <= Date.now()) return null
|
|
90
|
+
return { ...base, act: d.name, delegation: { id: d.id, name: d.name, scopes: JSON.parse(d.scopes) as string[] } }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function identityFromToken(authHeader: string | undefined): Promise<Identity | null> {
|
|
94
|
+
if (!authHeader?.startsWith('Bearer ')) return null
|
|
95
|
+
try {
|
|
96
|
+
const { payload } = await jwtVerify(authHeader.slice(7), storageOf().jwtSecret())
|
|
97
|
+
// Delegation token (agent) — revocation/expiry is checked on every request, and permissions are worn as the delegator's
|
|
98
|
+
// (the intersection is applied at gate stage 2)
|
|
99
|
+
if (payload.del) {
|
|
100
|
+
const d = await storageOf().delegationById(String(payload.del))
|
|
101
|
+
// Owner match — the delegation id alone is not
|
|
102
|
+
// proof of ownership, so a wrongly-minted token wearing someone else's delegation is refused here
|
|
103
|
+
if (!d || d.subject_id !== String(payload.sub) || d.revoked_at || new Date(d.expires_at).getTime() <= Date.now()) return null
|
|
104
|
+
const base = await loadIdentity(String(payload.sub))
|
|
105
|
+
if (!base) return null
|
|
106
|
+
const scopes: string[] = JSON.parse(d.scopes)
|
|
107
|
+
// Scope syntax is carried as-is — business interpretation of codes (including read scope) is left by the gate and queries to the app policy
|
|
108
|
+
return { ...base, act: d.name, delegation: { id: d.id, name: d.name, scopes } }
|
|
109
|
+
}
|
|
110
|
+
return await loadIdentity(String(payload.sub))
|
|
111
|
+
} catch {
|
|
112
|
+
return null
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** First-user bootstrap — the ONLY kernel write that does not pass the gate: no identity exists yet to
|
|
117
|
+
* pass it with (the gate needs a logged-in subject). Everything after the first users is written through
|
|
118
|
+
* commands. Idempotent by email: an existing account is returned untouched. */
|
|
119
|
+
export async function ensureUser(email: string, name: string, role: Role, password: string): Promise<string> {
|
|
120
|
+
const existing = await storageOf().userByEmail(email)
|
|
121
|
+
if (existing) return existing.id
|
|
122
|
+
const id = randomUUID()
|
|
123
|
+
await storageOf().insertUser({ id, email, name, role, password: hashPassword(password), status: USER_STATUS_ACTIVE })
|
|
124
|
+
return id
|
|
125
|
+
}
|