@north-light/identity 0.0.0-stage → 0.3.410

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Copyright (c) 2026 Northlight Systems. All rights reserved.
2
+
3
+ This software and its associated documentation files (the "Software") are the
4
+ proprietary and confidential property of Northlight Systems. No licence or
5
+ right to use, copy, modify, merge, publish, distribute, sublicense, sell,
6
+ reverse engineer, decompile or create derivative works of the Software is
7
+ granted except under a separate written agreement with Northlight Systems.
8
+
9
+ The Software is made available as compiled and minified packages through the
10
+ npm registry solely so that it can be installed and run by those authorised by
11
+ Northlight Systems. Installing a package from the registry does not grant any
12
+ licence to the Software's source code.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17
+ NORTHLIGHT SYSTEMS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING
18
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR ITS USE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @north-light/identity — verify directory-issued tokens and evaluate crouter scopes
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
+ ![crouter](https://raw.githubusercontent.com/Northlight-Systems/crouter/main/assets/banner.svg)
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/@north-light/identity"><img alt="npm" src="https://img.shields.io/npm/v/@north-light/identity?label=npm"></a>
7
+ </p>
8
+
9
+ `@north-light/identity` is the token contract shared by crouter's runtime, [`@north-light/sdk`](https://www.npmjs.com/package/@north-light/sdk) and [`@north-light/plugin`](https://www.npmjs.com/package/@north-light/plugin). It does two things: it verifies the signed JWTs that a crouter cloud directory issues (access tokens, ID tokens, outbound provider tokens and grant-sync notices) against the directory's published keys, and it parses and compares scope strings such as `crtr:llm` or `crtr:memory:read:user:work/`. It is ESM-only, depends only on [`jose`](https://github.com/panva/jose), and has no side effects on import.
10
+
11
+ It is a verifier, not an identity provider. It never issues, signs or stores tokens, and it does not run a login flow; the directory does that. Most applications do not import it directly: the SDK's OAuth helpers and the plugin kit's `auth` option call it for you. Use it when you write your own provider or service that receives these tokens.
12
+
13
+ [Docs](https://docs.crouter.ai/docs/concepts/scopes-and-trust) · [Plugin authentication](https://docs.crouter.ai/docs/plugin/deploying) · [Apps with many users](https://docs.crouter.ai/docs/sdk/guides/apps-with-many-users) · [crouter repository](https://github.com/Northlight-Systems/crouter)
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @north-light/identity
19
+ ```
20
+
21
+ ## Verify a token
22
+
23
+ Every verifier takes `{ token, jwks, issuer, audience }` and returns the typed claims or throws. `jwks` is either a static JWKS object or a `JwksCache`.
24
+
25
+ ```ts
26
+ import { JwksCache, verifyOutboundToken } from '@north-light/identity';
27
+
28
+ const issuer = 'https://directory.example.com';
29
+ const jwks = new JwksCache(issuer, fetch, `${issuer}/.well-known/jwks.json`);
30
+
31
+ export async function authorize(request: Request) {
32
+ const token = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '';
33
+ const claims = await verifyOutboundToken({
34
+ token,
35
+ jwks,
36
+ issuer,
37
+ audience: 'https://provider.example.com/crtr', // exactly the URL the provider registered
38
+ });
39
+ return claims.scope.split(' '); // the provider's `<provider>:<group>` strings the caller holds
40
+ }
41
+ ```
42
+
43
+ `JwksCache` keeps the last good key set for one issuer. When a token names a `kid` it has not seen, it refetches, at most once every 30 seconds, and concurrent requests share that fetch. A failed refresh leaves the previous keys in place. If you omit the third argument, it discovers `jwks_uri` from `<issuer>/.well-known/openid-configuration`.
44
+
45
+ | Function | Checks | Returns |
46
+ |---|---|---|
47
+ | `verifyAccessToken` | `typ: at+jwt`, ES256, signature, `iss`, `aud`, `exp`; `sub` is `user:<id>`, `grantee` is `app:<id>`; `rev` is a positive integer (a token without `rev` throws `MissingRevClaimError`) | `AccessTokenClaims` (`sub`, `grantee`, `client_id`, `grant`, `rev`, `exp`) |
48
+ | `verifyOutboundToken` | `typ: at+jwt`, ES256 or RS256 with a `kid`, signature, `iss`, `aud`, `exp`; claim presence and types, including `scope`, `initiating_app`, `act`, `jti` | `OutboundTokenClaims` |
49
+ | `verifyIdToken` | ES256, signature, `iss`, `aud`, `exp`; `sub` is `user:<id>` | `IdTokenClaims` (`email*` when `email` was granted; `name`, `given_name`, `family_name` when `profile` was) |
50
+ | `verifySyncNotice` | ES256 with a `kid`, `purpose: grant_sync`, lifetime of at most five minutes, 30 s clock tolerance | `SyncNoticeClaims` (`jti`, `iat`, `exp`) |
51
+
52
+ `aud` must match exactly; a trailing-slash difference is refused. The `act` claim of an outbound token is for audit only: nothing in this package authorizes on it.
53
+
54
+ ## Parse and compare scopes
55
+
56
+ ```ts
57
+ import { parseScope, covers } from '@north-light/identity';
58
+
59
+ parseScope('crtr:files:rw:user:reports'); // returns the string, typed as Scope
60
+ parseScope('crtr:files:rw:user:../etc'); // throws TypeError: Unsupported scope
61
+
62
+ covers('crtr:memory:rw:user', 'crtr:memory:read:user:work'); // true: rw covers read, no path covers any path
63
+ covers('crtr:memory:read:user', 'crtr:memory:rw:user'); // false
64
+ covers('crtr:files:rw:user:.', 'crtr:files:read:user:a/b'); // true: `.` is the whole directory
65
+ ```
66
+
67
+ The grammar `parseScope` accepts:
68
+
69
+ | Scope | Meaning |
70
+ |---|---|
71
+ | `crtr:llm`, `crtr:act`, `crtr:schedule` | Model calls and starting runs; acting on nodes, files and bash; scheduling crons |
72
+ | `crtr:memory:read:user[:path]`, `crtr:memory:rw:user[:path]`, `crtr:memory:manage:user` | The person's documents, optionally limited to a path; `manage` covers both access levels |
73
+ | `crtr:memory:read\|rw:app:<id>[:profile:<profile>[:path]]` | An app's documents |
74
+ | `crtr:files:read\|rw:user:<dir>`, `crtr:files:read\|rw:app:<id>:<dir>`, `crtr:files:share` | Host files a run may mount, and sharing them |
75
+ | `crtr:conversations:read:app:<id>`, `crtr:objects:read:app:<id>` | Reading another app's conversations or node objects |
76
+ | `crtr:peer:<id>` | A peer grant |
77
+ | `<provider>:<group>` | A capability provider's own scope, such as the ones in an outbound token's `scope` |
78
+
79
+ Paths are relative and refuse `..`, `:`, backslashes, whitespace and empty segments. A memory path ending in `/` covers that directory and everything below it; a file path names a directory and covers it and everything below, with `.` meaning the whole root. Passing `grantee` as the second argument to `parseScope` also refuses an `app:` holder other than the grantee. `ENFORCED` is the set of scopes `crtr sys connect --scopes` accepts when it mints a token. What each scope allows is in [Scopes and trust](https://docs.crouter.ai/docs/concepts/scopes-and-trust).
80
+
81
+ ## Related
82
+
83
+ - [`@north-light/sdk`](https://www.npmjs.com/package/@north-light/sdk): uses this package for ID-token verification and scope validation in its OAuth helpers.
84
+ - [`@north-light/plugin`](https://www.npmjs.com/package/@north-light/plugin): verifies the directory's outbound tokens for providers registered in the directory.
85
+ - [Main repository](https://github.com/Northlight-Systems/crouter): the `crtr` CLI, the `crtrd` daemon,.
86
+
87
+ ## License
88
+
89
+ Proprietary. Copyright (c) 2026 Northlight Systems. All rights reserved. See `LICENSE`.
@@ -0,0 +1,107 @@
1
+ import { type JSONWebKeySet, type JWTPayload } from 'jose';
2
+ export interface AccessTokenClaims extends JWTPayload {
3
+ sub: string;
4
+ grantee: string;
5
+ client_id: string;
6
+ grant: string;
7
+ /** The grant revision the directory minted against: a freshness floor, never authorization (contract 1). */
8
+ rev: number;
9
+ exp: number;
10
+ }
11
+ /** Thrown by `verifyAccessToken` for a signed token with no `rev` claim: the directory predates the claim. */
12
+ export declare class MissingRevClaimError extends Error {
13
+ constructor();
14
+ }
15
+ /** `email*` appear when `email` was granted; `name`, `given_name`, `family_name` when `profile` was granted and the person has a name. A person with no name has none of the three: never the phone number. `picture` (an https URL of the person's Google photo) when `profile` was granted and the account has one. */
16
+ export interface IdTokenClaims extends JWTPayload {
17
+ sub: string;
18
+ email?: string;
19
+ email_verified?: boolean;
20
+ name?: string;
21
+ given_name?: string;
22
+ family_name?: string;
23
+ picture?: string;
24
+ }
25
+ export type Scope = 'crtr:llm' | 'crtr:act' | 'crtr:schedule' | `crtr:memory:${'read' | 'rw'}:user${'' | `:${string}`}` | 'crtr:memory:manage:user' | `crtr:memory:${'read' | 'rw'}:app:${string}` | `crtr:files:${'read' | 'rw'}:${'user' | `app:${string}`}:${string}` | 'crtr:files:share' | `crtr:${'conversations' | 'objects'}:read:app:${string}` | `crtr:peer:${string}` | `${string}:${string}`;
26
+ /** App-memory form keys omit the app id. */
27
+ export declare const ENFORCED: ReadonlySet<string>;
28
+ export declare function parseScope(value: string, grantee?: string): Scope;
29
+ export declare function covers(held: string, requested: string): boolean;
30
+ /** Keys are scoped to one configured issuer; failed refreshes keep the last successful set. */
31
+ export declare class JwksCache {
32
+ readonly issuer: string;
33
+ private readonly fetcher;
34
+ private keys;
35
+ private lastUnknownRefresh;
36
+ private loading;
37
+ private discovery;
38
+ constructor(issuer: string, fetcher?: typeof fetch, jwksUri?: string);
39
+ load(): Promise<JSONWebKeySet>;
40
+ private fetchKeys;
41
+ forKid(kid: string | undefined): Promise<JSONWebKeySet>;
42
+ }
43
+ export declare function verifyAccessToken(options: {
44
+ token: string;
45
+ jwks: JSONWebKeySet | JwksCache;
46
+ issuer: string;
47
+ audience: string;
48
+ }): Promise<AccessTokenClaims>;
49
+ /** One level of the outbound token's RFC 8693 `act` nesting: the actor, and the actor it acted for. */
50
+ export interface OutboundActor {
51
+ sub: string;
52
+ act?: OutboundActor;
53
+ }
54
+ /** The claims of the outbound token the directory mints for one provider call (contract 3). */
55
+ export interface OutboundTokenClaims extends JWTPayload {
56
+ iss: string;
57
+ aud: string;
58
+ /** The user the call is made for, `user:<id>`. */
59
+ sub: string;
60
+ /** The principal the grant was issued to, `app:<id>` or the user. */
61
+ grantee: string;
62
+ /** The runtime's registered OAuth client id. */
63
+ client_id: string;
64
+ /** The provider's `<provider>:<group>` strings the caller holds, space-separated; may be empty. */
65
+ scope: string;
66
+ initiating_app: string;
67
+ /** Audit only; nothing authorizes on it. */
68
+ act: OutboundActor;
69
+ iat: number;
70
+ exp: number;
71
+ jti: string;
72
+ }
73
+ /**
74
+ * Verifies the outbound token a provider receives (contract 3 D3-TOK-12): ES256 or RS256 with
75
+ * a `kid`, typ `at+jwt`, signature against `jwks` (a `JwksCache` refetches once on an unknown
76
+ * `kid`), `iss` = `issuer`, `aud` exactly `audience` (a trailing-slash difference is refused),
77
+ * and `exp`. `sub` must be a `user:` principal and `grantee` and `initiating_app`
78
+ * an `app:` or `user:` principal; the remaining claims are checked for presence and type only; which of them gates a
79
+ * call is the caller's rule (D3-TOK-13 gates on `scope` alone, and nothing gates on `act`).
80
+ */
81
+ export declare function verifyOutboundToken(options: {
82
+ token: string;
83
+ jwks: JSONWebKeySet | JwksCache;
84
+ issuer: string;
85
+ audience: string;
86
+ }): Promise<OutboundTokenClaims>;
87
+ export interface SyncNoticeClaims extends JWTPayload {
88
+ purpose: 'grant_sync';
89
+ iat: number;
90
+ exp: number;
91
+ jti: string;
92
+ }
93
+ /** The directory's grant-sync notice: ES256 with the directory signing key named
94
+ * by `kid`, no `typ`, `aud` = the runtime's registered URL, a lifetime of at most
95
+ * five minutes, and a `jti` the runtime uses to answer replays without a sync. */
96
+ export declare function verifySyncNotice(options: {
97
+ token: string;
98
+ jwks: JSONWebKeySet | JwksCache;
99
+ issuer: string;
100
+ audience: string;
101
+ }): Promise<SyncNoticeClaims>;
102
+ export declare function verifyIdToken(options: {
103
+ token: string;
104
+ jwks: JSONWebKeySet | JwksCache;
105
+ issuer: string;
106
+ audience: string;
107
+ }): Promise<IdTokenClaims>;
package/dist/index.js ADDED
@@ -0,0 +1,226 @@
1
+ import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from 'jose';
2
+ /** Thrown by `verifyAccessToken` for a signed token with no `rev` claim: the directory predates the claim. */
3
+ export class MissingRevClaimError extends Error {
4
+ constructor() { super('access token has no rev claim: the directory is older than this runtime'); this.name = 'MissingRevClaimError'; }
5
+ }
6
+ /** App-memory form keys omit the app id. */
7
+ export const ENFORCED = new Set(['crtr:llm', 'crtr:act', 'crtr:schedule', 'crtr:memory:read:user', 'crtr:memory:read:app', 'crtr:memory:rw:app', 'crtr:files:read:user:.', 'crtr:files:rw:user:.']);
8
+ const id = /^[A-Za-z0-9_-]{1,64}$/;
9
+ function validPath(path, directoryOnly = false) {
10
+ if (path === '.' && directoryOnly)
11
+ return true;
12
+ return path.length > 0 && !path.startsWith('/') && !path.includes('..') && !path.includes(':') &&
13
+ !path.includes('\\') && !/\s/.test(path) &&
14
+ !path.split('/').some((part, index, parts) => part === '.' || (part === '' && index !== parts.length - 1)) &&
15
+ (!directoryOnly || !path.endsWith('/'));
16
+ }
17
+ function selector(value) {
18
+ if (value === 'crtr:llm' || value === 'crtr:act' || value === 'crtr:schedule')
19
+ return { kind: value.slice(5), value };
20
+ if (value === 'crtr:files:share')
21
+ return { kind: 'share', value };
22
+ if (value === 'crtr:memory:manage:user')
23
+ return { kind: 'memory', access: 'manage', holder: 'user' };
24
+ let match = /^crtr:memory:(read|rw):user(?::(.+))?$/.exec(value);
25
+ if (match && (match[2] === undefined || validPath(match[2])))
26
+ return { kind: 'memory', access: match[1], holder: 'user', path: match[2] };
27
+ match = /^crtr:memory:(read|rw):app:([A-Za-z0-9_-]{1,64})(?::profile:([A-Za-z0-9_-]{1,64})(?::(.+))?)?$/.exec(value);
28
+ if (match && (match[4] === undefined || validPath(match[4]))) {
29
+ return { kind: 'memory', access: match[1], holder: `app:${match[2]}`, profile: match[3], path: match[4] };
30
+ }
31
+ match = /^crtr:files:(read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(value);
32
+ if (match && validPath(match[3], true))
33
+ return { kind: 'files', access: match[1], holder: match[2], path: match[3] };
34
+ match = /^crtr:(conversations|objects):read:app:([A-Za-z0-9_-]{1,64})$/.exec(value);
35
+ if (match)
36
+ return { kind: match[1], value };
37
+ match = /^crtr:peer:([A-Za-z0-9_-]{1,64})$/.exec(value);
38
+ if (match)
39
+ return { kind: 'peer', value };
40
+ match = /^([^:]+):([^:]+)$/.exec(value);
41
+ if (match && match[1] !== 'crtr' && id.test(match[1]) && id.test(match[2]))
42
+ return { kind: 'provider', value };
43
+ throw new TypeError(`Unsupported scope: ${value}`);
44
+ }
45
+ export function parseScope(value, grantee) {
46
+ const parsed = selector(value);
47
+ if (grantee && (parsed.kind === 'memory' || parsed.kind === 'files') && parsed.holder.startsWith('app:') && parsed.holder !== grantee) {
48
+ throw new TypeError(`Unsupported scope: ${value}`);
49
+ }
50
+ return value;
51
+ }
52
+ function containsPath(held, requested) {
53
+ if (held === undefined)
54
+ return true;
55
+ if (requested === undefined)
56
+ return false;
57
+ return held === requested || (held.endsWith('/') && requested.startsWith(held));
58
+ }
59
+ export function covers(held, requested) {
60
+ const h = selector(held);
61
+ const r = selector(requested);
62
+ if (h.kind !== r.kind)
63
+ return false;
64
+ if (h.kind === 'memory' && r.kind === 'memory') {
65
+ return h.holder === r.holder && (h.access === r.access || h.access === 'manage' || (h.access === 'rw' && r.access === 'read')) &&
66
+ (h.profile === undefined || h.profile === r.profile) && containsPath(h.path, r.path);
67
+ }
68
+ if (h.kind === 'files' && r.kind === 'files') {
69
+ return h.holder === r.holder && (h.access === 'rw' || r.access === 'read') &&
70
+ (h.path === '.' || h.path === r.path || r.path.startsWith(`${h.path}/`));
71
+ }
72
+ return held === requested;
73
+ }
74
+ /** Keys are scoped to one configured issuer; failed refreshes keep the last successful set. */
75
+ export class JwksCache {
76
+ issuer;
77
+ fetcher;
78
+ keys;
79
+ lastUnknownRefresh = -Infinity;
80
+ loading;
81
+ discovery;
82
+ constructor(issuer, fetcher = fetch, jwksUri) {
83
+ this.issuer = issuer;
84
+ this.fetcher = fetcher;
85
+ if (jwksUri)
86
+ this.discovery = { jwks_uri: jwksUri };
87
+ }
88
+ async load() {
89
+ if (this.loading)
90
+ return this.loading;
91
+ const loading = this.fetchKeys();
92
+ this.loading = loading;
93
+ try {
94
+ return await loading;
95
+ }
96
+ finally {
97
+ this.loading = undefined;
98
+ }
99
+ }
100
+ async fetchKeys() {
101
+ if (!this.discovery) {
102
+ const response = await this.fetcher(`${this.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`);
103
+ if (!response.ok)
104
+ throw new Error(`Directory discovery failed: ${response.status}`);
105
+ const value = await response.json();
106
+ if (!value || typeof value !== 'object' || !('jwks_uri' in value) || typeof value.jwks_uri !== 'string')
107
+ throw new Error('Directory discovery has no jwks_uri');
108
+ this.discovery = { jwks_uri: value.jwks_uri };
109
+ }
110
+ const response = await this.fetcher(this.discovery.jwks_uri);
111
+ if (!response.ok)
112
+ throw new Error(`Directory JWKS failed: ${response.status}`);
113
+ const keys = await response.json();
114
+ if (!keys || typeof keys !== 'object' || !('keys' in keys) || !Array.isArray(keys.keys))
115
+ throw new Error('Invalid directory JWKS');
116
+ this.keys = keys;
117
+ return this.keys;
118
+ }
119
+ async forKid(kid) {
120
+ if (!this.keys)
121
+ return this.load();
122
+ if (this.keys.keys.some((key) => key.kid === kid))
123
+ return this.keys;
124
+ // Concurrent requests for a newly published kid must await the same refetch, not use
125
+ // the stale set while the 30-second unknown-kid throttle is running.
126
+ if (this.loading)
127
+ return this.loading;
128
+ if (Date.now() - this.lastUnknownRefresh >= 30_000) {
129
+ this.lastUnknownRefresh = Date.now();
130
+ await this.load();
131
+ }
132
+ return this.keys;
133
+ }
134
+ }
135
+ function validatePrincipal(value, kind) {
136
+ return typeof value === 'string' && value.startsWith(`${kind}:`) && id.test(value.slice(kind.length + 1));
137
+ }
138
+ function keySet(jwks, kid) {
139
+ return jwks instanceof JwksCache ? jwks.forKid(kid) : Promise.resolve(jwks);
140
+ }
141
+ export async function verifyAccessToken(options) {
142
+ const header = decodeProtectedHeader(options.token);
143
+ if (header.typ !== 'at+jwt' || header.alg !== 'ES256')
144
+ throw new Error('Invalid access token header');
145
+ const keys = await keySet(options.jwks, header.kid);
146
+ const { payload } = await jwtVerify(options.token, createLocalJWKSet(keys), {
147
+ issuer: options.issuer, audience: options.audience, algorithms: ['ES256'], typ: 'at+jwt',
148
+ });
149
+ if (payload.aud !== options.audience || !validatePrincipal(payload.sub, 'user') || !validatePrincipal(payload.grantee, 'app') ||
150
+ typeof payload.client_id !== 'string' || !id.test(payload.client_id) || typeof payload.grant !== 'string' ||
151
+ typeof payload.exp !== 'number') {
152
+ throw new Error('Invalid access token claims');
153
+ }
154
+ if (payload.rev === undefined)
155
+ throw new MissingRevClaimError();
156
+ if (typeof payload.rev !== 'number' || !Number.isInteger(payload.rev) || payload.rev < 1)
157
+ throw new Error('Invalid access token claims');
158
+ return payload;
159
+ }
160
+ function nonEmptyString(value) {
161
+ return typeof value === 'string' && value !== '';
162
+ }
163
+ function appOrUser(value) {
164
+ return validatePrincipal(value, 'app') || validatePrincipal(value, 'user');
165
+ }
166
+ function isActor(value) {
167
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && nonEmptyString(value.sub);
168
+ }
169
+ /**
170
+ * Verifies the outbound token a provider receives (contract 3 D3-TOK-12): ES256 or RS256 with
171
+ * a `kid`, typ `at+jwt`, signature against `jwks` (a `JwksCache` refetches once on an unknown
172
+ * `kid`), `iss` = `issuer`, `aud` exactly `audience` (a trailing-slash difference is refused),
173
+ * and `exp`. `sub` must be a `user:` principal and `grantee` and `initiating_app`
174
+ * an `app:` or `user:` principal; the remaining claims are checked for presence and type only; which of them gates a
175
+ * call is the caller's rule (D3-TOK-13 gates on `scope` alone, and nothing gates on `act`).
176
+ */
177
+ export async function verifyOutboundToken(options) {
178
+ const header = decodeProtectedHeader(options.token);
179
+ if (header.typ !== 'at+jwt' || (header.alg !== 'ES256' && header.alg !== 'RS256'))
180
+ throw new Error('Invalid outbound token header');
181
+ if (!nonEmptyString(header.kid))
182
+ throw new Error('Outbound token has no key id');
183
+ const keys = await keySet(options.jwks, header.kid);
184
+ const { payload } = await jwtVerify(options.token, createLocalJWKSet(keys), {
185
+ issuer: options.issuer, audience: options.audience, algorithms: ['ES256', 'RS256'], typ: 'at+jwt', requiredClaims: ['exp'],
186
+ });
187
+ if (payload.aud !== options.audience || typeof payload.exp !== 'number' || typeof payload.iat !== 'number' ||
188
+ !validatePrincipal(payload.sub, 'user') || !appOrUser(payload.grantee) || !nonEmptyString(payload.client_id) ||
189
+ typeof payload.scope !== 'string' || !appOrUser(payload.initiating_app) || !isActor(payload.act) ||
190
+ !nonEmptyString(payload.jti)) {
191
+ throw new Error('Invalid outbound token claims');
192
+ }
193
+ return payload;
194
+ }
195
+ /** The directory's grant-sync notice: ES256 with the directory signing key named
196
+ * by `kid`, no `typ`, `aud` = the runtime's registered URL, a lifetime of at most
197
+ * five minutes, and a `jti` the runtime uses to answer replays without a sync. */
198
+ export async function verifySyncNotice(options) {
199
+ const header = decodeProtectedHeader(options.token);
200
+ if (header.alg !== 'ES256')
201
+ throw new Error('Invalid sync notice algorithm');
202
+ if (typeof header.kid !== 'string' || header.kid === '')
203
+ throw new Error('Sync notice has no key id');
204
+ const keys = await keySet(options.jwks, header.kid);
205
+ const { payload } = await jwtVerify(options.token, createLocalJWKSet(keys), {
206
+ issuer: options.issuer, audience: options.audience, algorithms: ['ES256'], requiredClaims: ['exp', 'iat', 'jti'],
207
+ maxTokenAge: 300, clockTolerance: 30,
208
+ });
209
+ if (payload.aud !== options.audience || payload.purpose !== 'grant_sync' || typeof payload.jti !== 'string' || payload.jti === '' ||
210
+ typeof payload.exp !== 'number' || typeof payload.iat !== 'number' || payload.exp - payload.iat > 300) {
211
+ throw new Error('Invalid sync notice claims');
212
+ }
213
+ return payload;
214
+ }
215
+ export async function verifyIdToken(options) {
216
+ const header = decodeProtectedHeader(options.token);
217
+ if (header.alg !== 'ES256')
218
+ throw new Error('Invalid ID token algorithm');
219
+ const keys = await keySet(options.jwks, header.kid);
220
+ const { payload } = await jwtVerify(options.token, createLocalJWKSet(keys), {
221
+ issuer: options.issuer, audience: options.audience, algorithms: ['ES256'],
222
+ });
223
+ if (payload.aud !== options.audience || typeof payload.exp !== 'number' || !validatePrincipal(payload.sub, 'user'))
224
+ throw new Error('Invalid ID token claims');
225
+ return payload;
226
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.410",
4
+ "description": "crouter cloud access-token verification and scope rules",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json"
20
+ },
21
+ "dependencies": {
22
+ "jose": "^6.2.1"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/Northlight-Systems/crouter.git",
30
+ "directory": "packages/crouter-identity"
31
+ },
32
+ "license": "UNLICENSED"
33
+ }