@artemis-apps/app-server 0.0.0-stage → 0.1.1
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/dist/account-deletion/account-deletion.service.d.ts +18 -0
- package/dist/account-deletion/account-deletion.service.js +18 -0
- package/dist/activity/core-activity.client.d.ts +20 -0
- package/dist/activity/core-activity.client.js +32 -0
- package/dist/core-api/core-api.client.d.ts +25 -0
- package/dist/core-api/core-api.client.js +63 -0
- package/dist/enrollment/enrollment.service.d.ts +30 -0
- package/dist/enrollment/enrollment.service.js +103 -0
- package/dist/entity-grants/entity-grant.service.d.ts +22 -0
- package/dist/entity-grants/entity-grant.service.js +49 -0
- package/dist/events/security-event.routes.d.ts +24 -0
- package/dist/events/security-event.routes.js +28 -0
- package/dist/handlers/handler.routes.d.ts +32 -0
- package/dist/handlers/handler.routes.js +74 -0
- package/dist/icon/app-icon.routes.d.ts +15 -0
- package/dist/icon/app-icon.routes.js +18 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +4 -0
- package/dist/keys/app-key.entity.d.ts +67 -0
- package/dist/keys/app-key.entity.js +10 -0
- package/dist/keys/app-key.repository.d.ts +14 -0
- package/dist/keys/app-key.repository.js +38 -0
- package/dist/manifest/manifest.routes.d.ts +115 -0
- package/dist/manifest/manifest.routes.js +9 -0
- package/dist/oidc/account-claims.d.ts +5 -0
- package/dist/oidc/account-claims.js +22 -0
- package/dist/oidc/oidc.client.d.ts +64 -0
- package/dist/oidc/oidc.client.js +205 -0
- package/dist/platform.config.d.ts +22 -0
- package/dist/platform.config.js +0 -0
- package/dist/platform.d.ts +387 -0
- package/dist/platform.js +125 -0
- package/dist/platform.tables.d.ts +448 -0
- package/dist/platform.tables.js +9 -0
- package/dist/providers/provider.routes.d.ts +78 -0
- package/dist/providers/provider.routes.js +208 -0
- package/dist/relay/core-relay.routes.d.ts +26 -0
- package/dist/relay/core-relay.routes.js +64 -0
- package/dist/session/app-session.entity.d.ts +301 -0
- package/dist/session/app-session.entity.js +26 -0
- package/dist/session/app-session.repository.d.ts +34 -0
- package/dist/session/app-session.repository.js +87 -0
- package/dist/session/app-sign-in-attempt.entity.d.ts +82 -0
- package/dist/session/app-sign-in-attempt.entity.js +8 -0
- package/dist/session/app-sign-in-attempt.repository.d.ts +15 -0
- package/dist/session/app-sign-in-attempt.repository.js +29 -0
- package/dist/session/app.cookies.d.ts +22 -0
- package/dist/session/app.cookies.js +18 -0
- package/dist/session/require-permissions.middleware.d.ts +36 -0
- package/dist/session/require-permissions.middleware.js +34 -0
- package/dist/session/session.routes.d.ts +204 -0
- package/dist/session/session.routes.js +92 -0
- package/dist/session/session.service.d.ts +50 -0
- package/dist/session/session.service.js +137 -0
- package/dist/storage/core-storage.client.d.ts +27 -0
- package/dist/storage/core-storage.client.js +71 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.js +3 -0
- package/dist/testing/platform-fixtures.d.ts +24 -0
- package/dist/testing/platform-fixtures.js +25 -0
- package/dist/testing/test-core.d.ts +73 -0
- package/dist/testing/test-core.js +134 -0
- package/package.json +45 -3
- package/README.md +0 -3
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { JWK } from 'jose';
|
|
2
|
+
/**
|
|
3
|
+
* The app's signing key (ES256), generated on its first start: its client authentication
|
|
4
|
+
* (`private_key_jwt`). Only its public part ever leaves the app, in the manifest. One row.
|
|
5
|
+
*/
|
|
6
|
+
export declare const appKeys: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
7
|
+
name: "app_keys";
|
|
8
|
+
schema: undefined;
|
|
9
|
+
columns: {
|
|
10
|
+
kid: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
11
|
+
name: "kid";
|
|
12
|
+
tableName: "app_keys";
|
|
13
|
+
dataType: "string";
|
|
14
|
+
columnType: "SQLiteText";
|
|
15
|
+
data: string;
|
|
16
|
+
driverParam: string;
|
|
17
|
+
notNull: true;
|
|
18
|
+
hasDefault: false;
|
|
19
|
+
isPrimaryKey: true;
|
|
20
|
+
isAutoincrement: false;
|
|
21
|
+
hasRuntimeDefault: false;
|
|
22
|
+
enumValues: [string, ...string[]];
|
|
23
|
+
baseColumn: never;
|
|
24
|
+
identity: undefined;
|
|
25
|
+
generated: undefined;
|
|
26
|
+
}, {}, {
|
|
27
|
+
length: undefined;
|
|
28
|
+
}>;
|
|
29
|
+
privateJwk: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
30
|
+
name: "privateJwk";
|
|
31
|
+
tableName: "app_keys";
|
|
32
|
+
dataType: "json";
|
|
33
|
+
columnType: "SQLiteTextJson";
|
|
34
|
+
data: JWK;
|
|
35
|
+
driverParam: string;
|
|
36
|
+
notNull: true;
|
|
37
|
+
hasDefault: false;
|
|
38
|
+
isPrimaryKey: false;
|
|
39
|
+
isAutoincrement: false;
|
|
40
|
+
hasRuntimeDefault: false;
|
|
41
|
+
enumValues: undefined;
|
|
42
|
+
baseColumn: never;
|
|
43
|
+
identity: undefined;
|
|
44
|
+
generated: undefined;
|
|
45
|
+
}, {}, {
|
|
46
|
+
$type: JWK;
|
|
47
|
+
}>;
|
|
48
|
+
createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
49
|
+
name: "createdAt";
|
|
50
|
+
tableName: "app_keys";
|
|
51
|
+
dataType: "date";
|
|
52
|
+
columnType: "SQLiteTimestamp";
|
|
53
|
+
data: Date;
|
|
54
|
+
driverParam: number;
|
|
55
|
+
notNull: true;
|
|
56
|
+
hasDefault: false;
|
|
57
|
+
isPrimaryKey: false;
|
|
58
|
+
isAutoincrement: false;
|
|
59
|
+
hasRuntimeDefault: false;
|
|
60
|
+
enumValues: undefined;
|
|
61
|
+
baseColumn: never;
|
|
62
|
+
identity: undefined;
|
|
63
|
+
generated: undefined;
|
|
64
|
+
}, {}, {}>;
|
|
65
|
+
};
|
|
66
|
+
dialect: 'sqlite';
|
|
67
|
+
}>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
|
|
2
|
+
/**
|
|
3
|
+
* The app's signing key (ES256), generated on its first start: its client authentication
|
|
4
|
+
* (`private_key_jwt`). Only its public part ever leaves the app, in the manifest. One row.
|
|
5
|
+
*/
|
|
6
|
+
export const appKeys = sqliteTable('app_keys', {
|
|
7
|
+
kid: text().primaryKey(),
|
|
8
|
+
privateJwk: text({ mode: 'json' }).$type().notNull(),
|
|
9
|
+
createdAt: integer({ mode: 'timestamp_ms' }).notNull(),
|
|
10
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type AppPublicKey } from '@artemis-apps/contracts';
|
|
2
|
+
import type { PlatformDatabase } from '../platform.tables.ts';
|
|
3
|
+
/** The app's signing key: the private part signs, the public part goes in the manifest. */
|
|
4
|
+
export interface AppKey {
|
|
5
|
+
kid: string;
|
|
6
|
+
/** Signs the app's client assertions. */
|
|
7
|
+
privateKey: CryptoKey;
|
|
8
|
+
publicJwk: AppPublicKey;
|
|
9
|
+
}
|
|
10
|
+
export declare function createAppKeyRepository(database: PlatformDatabase): {
|
|
11
|
+
/** The app's key, generated and stored on first use. */
|
|
12
|
+
findOrCreate(): Promise<AppKey>;
|
|
13
|
+
};
|
|
14
|
+
export type AppKeyRepository = ReturnType<typeof createAppKeyRepository>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { generateKeyPairSync, randomUUID } from 'node:crypto';
|
|
2
|
+
import { APP_KEY_ALGORITHM, AppPublicKeySchema } from '@artemis-apps/contracts';
|
|
3
|
+
import { importJWK } from 'jose';
|
|
4
|
+
import { appKeys } from './app-key.entity.js';
|
|
5
|
+
function generatePrivateJwk() {
|
|
6
|
+
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
|
7
|
+
return privateKey.export({ format: 'jwk' });
|
|
8
|
+
}
|
|
9
|
+
export function createAppKeyRepository(database) {
|
|
10
|
+
return {
|
|
11
|
+
/** The app's key, generated and stored on first use. */
|
|
12
|
+
async findOrCreate() {
|
|
13
|
+
const stored = database.select().from(appKeys).get();
|
|
14
|
+
const row = stored ?? { kid: randomUUID(), privateJwk: generatePrivateJwk() };
|
|
15
|
+
if (!stored)
|
|
16
|
+
database
|
|
17
|
+
.insert(appKeys)
|
|
18
|
+
.values({ ...row, createdAt: new Date() })
|
|
19
|
+
.run();
|
|
20
|
+
const { kid, privateJwk } = row;
|
|
21
|
+
const { kty, crv, x, y } = privateJwk;
|
|
22
|
+
return {
|
|
23
|
+
kid,
|
|
24
|
+
privateKey: (await importJWK(privateJwk, APP_KEY_ALGORITHM)),
|
|
25
|
+
// Only the public members: the schema refuses anything else.
|
|
26
|
+
publicJwk: AppPublicKeySchema.parse({
|
|
27
|
+
kty,
|
|
28
|
+
crv,
|
|
29
|
+
x,
|
|
30
|
+
y,
|
|
31
|
+
kid,
|
|
32
|
+
alg: APP_KEY_ALGORITHM,
|
|
33
|
+
use: 'sig',
|
|
34
|
+
}),
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { type AppManifest } from '@artemis-apps/contracts';
|
|
2
|
+
export interface ManifestRoutesOptions {
|
|
3
|
+
/** The app's complete manifest (see `createPlatform`). */
|
|
4
|
+
manifest: () => Promise<AppManifest>;
|
|
5
|
+
}
|
|
6
|
+
/** The manifest at its conventional path: the core compares it with the one pasted to enroll. */
|
|
7
|
+
export declare function createManifestRoutes({ manifest }: ManifestRoutesOptions): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
|
|
8
|
+
"/.well-known/artemis/app.json": {
|
|
9
|
+
$get: {
|
|
10
|
+
output: {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
description?: string | undefined;
|
|
14
|
+
permissions: import("@artemis-apps/contracts").DelegablePermission[];
|
|
15
|
+
types: {
|
|
16
|
+
id: string;
|
|
17
|
+
version: number;
|
|
18
|
+
parent: string | null;
|
|
19
|
+
titleFields: string[];
|
|
20
|
+
schema: {
|
|
21
|
+
[x: string]: string | number | boolean | import("hono/utils/types").JSONValue[] | {
|
|
22
|
+
[x: string]: string | number | boolean | import("hono/utils/types").JSONValue[] | /*elided*/ any | null;
|
|
23
|
+
} | null;
|
|
24
|
+
};
|
|
25
|
+
permissions: {
|
|
26
|
+
[x: string]: string | null;
|
|
27
|
+
};
|
|
28
|
+
operations: {
|
|
29
|
+
[x: string]: string;
|
|
30
|
+
};
|
|
31
|
+
kinds: string[];
|
|
32
|
+
actions: {
|
|
33
|
+
[x: string]: {
|
|
34
|
+
permission: string;
|
|
35
|
+
target: "page" | "server";
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
messages: {
|
|
39
|
+
en?: {
|
|
40
|
+
name: string;
|
|
41
|
+
plural: string;
|
|
42
|
+
permissions: {
|
|
43
|
+
[x: string]: {
|
|
44
|
+
label: string;
|
|
45
|
+
description: string;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
operations: {
|
|
49
|
+
[x: string]: string;
|
|
50
|
+
};
|
|
51
|
+
kinds: {
|
|
52
|
+
[x: string]: string;
|
|
53
|
+
};
|
|
54
|
+
actions: {
|
|
55
|
+
[x: string]: string;
|
|
56
|
+
};
|
|
57
|
+
} | undefined;
|
|
58
|
+
fr?: {
|
|
59
|
+
name: string;
|
|
60
|
+
plural: string;
|
|
61
|
+
permissions: {
|
|
62
|
+
[x: string]: {
|
|
63
|
+
label: string;
|
|
64
|
+
description: string;
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
operations: {
|
|
68
|
+
[x: string]: string;
|
|
69
|
+
};
|
|
70
|
+
kinds: {
|
|
71
|
+
[x: string]: string;
|
|
72
|
+
};
|
|
73
|
+
actions: {
|
|
74
|
+
[x: string]: string;
|
|
75
|
+
};
|
|
76
|
+
} | undefined;
|
|
77
|
+
};
|
|
78
|
+
}[];
|
|
79
|
+
listed?: boolean | undefined;
|
|
80
|
+
kinds?: {
|
|
81
|
+
[x: string]: {
|
|
82
|
+
kind: string;
|
|
83
|
+
icon: string;
|
|
84
|
+
template?: string | undefined;
|
|
85
|
+
}[];
|
|
86
|
+
} | undefined;
|
|
87
|
+
handles?: {
|
|
88
|
+
[x: string]: {
|
|
89
|
+
[x: string]: string[];
|
|
90
|
+
};
|
|
91
|
+
} | undefined;
|
|
92
|
+
url: string;
|
|
93
|
+
provides: {
|
|
94
|
+
[x: string]: {
|
|
95
|
+
operations: string[];
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
jwks: {
|
|
99
|
+
keys: {
|
|
100
|
+
kty: "EC";
|
|
101
|
+
crv: "P-256";
|
|
102
|
+
x: string;
|
|
103
|
+
y: string;
|
|
104
|
+
kid: string;
|
|
105
|
+
alg: "ES256";
|
|
106
|
+
use: "sig";
|
|
107
|
+
}[];
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
outputFormat: "json";
|
|
111
|
+
status: import("hono/utils/http-status").ContentfulStatusCode;
|
|
112
|
+
input: {};
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
}, "/", "/.well-known/artemis/app.json">;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { APP_PROTOCOL_PATHS } from '@artemis-apps/contracts';
|
|
2
|
+
import { Hono } from 'hono';
|
|
3
|
+
/** The manifest at its conventional path: the core compares it with the one pasted to enroll. */
|
|
4
|
+
export function createManifestRoutes({ manifest }) {
|
|
5
|
+
return new Hono().get(APP_PROTOCOL_PATHS.manifest, async (context) => {
|
|
6
|
+
context.header('Cache-Control', 'no-store');
|
|
7
|
+
return context.json((await manifest()));
|
|
8
|
+
});
|
|
9
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Account, type AccountClaims, type AccountPreferences } from '@artemis-apps/contracts';
|
|
2
|
+
/** The account an ID token identifies; `undefined` when its avatar claims are unusable. */
|
|
3
|
+
export declare function accountFromClaims(claims: AccountClaims): Account | undefined;
|
|
4
|
+
/** The preferences ID token claims carry; a language the platform doesn't speak is English. */
|
|
5
|
+
export declare function preferencesFromClaims({ locale }: AccountClaims): AccountPreferences;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { AvatarSchema, DEFAULT_LOCALE, isLocale, } from '@artemis-apps/contracts';
|
|
2
|
+
/**
|
|
3
|
+
* The avatar carried by ID token claims: `picture` is the public URL of an uploaded image (its
|
|
4
|
+
* last path segment is the file id), `avatar_seed` the seed of a generated one.
|
|
5
|
+
* `undefined` when the claims carry neither, or something that is not an avatar.
|
|
6
|
+
*/
|
|
7
|
+
function avatarFromClaims({ picture, avatar_seed: seed }) {
|
|
8
|
+
const candidate = picture
|
|
9
|
+
? { kind: 'file', fileId: new URL(picture).pathname.split('/').pop(), url: picture }
|
|
10
|
+
: { kind: 'generated', seed };
|
|
11
|
+
const parsed = AvatarSchema.safeParse(candidate);
|
|
12
|
+
return parsed.success ? parsed.data : undefined;
|
|
13
|
+
}
|
|
14
|
+
/** The account an ID token identifies; `undefined` when its avatar claims are unusable. */
|
|
15
|
+
export function accountFromClaims(claims) {
|
|
16
|
+
const avatar = avatarFromClaims(claims);
|
|
17
|
+
return avatar && { id: claims.sub, email: claims.email, name: claims.name, avatar };
|
|
18
|
+
}
|
|
19
|
+
/** The preferences ID token claims carry; a language the platform doesn't speak is English. */
|
|
20
|
+
export function preferencesFromClaims({ locale }) {
|
|
21
|
+
return { locale: isLocale(locale) ? locale : DEFAULT_LOCALE };
|
|
22
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type EntityGrantTarget } from '@artemis-apps/contracts';
|
|
2
|
+
import { type JWTPayload } from 'jose';
|
|
3
|
+
import type { AppKey } from '../keys/app-key.repository.ts';
|
|
4
|
+
import type { PlatformConfig } from '../platform.config.ts';
|
|
5
|
+
import type { SessionGrant } from '../session/app-session.repository.ts';
|
|
6
|
+
export interface AuthorizationRequest {
|
|
7
|
+
authorizationUrl: string;
|
|
8
|
+
state: string;
|
|
9
|
+
codeVerifier: string;
|
|
10
|
+
}
|
|
11
|
+
/** An access token of the app itself (`client_credentials`), for its own calls to the core. */
|
|
12
|
+
export interface AppToken {
|
|
13
|
+
accessToken: string;
|
|
14
|
+
expiresAt: Date;
|
|
15
|
+
}
|
|
16
|
+
/** An access token of the app for an account, limited to one entity (an entity grant). */
|
|
17
|
+
export interface EntityGrant {
|
|
18
|
+
accessToken: string;
|
|
19
|
+
expiresAt: Date;
|
|
20
|
+
}
|
|
21
|
+
/** The account refused to allow the app (`access_denied`): nothing went wrong. */
|
|
22
|
+
export declare class AuthorizationDeniedError extends Error {
|
|
23
|
+
readonly name = "AuthorizationDeniedError";
|
|
24
|
+
}
|
|
25
|
+
/** The core does not know this client (any more): the app is not enrolled. */
|
|
26
|
+
export declare class InvalidClientError extends Error {
|
|
27
|
+
readonly name = "InvalidClientError";
|
|
28
|
+
}
|
|
29
|
+
export interface OidcClientOptions {
|
|
30
|
+
config: PlatformConfig;
|
|
31
|
+
appKey: Promise<AppKey>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The app as an OAuth 2.1 / OpenID Connect client of its core (`openid-client`): it
|
|
35
|
+
* authenticates with its key (`private_key_jwt`), pushes its authorization requests (PAR) with
|
|
36
|
+
* PKCE, and verifies what the core signs (security events, logout and provider tokens) against
|
|
37
|
+
* the core's JWKS. Throws `InvalidClientError` whenever the core does not know it.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createOidcClient({ config, appKey }: OidcClientOptions): {
|
|
40
|
+
/** Pushes the authorization request (PAR); the browser goes to the returned URL. */
|
|
41
|
+
startAuthorization(): Promise<AuthorizationRequest>;
|
|
42
|
+
/** `callbackUrl` must be the public URL the core redirected to (query included). */
|
|
43
|
+
completeAuthorization(callbackUrl: URL, { state, codeVerifier }: Pick<AuthorizationRequest, 'state' | 'codeVerifier'>): Promise<SessionGrant>;
|
|
44
|
+
/** Returns `undefined` when the core refuses the refresh token (revoked grant). */
|
|
45
|
+
refresh(grant: SessionGrant & {
|
|
46
|
+
refreshToken: string;
|
|
47
|
+
}): Promise<SessionGrant | undefined>;
|
|
48
|
+
/** An access token of the app itself. Throws `InvalidClientError` while it is not enrolled. */
|
|
49
|
+
requestAppToken(): Promise<AppToken>;
|
|
50
|
+
/**
|
|
51
|
+
* Exchanges an account's access token for an entity grant (RFC 8693): `permissions` of the
|
|
52
|
+
* entity's type, on that entity only. Throws the core's refusal as a `ResponseBodyError`.
|
|
53
|
+
*/
|
|
54
|
+
exchangeEntityGrant(subjectToken: string, target: EntityGrantTarget, permissions: readonly string[]): Promise<EntityGrant>;
|
|
55
|
+
/** Revokes a token at the core (RFC 7009). */
|
|
56
|
+
revoke(token: string): Promise<void>;
|
|
57
|
+
buildSignOutUrl(idTokenHint?: string): Promise<string>;
|
|
58
|
+
/**
|
|
59
|
+
* Verifies a JWT the core signed for this app (`aud`: its id), of the given `typ` when one
|
|
60
|
+
* is set. Throws `HTTPException(401)` for anything else.
|
|
61
|
+
*/
|
|
62
|
+
verifyCoreToken(token: string, type?: string): Promise<JWTPayload>;
|
|
63
|
+
};
|
|
64
|
+
export type OidcClient = ReturnType<typeof createOidcClient>;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { AccountClaimsSchema, APP_ADMINISTRATOR_CLAIM, appRedirectUri, coreIssuerUrl, DEFAULT_LOCALE, ENTITY_GRANT, formatScope, intersectPermissions, OPENID_SCOPE, parseScope, } from '@artemis-apps/contracts';
|
|
2
|
+
import { HTTPException } from 'hono/http-exception';
|
|
3
|
+
import { createRemoteJWKSet, customFetch as joseCustomFetch, jwtVerify, } from 'jose';
|
|
4
|
+
import { AuthorizationResponseError, allowInsecureRequests, authorizationCodeGrant, buildAuthorizationUrlWithPAR, buildEndSessionUrl, calculatePKCECodeChallenge, clientCredentialsGrant, customFetch, discovery, genericGrantRequest, PrivateKeyJwt, ResponseBodyError, randomPKCECodeVerifier, randomState, refreshTokenGrant, tokenRevocation, } from 'openid-client';
|
|
5
|
+
import { accountFromClaims, preferencesFromClaims } from './account-claims.js';
|
|
6
|
+
/** The account refused to allow the app (`access_denied`): nothing went wrong. */
|
|
7
|
+
export class AuthorizationDeniedError extends Error {
|
|
8
|
+
name = 'AuthorizationDeniedError';
|
|
9
|
+
}
|
|
10
|
+
/** The core does not know this client (any more): the app is not enrolled. */
|
|
11
|
+
export class InvalidClientError extends Error {
|
|
12
|
+
name = 'InvalidClientError';
|
|
13
|
+
}
|
|
14
|
+
const isInvalidClient = (error) => error instanceof ResponseBodyError && error.error === 'invalid_client';
|
|
15
|
+
/**
|
|
16
|
+
* The app as an OAuth 2.1 / OpenID Connect client of its core (`openid-client`): it
|
|
17
|
+
* authenticates with its key (`private_key_jwt`), pushes its authorization requests (PAR) with
|
|
18
|
+
* PKCE, and verifies what the core signs (security events, logout and provider tokens) against
|
|
19
|
+
* the core's JWKS. Throws `InvalidClientError` whenever the core does not know it.
|
|
20
|
+
*/
|
|
21
|
+
export function createOidcClient({ config, appKey }) {
|
|
22
|
+
const { appUrl, coreUrl, manifest } = config;
|
|
23
|
+
const issuer = new URL(coreIssuerUrl(coreUrl));
|
|
24
|
+
const redirectUri = appRedirectUri(appUrl);
|
|
25
|
+
const scope = `${OPENID_SCOPE} ${formatScope(manifest.permissions)}`;
|
|
26
|
+
let cached;
|
|
27
|
+
let coreKeys;
|
|
28
|
+
async function discover() {
|
|
29
|
+
const { privateKey, kid } = await appKey;
|
|
30
|
+
return discovery(issuer, manifest.id, undefined, PrivateKeyJwt({ key: privateKey, kid }), {
|
|
31
|
+
// Development cores run on plain http://localhost; production issuers stay https-only.
|
|
32
|
+
execute: issuer.protocol === 'http:' ? [allowInsecureRequests] : [],
|
|
33
|
+
...(config.fetch && { [customFetch]: config.fetch }),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/** Discovery is cached, and redone after a failure. */
|
|
37
|
+
function configuration() {
|
|
38
|
+
if (!cached) {
|
|
39
|
+
const pending = discover();
|
|
40
|
+
pending.catch(() => {
|
|
41
|
+
if (cached === pending)
|
|
42
|
+
cached = undefined;
|
|
43
|
+
});
|
|
44
|
+
cached = pending;
|
|
45
|
+
}
|
|
46
|
+
return cached;
|
|
47
|
+
}
|
|
48
|
+
/** Runs a request authenticated as the app, telling `invalid_client` apart. */
|
|
49
|
+
async function asClient(request) {
|
|
50
|
+
try {
|
|
51
|
+
return await request(await configuration());
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (isInvalidClient(error))
|
|
55
|
+
throw new InvalidClientError('The core does not know this app.');
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Maps a token response; fields a refresh response may omit fall back to `previous`. */
|
|
60
|
+
function toSessionGrant(tokens, previous) {
|
|
61
|
+
const claims = tokens.claims();
|
|
62
|
+
const parsedClaims = claims && AccountClaimsSchema.safeParse(claims);
|
|
63
|
+
const claimedAccount = parsedClaims?.success ? accountFromClaims(parsedClaims.data) : undefined;
|
|
64
|
+
if (parsedClaims && !claimedAccount) {
|
|
65
|
+
throw new HTTPException(502, {
|
|
66
|
+
message: 'The core issued an ID token without account claims.',
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
// A refreshed ID token carries the account as it is now (name, email, avatar, language).
|
|
70
|
+
const account = claimedAccount ?? previous?.account;
|
|
71
|
+
const preferences = parsedClaims?.success
|
|
72
|
+
? preferencesFromClaims(parsedClaims.data)
|
|
73
|
+
: (previous?.preferences ?? { locale: DEFAULT_LOCALE });
|
|
74
|
+
const administrator = parsedClaims?.success
|
|
75
|
+
? parsedClaims.data[APP_ADMINISTRATOR_CLAIM] === true
|
|
76
|
+
: (previous?.administrator ?? false);
|
|
77
|
+
const idToken = tokens.id_token ?? previous?.idToken;
|
|
78
|
+
const sid = typeof claims?.sid === 'string' ? claims.sid : previous?.sid;
|
|
79
|
+
if (!account || !idToken || !sid) {
|
|
80
|
+
throw new HTTPException(502, { message: 'The core did not issue an ID token.' });
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
account,
|
|
84
|
+
preferences,
|
|
85
|
+
administrator,
|
|
86
|
+
idToken,
|
|
87
|
+
sid,
|
|
88
|
+
permissions: tokens.scope === undefined
|
|
89
|
+
? (previous?.permissions ?? [])
|
|
90
|
+
: intersectPermissions(manifest.permissions, parseScope(tokens.scope)),
|
|
91
|
+
accessToken: tokens.access_token,
|
|
92
|
+
refreshToken: tokens.refresh_token ?? previous?.refreshToken ?? null,
|
|
93
|
+
accessTokenExpiresAt: new Date(Date.now() + (tokens.expiresIn() ?? 0) * 1000),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
/** Pushes the authorization request (PAR); the browser goes to the returned URL. */
|
|
98
|
+
async startAuthorization() {
|
|
99
|
+
const state = randomState();
|
|
100
|
+
const codeVerifier = randomPKCECodeVerifier();
|
|
101
|
+
const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
|
|
102
|
+
const authorizationUrl = await asClient((configuration) => buildAuthorizationUrlWithPAR(configuration, {
|
|
103
|
+
redirect_uri: redirectUri,
|
|
104
|
+
scope,
|
|
105
|
+
state,
|
|
106
|
+
code_challenge: codeChallenge,
|
|
107
|
+
code_challenge_method: 'S256',
|
|
108
|
+
}));
|
|
109
|
+
return { authorizationUrl: authorizationUrl.toString(), state, codeVerifier };
|
|
110
|
+
},
|
|
111
|
+
/** `callbackUrl` must be the public URL the core redirected to (query included). */
|
|
112
|
+
async completeAuthorization(callbackUrl, { state, codeVerifier }) {
|
|
113
|
+
try {
|
|
114
|
+
const tokens = await asClient((configuration) => authorizationCodeGrant(configuration, callbackUrl, {
|
|
115
|
+
expectedState: state,
|
|
116
|
+
pkceCodeVerifier: codeVerifier,
|
|
117
|
+
idTokenExpected: true,
|
|
118
|
+
}));
|
|
119
|
+
return toSessionGrant(tokens);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error instanceof AuthorizationResponseError && error.error === 'access_denied') {
|
|
123
|
+
throw new AuthorizationDeniedError('The account did not allow this app.');
|
|
124
|
+
}
|
|
125
|
+
if (error instanceof AuthorizationResponseError || error instanceof ResponseBodyError) {
|
|
126
|
+
throw new HTTPException(400, {
|
|
127
|
+
message: `Sign-in refused by the core: ${error.error_description ?? error.error}.`,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
/** Returns `undefined` when the core refuses the refresh token (revoked grant). */
|
|
134
|
+
async refresh(grant) {
|
|
135
|
+
try {
|
|
136
|
+
const tokens = await asClient((configuration) => refreshTokenGrant(configuration, grant.refreshToken));
|
|
137
|
+
return toSessionGrant(tokens, grant);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error instanceof ResponseBodyError)
|
|
141
|
+
return undefined;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
/** An access token of the app itself. Throws `InvalidClientError` while it is not enrolled. */
|
|
146
|
+
async requestAppToken() {
|
|
147
|
+
const tokens = await asClient((configuration) => clientCredentialsGrant(configuration));
|
|
148
|
+
return {
|
|
149
|
+
accessToken: tokens.access_token,
|
|
150
|
+
expiresAt: new Date(Date.now() + (tokens.expiresIn() ?? 0) * 1000),
|
|
151
|
+
};
|
|
152
|
+
},
|
|
153
|
+
/**
|
|
154
|
+
* Exchanges an account's access token for an entity grant (RFC 8693): `permissions` of the
|
|
155
|
+
* entity's type, on that entity only. Throws the core's refusal as a `ResponseBodyError`.
|
|
156
|
+
*/
|
|
157
|
+
async exchangeEntityGrant(subjectToken, target, permissions) {
|
|
158
|
+
const tokens = await asClient((configuration) => genericGrantRequest(configuration, ENTITY_GRANT.grantType, {
|
|
159
|
+
subject_token: subjectToken,
|
|
160
|
+
subject_token_type: ENTITY_GRANT.tokenType,
|
|
161
|
+
requested_token_type: ENTITY_GRANT.tokenType,
|
|
162
|
+
scope: formatScope(permissions),
|
|
163
|
+
[ENTITY_GRANT.entityParam]: JSON.stringify(target),
|
|
164
|
+
}));
|
|
165
|
+
return {
|
|
166
|
+
accessToken: tokens.access_token,
|
|
167
|
+
expiresAt: new Date(Date.now() + (tokens.expiresIn() ?? 0) * 1000),
|
|
168
|
+
};
|
|
169
|
+
},
|
|
170
|
+
/** Revokes a token at the core (RFC 7009). */
|
|
171
|
+
async revoke(token) {
|
|
172
|
+
await asClient((configuration) => tokenRevocation(configuration, token));
|
|
173
|
+
},
|
|
174
|
+
async buildSignOutUrl(idTokenHint) {
|
|
175
|
+
const endSessionUrl = buildEndSessionUrl(await configuration(), {
|
|
176
|
+
post_logout_redirect_uri: appUrl,
|
|
177
|
+
...(idTokenHint && { id_token_hint: idTokenHint }),
|
|
178
|
+
});
|
|
179
|
+
return endSessionUrl.toString();
|
|
180
|
+
},
|
|
181
|
+
/**
|
|
182
|
+
* Verifies a JWT the core signed for this app (`aud`: its id), of the given `typ` when one
|
|
183
|
+
* is set. Throws `HTTPException(401)` for anything else.
|
|
184
|
+
*/
|
|
185
|
+
async verifyCoreToken(token, type) {
|
|
186
|
+
const metadata = (await configuration()).serverMetadata();
|
|
187
|
+
if (!metadata.jwks_uri)
|
|
188
|
+
throw new HTTPException(502, { message: 'The core has no JWKS.' });
|
|
189
|
+
coreKeys ??= createRemoteJWKSet(new URL(metadata.jwks_uri), {
|
|
190
|
+
...(config.fetch && { [joseCustomFetch]: config.fetch }),
|
|
191
|
+
});
|
|
192
|
+
try {
|
|
193
|
+
const { payload } = await jwtVerify(token, coreKeys, {
|
|
194
|
+
issuer: metadata.issuer,
|
|
195
|
+
audience: manifest.id,
|
|
196
|
+
...(type && { typ: type }),
|
|
197
|
+
});
|
|
198
|
+
return payload;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
throw new HTTPException(401, { message: 'Invalid token.' });
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AppManifestDeclaration } from '@artemis-apps/contracts';
|
|
2
|
+
export interface PlatformConfig {
|
|
3
|
+
/** Public URL of this app (an origin, maybe with a base path): the `url` of its manifest. */
|
|
4
|
+
appUrl: string;
|
|
5
|
+
/** Origin of the core this app trusts: all it knows of the platform. */
|
|
6
|
+
coreUrl: string;
|
|
7
|
+
/**
|
|
8
|
+
* Where this server reaches the core directly (`http://127.0.0.1:4000` for the apps the core
|
|
9
|
+
* runs), when the core's public URL may not resolve or loop back from here. Browsers, tokens
|
|
10
|
+
* and the issuer keep `coreUrl`: only the server's own requests go there.
|
|
11
|
+
*/
|
|
12
|
+
coreInternalUrl?: string;
|
|
13
|
+
/** What the app declares about itself; the platform completes its manifest. */
|
|
14
|
+
manifest: AppManifestDeclaration;
|
|
15
|
+
/**
|
|
16
|
+
* The app's icon, an SVG document served at `APP_PROTOCOL_PATHS.icon` (the core's app switcher
|
|
17
|
+
* shows it). Without one, the icon path answers 404.
|
|
18
|
+
*/
|
|
19
|
+
icon?: string;
|
|
20
|
+
/** Outbound HTTP to the core. Defaults to the global `fetch`. */
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
}
|
|
File without changes
|