@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.
Files changed (64) hide show
  1. package/dist/account-deletion/account-deletion.service.d.ts +18 -0
  2. package/dist/account-deletion/account-deletion.service.js +18 -0
  3. package/dist/activity/core-activity.client.d.ts +20 -0
  4. package/dist/activity/core-activity.client.js +32 -0
  5. package/dist/core-api/core-api.client.d.ts +25 -0
  6. package/dist/core-api/core-api.client.js +63 -0
  7. package/dist/enrollment/enrollment.service.d.ts +30 -0
  8. package/dist/enrollment/enrollment.service.js +103 -0
  9. package/dist/entity-grants/entity-grant.service.d.ts +22 -0
  10. package/dist/entity-grants/entity-grant.service.js +49 -0
  11. package/dist/events/security-event.routes.d.ts +24 -0
  12. package/dist/events/security-event.routes.js +28 -0
  13. package/dist/handlers/handler.routes.d.ts +32 -0
  14. package/dist/handlers/handler.routes.js +74 -0
  15. package/dist/icon/app-icon.routes.d.ts +15 -0
  16. package/dist/icon/app-icon.routes.js +18 -0
  17. package/dist/index.d.ts +11 -0
  18. package/dist/index.js +4 -0
  19. package/dist/keys/app-key.entity.d.ts +67 -0
  20. package/dist/keys/app-key.entity.js +10 -0
  21. package/dist/keys/app-key.repository.d.ts +14 -0
  22. package/dist/keys/app-key.repository.js +38 -0
  23. package/dist/manifest/manifest.routes.d.ts +115 -0
  24. package/dist/manifest/manifest.routes.js +9 -0
  25. package/dist/oidc/account-claims.d.ts +5 -0
  26. package/dist/oidc/account-claims.js +22 -0
  27. package/dist/oidc/oidc.client.d.ts +64 -0
  28. package/dist/oidc/oidc.client.js +205 -0
  29. package/dist/platform.config.d.ts +22 -0
  30. package/dist/platform.config.js +0 -0
  31. package/dist/platform.d.ts +387 -0
  32. package/dist/platform.js +125 -0
  33. package/dist/platform.tables.d.ts +448 -0
  34. package/dist/platform.tables.js +9 -0
  35. package/dist/providers/provider.routes.d.ts +78 -0
  36. package/dist/providers/provider.routes.js +208 -0
  37. package/dist/relay/core-relay.routes.d.ts +26 -0
  38. package/dist/relay/core-relay.routes.js +64 -0
  39. package/dist/session/app-session.entity.d.ts +301 -0
  40. package/dist/session/app-session.entity.js +26 -0
  41. package/dist/session/app-session.repository.d.ts +34 -0
  42. package/dist/session/app-session.repository.js +87 -0
  43. package/dist/session/app-sign-in-attempt.entity.d.ts +82 -0
  44. package/dist/session/app-sign-in-attempt.entity.js +8 -0
  45. package/dist/session/app-sign-in-attempt.repository.d.ts +15 -0
  46. package/dist/session/app-sign-in-attempt.repository.js +29 -0
  47. package/dist/session/app.cookies.d.ts +22 -0
  48. package/dist/session/app.cookies.js +18 -0
  49. package/dist/session/require-permissions.middleware.d.ts +36 -0
  50. package/dist/session/require-permissions.middleware.js +34 -0
  51. package/dist/session/session.routes.d.ts +204 -0
  52. package/dist/session/session.routes.js +92 -0
  53. package/dist/session/session.service.d.ts +50 -0
  54. package/dist/session/session.service.js +137 -0
  55. package/dist/storage/core-storage.client.d.ts +27 -0
  56. package/dist/storage/core-storage.client.js +71 -0
  57. package/dist/testing/index.d.ts +2 -0
  58. package/dist/testing/index.js +3 -0
  59. package/dist/testing/platform-fixtures.d.ts +24 -0
  60. package/dist/testing/platform-fixtures.js +25 -0
  61. package/dist/testing/test-core.d.ts +73 -0
  62. package/dist/testing/test-core.js +134 -0
  63. package/package.json +45 -3
  64. package/README.md +0 -3
