@artemis-apps/app-server 0.0.0-stage → 0.1.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.
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,50 @@
1
+ import type { EnrollmentService } from '../enrollment/enrollment.service.ts';
2
+ import { type OidcClient } from '../oidc/oidc.client.ts';
3
+ import type { PlatformConfig } from '../platform.config.ts';
4
+ import type { AppSession, AppSessionRepository } from './app-session.repository.ts';
5
+ import type { AppSignInAttemptRepository } from './app-sign-in-attempt.repository.ts';
6
+ export declare const APP_SESSION_TTL_MS: number;
7
+ export declare const APP_SIGN_IN_ATTEMPT_TTL_MS: number;
8
+ export interface SessionServiceOptions {
9
+ config: PlatformConfig;
10
+ oidcClient: OidcClient;
11
+ enrollment: Pick<EnrollmentService, 'isEnrolled' | 'forget'>;
12
+ sessions: AppSessionRepository;
13
+ signInAttempts: AppSignInAttemptRepository;
14
+ }
15
+ export declare function createSessionService({ config, oidcClient, enrollment, sessions, signInAttempts, }: SessionServiceOptions): {
16
+ /** Records the attempt; the caller binds its `state` to the browser. */
17
+ startSignIn(returnPath: string): Promise<{
18
+ authorizationUrl: string;
19
+ state: string;
20
+ }>;
21
+ /**
22
+ * Returns the opaque session token to hand to the browser. Throws
23
+ * `AuthorizationDeniedError` when the account did not allow the app.
24
+ */
25
+ completeSignIn(browserState: string | undefined, callbackUrl: URL): Promise<{
26
+ token: string;
27
+ returnPath: string;
28
+ }>;
29
+ resolve(token: string | undefined): Promise<AppSession | undefined>;
30
+ /**
31
+ * The session as it is now (another request may have refreshed it since it was resolved),
32
+ * its access token valid for a while yet; `undefined` once it is gone.
33
+ */
34
+ current(session: AppSession): Promise<AppSession | undefined>;
35
+ /** Runs a request to the core as the app: `invalid_client` makes the app unenrolled. */
36
+ asClient: <Result>(request: () => Promise<Result>) => Promise<Result>;
37
+ /**
38
+ * Refreshes a session whose access token the core refused before its expiry (the core
39
+ * restarted, the grant changed). `undefined` once the session is gone.
40
+ */
41
+ renew(refused: AppSession): Promise<AppSession | undefined>;
42
+ /**
43
+ * Ends the app session, revokes its refresh token, and returns where the browser ends its
44
+ * core session (which signs it out of every app).
45
+ */
46
+ signOut(token: string | undefined): Promise<string>;
47
+ /** Back-channel logout: the core ended one of its sessions. */
48
+ endCoreSession(sid: string): void;
49
+ };
50
+ export type SessionService = ReturnType<typeof createSessionService>;
@@ -0,0 +1,137 @@
1
+ import { randomToken, sha256 } from '@artemis-apps/server-kit';
2
+ import { HTTPException } from 'hono/http-exception';
3
+ import { InvalidClientError } from '../oidc/oidc.client.js';
4
+ export const APP_SESSION_TTL_MS = 14 * 24 * 60 * 60 * 1000;
5
+ export const APP_SIGN_IN_ATTEMPT_TTL_MS = 10 * 60 * 1000;
6
+ /** Tokens are refreshed slightly before expiry so that a request never runs on a dead grant. */
7
+ const REFRESH_MARGIN_MS = 30 * 1000;
8
+ const notEnrolled = () => new HTTPException(409, { message: 'This app is not enrolled.' });
9
+ export function createSessionService({ config, oidcClient, enrollment, sessions, signInAttempts, }) {
10
+ /** One refresh per session at a time: refresh tokens rotate, a second use would be refused. */
11
+ const pendingRefreshes = new Map();
12
+ /** Runs a request to the core as the app: `invalid_client` means it was revoked. */
13
+ async function asClient(request) {
14
+ try {
15
+ return await request();
16
+ }
17
+ catch (error) {
18
+ if (!(error instanceof InvalidClientError))
19
+ throw error;
20
+ enrollment.forget();
21
+ throw notEnrolled();
22
+ }
23
+ }
24
+ async function refresh(session) {
25
+ const { refreshToken } = session;
26
+ const grant = refreshToken
27
+ ? await asClient(() => oidcClient.refresh({ ...session, refreshToken }))
28
+ : undefined;
29
+ if (!grant) {
30
+ sessions.delete(session.tokenHash);
31
+ return undefined;
32
+ }
33
+ return sessions.update(session.tokenHash, grant);
34
+ }
35
+ function refreshOnce(session) {
36
+ let pending = pendingRefreshes.get(session.tokenHash);
37
+ if (!pending) {
38
+ pending = refresh(session).finally(() => pendingRefreshes.delete(session.tokenHash));
39
+ pendingRefreshes.set(session.tokenHash, pending);
40
+ }
41
+ return pending;
42
+ }
43
+ /** A stored session, its access token refreshed when about to expire; `undefined` once gone. */
44
+ function fresh(session) {
45
+ if (!session)
46
+ return undefined;
47
+ const now = Date.now();
48
+ if (session.expiresAt.getTime() <= now) {
49
+ sessions.delete(session.tokenHash);
50
+ return undefined;
51
+ }
52
+ if (session.accessTokenExpiresAt.getTime() - REFRESH_MARGIN_MS > now) {
53
+ return Promise.resolve(session);
54
+ }
55
+ return refreshOnce(session);
56
+ }
57
+ return {
58
+ /** Records the attempt; the caller binds its `state` to the browser. */
59
+ async startSignIn(returnPath) {
60
+ if (!(await enrollment.isEnrolled()))
61
+ throw notEnrolled();
62
+ const request = await asClient(() => oidcClient.startAuthorization());
63
+ const now = Date.now();
64
+ signInAttempts.deleteExpired(new Date(now));
65
+ signInAttempts.create({
66
+ state: request.state,
67
+ codeVerifier: request.codeVerifier,
68
+ returnPath,
69
+ expiresAt: new Date(now + APP_SIGN_IN_ATTEMPT_TTL_MS),
70
+ });
71
+ return { authorizationUrl: request.authorizationUrl, state: request.state };
72
+ },
73
+ /**
74
+ * Returns the opaque session token to hand to the browser. Throws
75
+ * `AuthorizationDeniedError` when the account did not allow the app.
76
+ */
77
+ async completeSignIn(browserState, callbackUrl) {
78
+ const attempt = browserState ? signInAttempts.consume(browserState) : undefined;
79
+ if (!attempt || attempt.expiresAt.getTime() <= Date.now()) {
80
+ throw new HTTPException(400, { message: 'Unknown or expired sign-in attempt.' });
81
+ }
82
+ const grant = await asClient(() => oidcClient.completeAuthorization(callbackUrl, attempt));
83
+ const token = randomToken();
84
+ const now = new Date();
85
+ sessions.deleteExpired(now);
86
+ sessions.create({
87
+ ...grant,
88
+ tokenHash: sha256(token),
89
+ expiresAt: new Date(now.getTime() + APP_SESSION_TTL_MS),
90
+ });
91
+ return { token, returnPath: attempt.returnPath };
92
+ },
93
+ async resolve(token) {
94
+ return token ? fresh(sessions.find(sha256(token))) : undefined;
95
+ },
96
+ /**
97
+ * The session as it is now (another request may have refreshed it since it was resolved),
98
+ * its access token valid for a while yet; `undefined` once it is gone.
99
+ */
100
+ async current(session) {
101
+ return fresh(sessions.find(session.tokenHash));
102
+ },
103
+ /** Runs a request to the core as the app: `invalid_client` makes the app unenrolled. */
104
+ asClient,
105
+ /**
106
+ * Refreshes a session whose access token the core refused before its expiry (the core
107
+ * restarted, the grant changed). `undefined` once the session is gone.
108
+ */
109
+ async renew(refused) {
110
+ // Another request may have renewed it already: its refresh token is spent.
111
+ const current = sessions.find(refused.tokenHash);
112
+ if (!current || current.accessToken !== refused.accessToken)
113
+ return current;
114
+ return refreshOnce(current);
115
+ },
116
+ /**
117
+ * Ends the app session, revokes its refresh token, and returns where the browser ends its
118
+ * core session (which signs it out of every app).
119
+ */
120
+ async signOut(token) {
121
+ const session = token ? sessions.find(sha256(token)) : undefined;
122
+ if (session)
123
+ sessions.delete(session.tokenHash);
124
+ if (!(await enrollment.isEnrolled()))
125
+ return config.appUrl;
126
+ if (session?.refreshToken) {
127
+ // The end of the core session revokes it too: this only makes it immediate.
128
+ await oidcClient.revoke(session.refreshToken).catch(() => undefined);
129
+ }
130
+ return oidcClient.buildSignOutUrl(session?.idToken);
131
+ },
132
+ /** Back-channel logout: the core ended one of its sessions. */
133
+ endCoreSession(sid) {
134
+ sessions.deleteBySid(sid);
135
+ },
136
+ };
137
+ }
@@ -0,0 +1,27 @@
1
+ import { type FileVisibility, type StoredFile } from '@artemis-apps/contracts';
2
+ import type { CoreApiClient } from '../core-api/core-api.client.ts';
3
+ export interface FileUpload {
4
+ file: Blob;
5
+ visibility: FileVisibility;
6
+ }
7
+ export interface CoreStorageClientOptions {
8
+ coreUrl: string;
9
+ coreApi: Pick<CoreApiClient, 'asApp'>;
10
+ }
11
+ /** Public URL of a public file of the core storage. */
12
+ export declare function publicFileUrl(coreUrl: string, fileId: string): string;
13
+ /**
14
+ * The app's files on the core storage, managed server to server with the app's own token:
15
+ * files belong to the app, never to an account.
16
+ */
17
+ export declare function createCoreStorageClient({ coreUrl, coreApi }: CoreStorageClientOptions): {
18
+ /** Kept byte for byte: normalise pictures first (`@artemis-apps/server-kit/images`). */
19
+ upload({ file, visibility }: FileUpload): Promise<StoredFile>;
20
+ /** The file's content (any visibility), to relay after the app's own checks. */
21
+ read(fileId: string): Promise<Response>;
22
+ /** Deleting a file that is already gone succeeds. */
23
+ delete(fileId: string): Promise<void>;
24
+ /** Where anyone can display a public file. */
25
+ publicUrl(fileId: string): string;
26
+ };
27
+ export type CoreStorageClient = ReturnType<typeof createCoreStorageClient>;
@@ -0,0 +1,71 @@
1
+ import { ApiErrorBodySchema, CORE_STORAGE_PATHS, fillPath, StoredFileSchema, } from '@artemis-apps/contracts';
2
+ import { HTTPException } from 'hono/http-exception';
3
+ /** Refusals of the core that are about the file itself: the app's client sees them as they are. */
4
+ const RELAYED_STATUSES = [413, 415];
5
+ function isRelayedStatus(status) {
6
+ return RELAYED_STATUSES.includes(status);
7
+ }
8
+ /** Public URL of a public file of the core storage. */
9
+ export function publicFileUrl(coreUrl, fileId) {
10
+ return new URL(fillPath(CORE_STORAGE_PATHS.publicFile, { fileId }), coreUrl).href;
11
+ }
12
+ /**
13
+ * The app's files on the core storage, managed server to server with the app's own token:
14
+ * files belong to the app, never to an account.
15
+ */
16
+ export function createCoreStorageClient({ coreUrl, coreApi }) {
17
+ const fileUrl = (fileId) => fillPath(CORE_STORAGE_PATHS.file, { fileId });
18
+ async function refusal(response) {
19
+ const body = ApiErrorBodySchema.safeParse(await response.json().catch(() => undefined));
20
+ if (isRelayedStatus(response.status)) {
21
+ return new HTTPException(response.status, {
22
+ message: body.success ? body.data.error.message : 'The core storage refused the file.',
23
+ });
24
+ }
25
+ return new HTTPException(502, {
26
+ message: `The core storage refused the request (status ${response.status}).`,
27
+ });
28
+ }
29
+ return {
30
+ /** Kept byte for byte: normalise pictures first (`@artemis-apps/server-kit/images`). */
31
+ async upload({ file, visibility }) {
32
+ const fields = { visibility };
33
+ const form = new FormData();
34
+ form.set('file', file);
35
+ form.set('visibility', fields.visibility);
36
+ const response = await coreApi.asApp(CORE_STORAGE_PATHS.files, {
37
+ method: 'POST',
38
+ body: form,
39
+ });
40
+ if (!response.ok)
41
+ throw await refusal(response);
42
+ const parsed = StoredFileSchema.safeParse(await response.json().catch(() => undefined));
43
+ if (!parsed.success) {
44
+ throw new HTTPException(502, { message: 'The core storage did not return the file.' });
45
+ }
46
+ return parsed.data;
47
+ },
48
+ /** The file's content (any visibility), to relay after the app's own checks. */
49
+ async read(fileId) {
50
+ const response = await coreApi.asApp(fileUrl(fileId), {
51
+ method: 'GET',
52
+ headers: { accept: '*/*' },
53
+ });
54
+ if (response.status === 404)
55
+ throw new HTTPException(404, { message: 'File not found.' });
56
+ if (!response.ok)
57
+ throw await refusal(response);
58
+ return response;
59
+ },
60
+ /** Deleting a file that is already gone succeeds. */
61
+ async delete(fileId) {
62
+ const response = await coreApi.asApp(fileUrl(fileId), { method: 'DELETE' });
63
+ if (!response.ok && response.status !== 404)
64
+ throw await refusal(response);
65
+ },
66
+ /** Where anyone can display a public file. */
67
+ publicUrl(fileId) {
68
+ return publicFileUrl(coreUrl, fileId);
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,2 @@
1
+ export { createTestAppSession, type TestAppSessionOptions } from './platform-fixtures.ts';
2
+ export { createTestCore, type HandlerTokenOptions, type ProviderTokenOptions, type TestCore, type TestCoreOptions, } from './test-core.ts';
@@ -0,0 +1,3 @@
1
+ /* Test helpers for apps and for this package: never write the platform tables by hand. */
2
+ export { createTestAppSession } from './platform-fixtures.js';
3
+ export { createTestCore, } from './test-core.js';
@@ -0,0 +1,24 @@
1
+ import type { Account, DelegablePermission } from '@artemis-apps/contracts';
2
+ import type { PlatformConfig } from '../platform.config.ts';
3
+ import type { PlatformDatabase } from '../platform.tables.ts';
4
+ export interface TestAppSessionOptions {
5
+ database: PlatformDatabase;
6
+ /** The config given to `createPlatform`: the cookie name derives from it. */
7
+ config: PlatformConfig;
8
+ account: Account;
9
+ /** Permissions granted to the app for this account. */
10
+ permissions: DelegablePermission[];
11
+ /** Defaults to one hour from now. */
12
+ expiresAt?: Date;
13
+ /** Defaults to one hour from now; an earlier date makes the next request refresh the grant. */
14
+ accessTokenExpiresAt?: Date;
15
+ /** The core session it belongs to (back-channel logout). */
16
+ sid?: string;
17
+ /** The account administers the platform's apps (the app's settings). Defaults to `false`. */
18
+ administrator?: boolean;
19
+ }
20
+ /**
21
+ * Stores an app session as the OIDC callback would, and returns the `cookie` request header
22
+ * that carries it.
23
+ */
24
+ export declare function createTestAppSession({ database, config, account, permissions, expiresAt, accessTokenExpiresAt, sid, administrator, }: TestAppSessionOptions): string;
@@ -0,0 +1,25 @@
1
+ import { randomToken, sha256 } from '@artemis-apps/server-kit';
2
+ import { createAppCookies } from '../session/app.cookies.js';
3
+ import { createAppSessionRepository } from '../session/app-session.repository.js';
4
+ const TEST_SESSION_TTL_MS = 60 * 60 * 1000;
5
+ /**
6
+ * Stores an app session as the OIDC callback would, and returns the `cookie` request header
7
+ * that carries it.
8
+ */
9
+ export function createTestAppSession({ database, config, account, permissions, expiresAt = new Date(Date.now() + TEST_SESSION_TTL_MS), accessTokenExpiresAt = new Date(Date.now() + TEST_SESSION_TTL_MS), sid = 'test-sid', administrator = false, }) {
10
+ const token = randomToken();
11
+ createAppSessionRepository(database).create({
12
+ tokenHash: sha256(token),
13
+ account,
14
+ preferences: { locale: 'en' },
15
+ administrator,
16
+ permissions,
17
+ idToken: 'test-id-token',
18
+ sid,
19
+ accessToken: 'test-access-token',
20
+ refreshToken: 'test-refresh-token',
21
+ accessTokenExpiresAt,
22
+ expiresAt,
23
+ });
24
+ return `${createAppCookies({ config }).session.name}=${token}`;
25
+ }
@@ -0,0 +1,73 @@
1
+ import { type AppManifest, type EntityPointer, type SecurityEvent, type TypePermission } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ /** A provider token, as the core mints it for one call. */
4
+ export interface ProviderTokenOptions {
5
+ /** The owner of the entities: the token's `sub`. */
6
+ ownerId: string;
7
+ /** The account acting, when it isn't the owner (`act.sub`). */
8
+ actorId?: string;
9
+ /** The consumer app (`client_id`). */
10
+ appId?: string;
11
+ /** The one type permission the call needs. */
12
+ permission: TypePermission;
13
+ /** The shared entity the call stays in. */
14
+ within?: EntityPointer;
15
+ }
16
+ /** The token the core signs to call one of the app's `server` actions. */
17
+ export interface HandlerTokenOptions {
18
+ /** The account the action runs for (the owner, or the account asking): the token's `sub`. */
19
+ subject: string;
20
+ /** The app that asked the core for it (`client_id`). */
21
+ callerAppId?: string;
22
+ }
23
+ export interface TestCoreOptions {
24
+ coreUrl?: string;
25
+ /** The app under test: the audience of what this core signs. */
26
+ appId: string;
27
+ /** Whether the core accepts the app from the start. */
28
+ enrolled?: boolean;
29
+ /** More of the core (its API), served before the rest. */
30
+ routes?: Hono;
31
+ /**
32
+ * Answers a refresh token grant (its form): a token response, or `undefined` to refuse it.
33
+ * By default, every refresh is refused.
34
+ */
35
+ refresh?: (form: URLSearchParams) => Record<string, unknown> | undefined;
36
+ /**
37
+ * Answers an entity grant request (RFC 8693, its form): a token response, or `undefined` to
38
+ * refuse it (`invalid_target`). By default, every exchange is granted.
39
+ */
40
+ exchange?: (form: URLSearchParams) => Record<string, unknown> | undefined;
41
+ }
42
+ /**
43
+ * A core as an app sees it, in memory: discovery, JWKS, a token endpoint granting the app's own
44
+ * tokens and entity grants while it is enrolled, the manifest endpoint, and the tokens a core
45
+ * signs for an app (security events, provider and handler tokens, logout tokens). Give its
46
+ * `fetch` to the platform config.
47
+ */
48
+ export declare function createTestCore({ coreUrl, appId, enrolled, routes, refresh, exchange, }: TestCoreOptions): {
49
+ state: {
50
+ enrolled: boolean;
51
+ appTokens: number;
52
+ manifests: AppManifest[];
53
+ /** The authorization requests the app pushed (PAR). */
54
+ pushedRequests: URLSearchParams[];
55
+ /** The entity grant requests the app made (token exchange). */
56
+ exchanges: URLSearchParams[];
57
+ };
58
+ /** Routes requests to the core to this one; anything else is refused. */
59
+ fetch: typeof fetch;
60
+ enroll: () => void;
61
+ revoke: () => void;
62
+ /** A Security Event Token, as the core pushes it. */
63
+ securityEvent: (event: SecurityEvent, subject: string) => Promise<string>;
64
+ /** The access token the core mints to call the app as a provider. */
65
+ providerToken: ({ ownerId, actorId, appId: consumerId, permission, within, }: ProviderTokenOptions) => Promise<string>;
66
+ /** The token the core signs to call one of the app's `server` actions. */
67
+ handlerToken: ({ subject, callerAppId }: HandlerTokenOptions) => Promise<string>;
68
+ /** An OIDC back-channel logout token for the core session `sid`. */
69
+ logoutToken: (sid: string, accountId: string) => Promise<string>;
70
+ /** A token signed by another key: what an impostor would send. */
71
+ forgedSecurityEvent(event: SecurityEvent, subject: string): Promise<string>;
72
+ };
73
+ export type TestCore = ReturnType<typeof createTestCore>;
@@ -0,0 +1,134 @@
1
+ import { generateKeyPairSync, randomUUID } from 'node:crypto';
2
+ import { CORE_API_PATHS, coreIssuerUrl, ENTITY_GRANT, HANDLER_TOKEN_TYPE, PROVIDER_TOKEN_TYPE, SECURITY_EVENT_TOKEN_TYPE, } from '@artemis-apps/contracts';
3
+ import { Hono } from 'hono';
4
+ import { SignJWT } from 'jose';
5
+ /**
6
+ * A core as an app sees it, in memory: discovery, JWKS, a token endpoint granting the app's own
7
+ * tokens and entity grants while it is enrolled, the manifest endpoint, and the tokens a core
8
+ * signs for an app (security events, provider and handler tokens, logout tokens). Give its
9
+ * `fetch` to the platform config.
10
+ */
11
+ export function createTestCore({ coreUrl = 'http://localhost:4000', appId, enrolled = true, routes, refresh = () => undefined, exchange, }) {
12
+ const issuer = coreIssuerUrl(coreUrl);
13
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
14
+ const kid = randomUUID();
15
+ const publicJwk = { ...publicKey.export({ format: 'jwk' }), kid, alg: 'RS256', use: 'sig' };
16
+ const state = {
17
+ enrolled,
18
+ appTokens: 0,
19
+ manifests: [],
20
+ /** The authorization requests the app pushed (PAR). */
21
+ pushedRequests: [],
22
+ /** The entity grant requests the app made (token exchange). */
23
+ exchanges: [],
24
+ };
25
+ /** Grants every exchange: a new token, for the scope asked. */
26
+ const grantExchange = (form) => ({
27
+ access_token: `entity-grant-${state.exchanges.length}`,
28
+ issued_token_type: ENTITY_GRANT.tokenType,
29
+ token_type: 'Bearer',
30
+ expires_in: ENTITY_GRANT.ttlSeconds,
31
+ scope: form.get('scope') ?? '',
32
+ });
33
+ const sign = (type, claims, audience = appId) => new SignJWT(claims)
34
+ .setProtectedHeader({ alg: 'RS256', kid, typ: type })
35
+ .setIssuer(issuer)
36
+ .setAudience(audience)
37
+ .setIssuedAt()
38
+ .setExpirationTime('5m')
39
+ .setJti(randomUUID())
40
+ .sign(privateKey);
41
+ const core = new Hono();
42
+ if (routes)
43
+ core.route('/', routes);
44
+ core
45
+ .get('/oidc/.well-known/openid-configuration', (context) => context.json({
46
+ issuer,
47
+ authorization_endpoint: `${issuer}/auth`,
48
+ pushed_authorization_request_endpoint: `${issuer}/request`,
49
+ token_endpoint: `${issuer}/token`,
50
+ revocation_endpoint: `${issuer}/token/revocation`,
51
+ end_session_endpoint: `${issuer}/session/end`,
52
+ jwks_uri: `${issuer}/jwks`,
53
+ token_endpoint_auth_methods_supported: ['private_key_jwt'],
54
+ code_challenge_methods_supported: ['S256'],
55
+ authorization_response_iss_parameter_supported: true,
56
+ }))
57
+ .get('/oidc/jwks', (context) => context.json({ keys: [publicJwk] }))
58
+ .post('/oidc/token', async (context) => {
59
+ const form = new URLSearchParams(await context.req.text());
60
+ if (!state.enrolled)
61
+ return context.json({ error: 'invalid_client' }, 401);
62
+ if (form.get('grant_type') === 'refresh_token') {
63
+ const tokens = refresh(form);
64
+ return tokens ? context.json(tokens) : context.json({ error: 'invalid_grant' }, 400);
65
+ }
66
+ if (form.get('grant_type') === ENTITY_GRANT.grantType) {
67
+ state.exchanges.push(form);
68
+ const tokens = (exchange ?? grantExchange)(form);
69
+ return tokens ? context.json(tokens) : context.json({ error: 'invalid_target' }, 400);
70
+ }
71
+ state.appTokens += 1;
72
+ return context.json({
73
+ access_token: `app-token-${state.appTokens}`,
74
+ token_type: 'Bearer',
75
+ expires_in: 600,
76
+ });
77
+ })
78
+ .post('/oidc/request', async (context) => {
79
+ if (!state.enrolled)
80
+ return context.json({ error: 'invalid_client' }, 401);
81
+ state.pushedRequests.push(new URLSearchParams(await context.req.text()));
82
+ return context.json({ request_uri: `urn:ietf:params:oauth:request_uri:${randomUUID()}`, expires_in: 60 }, 201);
83
+ })
84
+ .post('/oidc/token/revocation', (context) => context.body(null, 200))
85
+ .put(CORE_API_PATHS.appManifest, async (context) => {
86
+ state.manifests.push((await context.req.json()));
87
+ return context.body(null, 204);
88
+ });
89
+ return {
90
+ state,
91
+ /** Routes requests to the core to this one; anything else is refused. */
92
+ fetch: (async (input, init) => {
93
+ const request = new Request(input, init);
94
+ if (!request.url.startsWith(coreUrl))
95
+ throw new Error(`Unexpected request to ${request.url}.`);
96
+ return core.fetch(request);
97
+ }),
98
+ enroll: () => {
99
+ state.enrolled = true;
100
+ },
101
+ revoke: () => {
102
+ state.enrolled = false;
103
+ },
104
+ /** A Security Event Token, as the core pushes it. */
105
+ securityEvent: (event, subject) => sign(SECURITY_EVENT_TOKEN_TYPE, { sub: subject, events: { [event]: {} } }),
106
+ /** The access token the core mints to call the app as a provider. */
107
+ providerToken: ({ ownerId, actorId, appId: consumerId = 'calendar', permission, within, }) => sign(PROVIDER_TOKEN_TYPE, {
108
+ sub: ownerId,
109
+ client_id: consumerId,
110
+ scope: permission,
111
+ ...(actorId && actorId !== ownerId ? { act: { sub: actorId } } : {}),
112
+ ...(within ? { within } : {}),
113
+ }),
114
+ /** The token the core signs to call one of the app's `server` actions. */
115
+ handlerToken: ({ subject, callerAppId = 'drive' }) => sign(HANDLER_TOKEN_TYPE, { sub: subject, client_id: callerAppId }),
116
+ /** An OIDC back-channel logout token for the core session `sid`. */
117
+ logoutToken: (sid, accountId) => sign('logout+jwt', {
118
+ sub: accountId,
119
+ sid,
120
+ events: { 'http://schemas.openid.net/event/backchannel-logout': {} },
121
+ }),
122
+ /** A token signed by another key: what an impostor would send. */
123
+ forgedSecurityEvent(event, subject) {
124
+ const { privateKey: otherKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
125
+ return new SignJWT({ sub: subject, events: { [event]: {} } })
126
+ .setProtectedHeader({ alg: 'RS256', kid, typ: SECURITY_EVENT_TOKEN_TYPE })
127
+ .setIssuer(issuer)
128
+ .setAudience(appId)
129
+ .setIssuedAt()
130
+ .setExpirationTime('5m')
131
+ .sign(otherKey);
132
+ },
133
+ };
134
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@artemis-apps/app-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "default": "./dist/index.js"
10
+ },
11
+ "./testing": {
12
+ "types": "./dist/testing/index.d.ts",
13
+ "default": "./dist/testing/index.js"
14
+ }
15
+ },
16
+ "dependencies": {
17
+ "drizzle-orm": "0.45.4",
18
+ "hono": "4.13.23",
19
+ "jose": "6.2.19",
20
+ "openid-client": "6.9.1",
21
+ "zod": "4.6.7",
22
+ "@artemis-apps/contracts": "^0.1.0",
23
+ "@artemis-apps/server-kit": "^0.1.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "26.6.11",
27
+ "typescript": "7.0.2",
28
+ "vitest": "5.1.2",
29
+ "@artemis-apps/tsconfig": "^0.1.0",
30
+ "@artemis-apps/test-kit": "^0.1.0"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/artemis-apps/sdk.git",
35
+ "directory": "packages/app-server"
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc --project tsconfig.build.json",
45
+ "typecheck": "tsc --project tsconfig.json",
46
+ "test": "vitest run"
47
+ }
6
48
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.