@@ -0,0 +1,87 @@
1
+ import { eq, lte } from 'drizzle-orm';
2
+ import { appSessions } from './app-session.entity.js';
3
+ function toAppSession(row) {
4
+ return {
5
+ tokenHash: row.tokenHash,
6
+ account: {
7
+ id: row.accountId,
8
+ email: row.accountEmail,
9
+ name: row.accountName,
10
+ avatar: row.accountAvatar,
11
+ },
12
+ preferences: { locale: row.accountLocale },
13
+ administrator: row.administrator,
14
+ permissions: row.permissions,
15
+ idToken: row.idToken,
16
+ sid: row.sid,
17
+ accessToken: row.accessToken,
18
+ refreshToken: row.refreshToken,
19
+ accessTokenExpiresAt: row.accessTokenExpiresAt,
20
+ expiresAt: row.expiresAt,
21
+ };
22
+ }
23
+ function toGrantColumns({ account, preferences, ...grant }) {
24
+ return {
25
+ accountId: account.id,
26
+ accountEmail: account.email,
27
+ accountName: account.name,
28
+ accountAvatar: account.avatar,
29
+ accountLocale: preferences.locale,
30
+ administrator: grant.administrator,
31
+ permissions: grant.permissions,
32
+ idToken: grant.idToken,
33
+ sid: grant.sid,
34
+ accessToken: grant.accessToken,
35
+ refreshToken: grant.refreshToken,
36
+ accessTokenExpiresAt: grant.accessTokenExpiresAt,
37
+ };
38
+ }
39
+ export function createAppSessionRepository(database) {
40
+ return {
41
+ find(tokenHash) {
42
+ const row = database
43
+ .select()
44
+ .from(appSessions)
45
+ .where(eq(appSessions.tokenHash, tokenHash))
46
+ .get();
47
+ return row && toAppSession(row);
48
+ },
49
+ create(session) {
50
+ database
51
+ .insert(appSessions)
52
+ .values({
53
+ tokenHash: session.tokenHash,
54
+ ...toGrantColumns(session),
55
+ expiresAt: session.expiresAt,
56
+ createdAt: new Date(),
57
+ })
58
+ .run();
59
+ },
60
+ /** Replaces the grant (tokens, permissions) of a session after a refresh. */
61
+ update(tokenHash, grant) {
62
+ const row = database
63
+ .update(appSessions)
64
+ .set(toGrantColumns(grant))
65
+ .where(eq(appSessions.tokenHash, tokenHash))
66
+ .returning()
67
+ .get();
68
+ return row && toAppSession(row);
69
+ },
70
+ delete(tokenHash) {
71
+ database.delete(appSessions).where(eq(appSessions.tokenHash, tokenHash)).run();
72
+ },
73
+ deleteExpired(now) {
74
+ database.delete(appSessions).where(lte(appSessions.expiresAt, now)).run();
75
+ },
76
+ /** Ends the app sessions of one core OIDC session (back-channel logout). */
77
+ deleteBySid(sid) {
78
+ database.delete(appSessions).where(eq(appSessions.sid, sid)).run();
79
+ },
80
+ deleteByAccount(accountId) {
81
+ database.delete(appSessions).where(eq(appSessions.accountId, accountId)).run();
82
+ },
83
+ deleteAll() {
84
+ database.delete(appSessions).run();
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,82 @@
1
+ /** Pending OIDC authorization requests, consumed once by the callback. */
2
+ export declare const appSignInAttempts: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3
+ name: "app_sign_in_attempts";
4
+ schema: undefined;
5
+ columns: {
6
+ state: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7
+ name: "state";
8
+ tableName: "app_sign_in_attempts";
9
+ dataType: "string";
10
+ columnType: "SQLiteText";
11
+ data: string;
12
+ driverParam: string;
13
+ notNull: true;
14
+ hasDefault: false;
15
+ isPrimaryKey: true;
16
+ isAutoincrement: false;
17
+ hasRuntimeDefault: false;
18
+ enumValues: [string, ...string[]];
19
+ baseColumn: never;
20
+ identity: undefined;
21
+ generated: undefined;
22
+ }, {}, {
23
+ length: undefined;
24
+ }>;
25
+ codeVerifier: import("drizzle-orm/sqlite-core").SQLiteColumn<{
26
+ name: "codeVerifier";
27
+ tableName: "app_sign_in_attempts";
28
+ dataType: "string";
29
+ columnType: "SQLiteText";
30
+ data: string;
31
+ driverParam: string;
32
+ notNull: true;
33
+ hasDefault: false;
34
+ isPrimaryKey: false;
35
+ isAutoincrement: false;
36
+ hasRuntimeDefault: false;
37
+ enumValues: [string, ...string[]];
38
+ baseColumn: never;
39
+ identity: undefined;
40
+ generated: undefined;
41
+ }, {}, {
42
+ length: undefined;
43
+ }>;
44
+ returnPath: import("drizzle-orm/sqlite-core").SQLiteColumn<{
45
+ name: "returnPath";
46
+ tableName: "app_sign_in_attempts";
47
+ dataType: "string";
48
+ columnType: "SQLiteText";
49
+ data: string;
50
+ driverParam: string;
51
+ notNull: true;
52
+ hasDefault: false;
53
+ isPrimaryKey: false;
54
+ isAutoincrement: false;
55
+ hasRuntimeDefault: false;
56
+ enumValues: [string, ...string[]];
57
+ baseColumn: never;
58
+ identity: undefined;
59
+ generated: undefined;
60
+ }, {}, {
61
+ length: undefined;
62
+ }>;
63
+ expiresAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
64
+ name: "expiresAt";
65
+ tableName: "app_sign_in_attempts";
66
+ dataType: "date";
67
+ columnType: "SQLiteTimestamp";
68
+ data: Date;
69
+ driverParam: number;
70
+ notNull: true;
71
+ hasDefault: false;
72
+ isPrimaryKey: false;
73
+ isAutoincrement: false;
74
+ hasRuntimeDefault: false;
75
+ enumValues: undefined;
76
+ baseColumn: never;
77
+ identity: undefined;
78
+ generated: undefined;
79
+ }, {}, {}>;
80
+ };
81
+ dialect: 'sqlite';
82
+ }>;
@@ -0,0 +1,8 @@
1
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
2
+ /** Pending OIDC authorization requests, consumed once by the callback. */
3
+ export const appSignInAttempts = sqliteTable('app_sign_in_attempts', {
4
+ state: text().primaryKey(),
5
+ codeVerifier: text().notNull(),
6
+ returnPath: text().notNull(),
7
+ expiresAt: integer({ mode: 'timestamp_ms' }).notNull(),
8
+ });
@@ -0,0 +1,15 @@
1
+ import type { PlatformDatabase } from '../platform.tables.ts';
2
+ export interface AppSignInAttempt {
3
+ state: string;
4
+ codeVerifier: string;
5
+ returnPath: string;
6
+ expiresAt: Date;
7
+ }
8
+ export declare function createAppSignInAttemptRepository(database: PlatformDatabase): {
9
+ create(attempt: AppSignInAttempt): void;
10
+ /** Deletes and returns the attempt: an attempt is usable once. */
11
+ consume(state: string): AppSignInAttempt | undefined;
12
+ deleteExpired(now: Date): void;
13
+ deleteAll(): void;
14
+ };
15
+ export type AppSignInAttemptRepository = ReturnType<typeof createAppSignInAttemptRepository>;
@@ -0,0 +1,29 @@
1
+ import { eq, lte } from 'drizzle-orm';
2
+ import { appSignInAttempts } from './app-sign-in-attempt.entity.js';
3
+ export function createAppSignInAttemptRepository(database) {
4
+ return {
5
+ create(attempt) {
6
+ database.insert(appSignInAttempts).values(attempt).run();
7
+ },
8
+ /** Deletes and returns the attempt: an attempt is usable once. */
9
+ consume(state) {
10
+ const row = database
11
+ .delete(appSignInAttempts)
12
+ .where(eq(appSignInAttempts.state, state))
13
+ .returning()
14
+ .get();
15
+ return (row && {
16
+ state: row.state,
17
+ codeVerifier: row.codeVerifier,
18
+ returnPath: row.returnPath,
19
+ expiresAt: row.expiresAt,
20
+ });
21
+ },
22
+ deleteExpired(now) {
23
+ database.delete(appSignInAttempts).where(lte(appSignInAttempts.expiresAt, now)).run();
24
+ },
25
+ deleteAll() {
26
+ database.delete(appSignInAttempts).run();
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,22 @@
1
+ import type { PlatformConfig } from '../platform.config.ts';
2
+ export interface AppCookiesOptions {
3
+ config: PlatformConfig;
4
+ }
5
+ /** Cookies are per host, not per port: the app id is their owner. */
6
+ export declare function createAppCookies({ config }: AppCookiesOptions): {
7
+ /** Opaque session token; the database only stores its hash. */
8
+ session: {
9
+ name: string;
10
+ read: (context: import("hono").Context) => string | undefined;
11
+ write: (context: import("hono").Context, value: string) => void;
12
+ clear: (context: import("hono").Context) => string | undefined;
13
+ };
14
+ /** Binds a pending sign-in attempt (its OAuth `state`) to the browser that started it. */
15
+ signIn: {
16
+ name: string;
17
+ read: (context: import("hono").Context) => string | undefined;
18
+ write: (context: import("hono").Context, value: string) => void;
19
+ clear: (context: import("hono").Context) => string | undefined;
20
+ };
21
+ };
22
+ export type AppCookies = ReturnType<typeof createAppCookies>;
@@ -0,0 +1,18 @@
1
+ import { createHttpOnlyCookie } from '@artemis-apps/server-kit';
2
+ import { APP_SESSION_TTL_MS, APP_SIGN_IN_ATTEMPT_TTL_MS } from './session.service.js';
3
+ /** Cookies are per host, not per port: the app id is their owner. */
4
+ export function createAppCookies({ config }) {
5
+ const owner = config.manifest.id;
6
+ const secure = new URL(config.appUrl).protocol === 'https:';
7
+ return {
8
+ /** Opaque session token; the database only stores its hash. */
9
+ session: createHttpOnlyCookie({ owner, purpose: 'session', secure, ttlMs: APP_SESSION_TTL_MS }),
10
+ /** Binds a pending sign-in attempt (its OAuth `state`) to the browser that started it. */
11
+ signIn: createHttpOnlyCookie({
12
+ owner,
13
+ purpose: 'sign_in',
14
+ secure,
15
+ ttlMs: APP_SIGN_IN_ATTEMPT_TTL_MS,
16
+ }),
17
+ };
18
+ }
@@ -0,0 +1,36 @@
1
+ import { type Account, type DelegablePermission } from '@artemis-apps/contracts';
2
+ import type { HttpOnlyCookie } from '@artemis-apps/server-kit';
3
+ import type { AppSession } from './app-session.repository.ts';
4
+ import type { SessionService } from './session.service.ts';
5
+ /** Hono environment of routes guarded by `requirePermissions`. */
6
+ export interface RequirePermissionsEnv {
7
+ Variables: {
8
+ current: {
9
+ account: Account;
10
+ /**
11
+ * The app the request comes through (a manifest id). Today always this app, reached from
12
+ * its own web client; another app calling this API would be recorded under its own id.
13
+ */
14
+ appId: string;
15
+ /** Permissions granted to this app for the signed-in account. */
16
+ permissions: DelegablePermission[];
17
+ /** The account administers the platform's apps: it may change this one's settings. */
18
+ administrator: boolean;
19
+ };
20
+ /** The app session behind the request: calls to the core on the account's behalf need it. */
21
+ appSession: AppSession;
22
+ };
23
+ }
24
+ export interface RequirePermissionsOptions {
25
+ /** This app's manifest id. */
26
+ appId: string;
27
+ sessionService: SessionService;
28
+ sessionCookie: HttpOnlyCookie;
29
+ }
30
+ export declare function createRequirePermissions({ appId, sessionService, sessionCookie, }: RequirePermissionsOptions): (...required: DelegablePermission[]) => import("hono").MiddlewareHandler<RequirePermissionsEnv, string, {}, Response>;
31
+ export type RequirePermissions = ReturnType<typeof createRequirePermissions>;
32
+ /**
33
+ * Guards the app's own settings: a signed-in account administering the platform's apps
34
+ * (`admin:apps:write` in the core, as its ID token says), whatever the app was granted.
35
+ */
36
+ export declare function createRequireAdministrator(requirePermissions: RequirePermissions): import("hono").MiddlewareHandler<RequirePermissionsEnv, string, {}, Response>;
@@ -0,0 +1,34 @@
1
+ import { hasPermissions } from '@artemis-apps/contracts';
2
+ import { createMiddleware } from 'hono/factory';
3
+ import { HTTPException } from 'hono/http-exception';
4
+ export function createRequirePermissions({ appId, sessionService, sessionCookie, }) {
5
+ return (...required) => createMiddleware(async (context, next) => {
6
+ const session = await sessionService.resolve(sessionCookie.read(context));
7
+ if (!session)
8
+ throw new HTTPException(401, { message: 'Sign in to continue.' });
9
+ if (!hasPermissions(session.permissions, required)) {
10
+ throw new HTTPException(403, { message: 'This action requires a permission you lack.' });
11
+ }
12
+ context.set('current', {
13
+ account: session.account,
14
+ appId,
15
+ permissions: session.permissions,
16
+ administrator: session.administrator,
17
+ });
18
+ context.set('appSession', session);
19
+ await next();
20
+ });
21
+ }
22
+ /**
23
+ * Guards the app's own settings: a signed-in account administering the platform's apps
24
+ * (`admin:apps:write` in the core, as its ID token says), whatever the app was granted.
25
+ */
26
+ export function createRequireAdministrator(requirePermissions) {
27
+ const signedIn = requirePermissions();
28
+ return createMiddleware((context, next) => signedIn(context, async () => {
29
+ if (!context.get('current').administrator) {
30
+ throw new HTTPException(403, { message: 'Only an administrator can change this.' });
31
+ }
32
+ await next();
33
+ }));
34
+ }
@@ -0,0 +1,204 @@
1
+ import { type AppManifest } from '@artemis-apps/contracts';
2
+ import type { EnrollmentService } from '../enrollment/enrollment.service.ts';
3
+ import { type OidcClient } from '../oidc/oidc.client.ts';
4
+ import type { PlatformConfig } from '../platform.config.ts';
5
+ import type { AppCookies } from './app.cookies.ts';
6
+ import type { SessionService } from './session.service.ts';
7
+ export interface SessionRoutesOptions {
8
+ config: PlatformConfig;
9
+ manifest: () => Promise<AppManifest>;
10
+ enrollment: Pick<EnrollmentService, 'isEnrolled'>;
11
+ sessionService: SessionService;
12
+ oidcClient: Pick<OidcClient, 'verifyCoreToken'>;
13
+ cookies: AppCookies;
14
+ }
15
+ /**
16
+ * Endpoints the app web client uses (session state, sign-in flow, sign-out), and the core's
17
+ * back-channel logout.
18
+ */
19
+ export declare function createSessionRoutes({ config, manifest, enrollment, sessionService, oidcClient, cookies, }: SessionRoutesOptions): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
20
+ "/api/platform/session": {
21
+ $get: {
22
+ output: {
23
+ status: "unenrolled";
24
+ manifest: {
25
+ id: string;
26
+ name: string;
27
+ description?: string | undefined;
28
+ permissions: import("@artemis-apps/contracts").DelegablePermission[];
29
+ types: {
30
+ id: string;
31
+ version: number;
32
+ parent: string | null;
33
+ titleFields: string[];
34
+ schema: {
35
+ [x: string]: string | number | boolean | import("hono/utils/types").JSONValue[] | {
36
+ [x: string]: string | number | boolean | import("hono/utils/types").JSONValue[] | /*elided*/ any | null;
37
+ } | null;
38
+ };
39
+ permissions: {
40
+ [x: string]: string | null;
41
+ };
42
+ operations: {
43
+ [x: string]: string;
44
+ };
45
+ kinds: string[];
46
+ actions: {
47
+ [x: string]: {
48
+ permission: string;
49
+ target: "page" | "server";
50
+ };
51
+ };
52
+ messages: {
53
+ en?: {
54
+ name: string;
55
+ plural: string;
56
+ permissions: {
57
+ [x: string]: {
58
+ label: string;
59
+ description: string;
60
+ };
61
+ };
62
+ operations: {
63
+ [x: string]: string;
64
+ };
65
+ kinds: {
66
+ [x: string]: string;
67
+ };
68
+ actions: {
69
+ [x: string]: string;
70
+ };
71
+ } | undefined;
72
+ fr?: {
73
+ name: string;
74
+ plural: string;
75
+ permissions: {
76
+ [x: string]: {
77
+ label: string;
78
+ description: string;
79
+ };
80
+ };
81
+ operations: {
82
+ [x: string]: string;
83
+ };
84
+ kinds: {
85
+ [x: string]: string;
86
+ };
87
+ actions: {
88
+ [x: string]: string;
89
+ };
90
+ } | undefined;
91
+ };
92
+ }[];
93
+ listed?: boolean | undefined;
94
+ kinds?: {
95
+ [x: string]: {
96
+ kind: string;
97
+ icon: string;
98
+ template?: string | undefined;
99
+ }[];
100
+ } | undefined;
101
+ handles?: {
102
+ [x: string]: {
103
+ [x: string]: string[];
104
+ };
105
+ } | undefined;
106
+ url: string;
107
+ provides: {
108
+ [x: string]: {
109
+ operations: string[];
110
+ };
111
+ };
112
+ jwks: {
113
+ keys: {
114
+ kty: "EC";
115
+ crv: "P-256";
116
+ x: string;
117
+ y: string;
118
+ kid: string;
119
+ alg: "ES256";
120
+ use: "sig";
121
+ }[];
122
+ };
123
+ };
124
+ coreUrl: string;
125
+ };
126
+ outputFormat: "json";
127
+ status: import("hono/utils/http-status").ContentfulStatusCode;
128
+ input: {};
129
+ } | {
130
+ output: {
131
+ status: "unauthenticated";
132
+ signInUrl: string;
133
+ };
134
+ outputFormat: "json";
135
+ status: import("hono/utils/http-status").ContentfulStatusCode;
136
+ input: {};
137
+ } | {
138
+ output: {
139
+ status: "authenticated";
140
+ appId: string;
141
+ account: {
142
+ id: string;
143
+ email: string;
144
+ name: string;
145
+ avatar: {
146
+ kind: "generated";
147
+ seed: string;
148
+ } | {
149
+ kind: "file";
150
+ fileId: string;
151
+ url: string;
152
+ };
153
+ };
154
+ permissions: import("@artemis-apps/contracts").DelegablePermission[];
155
+ preferences: {
156
+ locale: "en" | "fr";
157
+ };
158
+ administrator: boolean;
159
+ coreUrl: string;
160
+ };
161
+ outputFormat: "json";
162
+ status: import("hono/utils/http-status").ContentfulStatusCode;
163
+ input: {};
164
+ };
165
+ };
166
+ } & {
167
+ "/api/platform/sign-in": {
168
+ $get: {
169
+ output: undefined;
170
+ outputFormat: "redirect";
171
+ status: 302;
172
+ input: {};
173
+ };
174
+ };
175
+ } & {
176
+ "/api/platform/callback": {
177
+ $get: {
178
+ output: undefined;
179
+ outputFormat: "redirect";
180
+ status: 302;
181
+ input: {};
182
+ };
183
+ };
184
+ } & {
185
+ "/api/platform/sign-out": {
186
+ $post: {
187
+ output: {
188
+ redirectTo: string;
189
+ };
190
+ outputFormat: "json";
191
+ status: import("hono/utils/http-status").ContentfulStatusCode;
192
+ input: {};
193
+ };
194
+ };
195
+ } & {
196
+ "/api/platform/back-channel-logout": {
197
+ $post: {
198
+ output: null;
199
+ outputFormat: "body";
200
+ status: 200;
201
+ input: {};
202
+ };
203
+ };
204
+ }, "/", "/api/platform/back-channel-logout">;
@@ -0,0 +1,92 @@
1
+ import { APP_PROTOCOL_PATHS, appBasePath, appEndpoint, CORE_PROTOCOL_PATHS, RETURN_TO_PARAM, sanitizeReturnPath, } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ import { HTTPException } from 'hono/http-exception';
4
+ import { AuthorizationDeniedError } from '../oidc/oidc.client.js';
5
+ /** The event a logout token carries (OpenID Connect Back-Channel Logout 1.0). */
6
+ const BACK_CHANNEL_LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
7
+ /**
8
+ * Endpoints the app web client uses (session state, sign-in flow, sign-out), and the core's
9
+ * back-channel logout.
10
+ */
11
+ export function createSessionRoutes({ config, manifest, enrollment, sessionService, oidcClient, cookies, }) {
12
+ const basePath = appBasePath(config.appUrl);
13
+ /** A return path on the origin, kept within the app (its base path), else the app's root. */
14
+ const withinApp = (path) => path === basePath || path.startsWith(`${basePath}/`) ? path : `${basePath}/`;
15
+ return new Hono()
16
+ .get(APP_PROTOCOL_PATHS.session, async (context) => {
17
+ context.header('Cache-Control', 'no-store');
18
+ if (!(await enrollment.isEnrolled())) {
19
+ return context.json({
20
+ status: 'unenrolled',
21
+ manifest: await manifest(),
22
+ coreUrl: config.coreUrl,
23
+ });
24
+ }
25
+ const session = await sessionService.resolve(cookies.session.read(context));
26
+ if (!session) {
27
+ return context.json({
28
+ status: 'unauthenticated',
29
+ signInUrl: appEndpoint(config.appUrl, APP_PROTOCOL_PATHS.signIn),
30
+ });
31
+ }
32
+ return context.json({
33
+ status: 'authenticated',
34
+ appId: config.manifest.id,
35
+ account: session.account,
36
+ permissions: session.permissions,
37
+ preferences: session.preferences,
38
+ administrator: session.administrator,
39
+ coreUrl: config.coreUrl,
40
+ });
41
+ })
42
+ .get(APP_PROTOCOL_PATHS.signIn, async (context) => {
43
+ // Not enrolled: the web client shows the manifest from the session state.
44
+ if (!(await enrollment.isEnrolled()))
45
+ return context.redirect(`${config.appUrl}/`);
46
+ const returnPath = withinApp(sanitizeReturnPath(context.req.query(RETURN_TO_PARAM)));
47
+ const { authorizationUrl, state } = await sessionService.startSignIn(returnPath);
48
+ cookies.signIn.write(context, state);
49
+ return context.redirect(authorizationUrl);
50
+ })
51
+ .get(APP_PROTOCOL_PATHS.callback, async (context) => {
52
+ const browserState = cookies.signIn.read(context);
53
+ cookies.signIn.clear(context);
54
+ // The redirect URI is derived from the public app URL, whatever proxy sits in front.
55
+ const { search } = new URL(context.req.url);
56
+ const callbackUrl = new URL(appEndpoint(config.appUrl, `${APP_PROTOCOL_PATHS.callback}${search}`));
57
+ try {
58
+ const { token, returnPath } = await sessionService.completeSignIn(browserState, callbackUrl);
59
+ cookies.session.write(context, token);
60
+ return context.redirect(returnPath);
61
+ }
62
+ catch (error) {
63
+ // The account would rather not use the app: back to the platform.
64
+ if (error instanceof AuthorizationDeniedError) {
65
+ return context.redirect(new URL(CORE_PROTOCOL_PATHS.accountPage, config.coreUrl).href);
66
+ }
67
+ throw error;
68
+ }
69
+ })
70
+ .post(APP_PROTOCOL_PATHS.signOut, async (context) => {
71
+ const redirectTo = await sessionService.signOut(cookies.session.read(context));
72
+ cookies.session.clear(context);
73
+ return context.json({ redirectTo });
74
+ })
75
+ .post(APP_PROTOCOL_PATHS.backChannelLogout, async (context) => {
76
+ context.header('Cache-Control', 'no-store');
77
+ const form = await context.req.parseBody();
78
+ const logoutToken = form.logout_token;
79
+ if (typeof logoutToken !== 'string') {
80
+ throw new HTTPException(400, { message: 'Expected a logout token.' });
81
+ }
82
+ const claims = await oidcClient.verifyCoreToken(logoutToken);
83
+ const events = claims.events;
84
+ if (!events?.[BACK_CHANNEL_LOGOUT_EVENT] ||
85
+ 'nonce' in claims ||
86
+ typeof claims.sid !== 'string') {
87
+ throw new HTTPException(400, { message: 'Not a logout token.' });
88
+ }
89
+ sessionService.endCoreSession(claims.sid);
90
+ return context.body(null, 200);
91
+ });
92
+ }