@permute/sdk 0.7.0 → 0.8.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/README.md CHANGED
@@ -6,6 +6,36 @@ The SDK supports Node.js 20 and newer and includes TypeScript declarations.
6
6
 
7
7
  See the [changelog](https://permute.ai/docs/changelog) for release notes and upgrade guidance.
8
8
 
9
+ ## Sign in without an API key
10
+
11
+ The CLI ships with `@permute/sdk`. Run it with `bunx`:
12
+
13
+ ```sh
14
+ bunx @permute/sdk auth login
15
+ # Or approve from another computer:
16
+ bunx @permute/sdk auth login --device-code --no-browser
17
+ bunx @permute/sdk auth status
18
+ bunx @permute/sdk auth logout
19
+ ```
20
+
21
+ Choose an organization, optionally limit the connection to one workspace, then select resources and permissions to approve in Permute. The CLI stores renewable credentials in your operating system’s credential store (no plaintext fallback). Active logins have no fixed maximum lifetime and expire after 30 days without renewal; company sign-in rules can require earlier authentication. Logging out revokes access before removing the local credential. Signing in again revokes the previous stored CLI session.
22
+
23
+ The SDK reuses credentials in memory between requests and reloads the OS store before renewal or when another process changes the saved login. The local auth directory holds only a lock and a non-secret change marker; tokens stay out of ordinary files. Current server permissions and revocation still apply to every request.
24
+
25
+ The CLI prints the issuer and `permute-cli` entry name to stderr before accessing the OS store. macOS controls its own permission dialog, which may identify the Node or Bun process. SDK applications stay silent by default and can supply `onCredentialStoreAccess: (issuer) => { /* show a notice */ }` to `OAuthLogin`; the callback runs once before the default OS store is accessed and receives no credentials.
26
+
27
+ ```ts
28
+ import { OAuthLogin } from '@permute/sdk/auth';
29
+
30
+ const client = await new OAuthLogin().client();
31
+ const workspace = client.withWorkspace('wksp_...');
32
+ const apps = await workspace.apps.list();
33
+ ```
34
+
35
+ The client renews access automatically. Existing permissions still control data, drafting, publication and action execution. Each request must fit both the approved selection and your current permissions. For organization-wide logins, use `client.withWorkspace(id)` for workspace API calls. Local stdio MCP can reuse this saved login when no API key is configured. Hosted app and hosted MCP credentials stay bound to their own audiences. API-key clients continue to work with `new PermuteClient({ apiKey })`.
36
+
37
+ For a development environment, pass both `--issuer https://auth.example.test` and `--api-url https://api.example.test` to CLI commands, or the matching `issuer` and `apiUrl` to `OAuthLogin`. Only HTTPS origins and local loopback HTTP are accepted. Use the same environment for login and logout.
38
+
9
39
  ## Dashboard source authoring
10
40
 
11
41
  API-key clients with dashboard write access can read and replace the complete
@@ -96,10 +126,12 @@ replacement without checking the changes. Graph commands use `get`’s numeric f
96
126
  Publishing requires a successful run of the current flow version. Deleting a flow
97
127
  requires admin access; its owned operations are deleted with it.
98
128
 
99
- Data Flow and operation authoring are REST/SDK only. MCP serves end users reading
100
- and analyzing governed outputs; it does not expose code editing, draft inspection,
101
- execution, or publication. Hosted connectors also restrict access to selected sources. Flow scheduling and standalone operation
102
- creation are not part of this surface.
129
+ Data Flow and operation authoring are REST/SDK only. MCP does not expose their code
130
+ editing, draft inspection, execution, or publication. Hosted MCP access uses
131
+ selected sources or a hosted app's current grants and published action bindings,
132
+ intersected with the user's permissions. App actions require confirmation in
133
+ Permute; see the [MCP guide](https://permute.ai/docs/mcp). Flow scheduling and
134
+ standalone operation creation are not part of this surface.
103
135
 
104
136
  ## Publish write syncs
105
137
 
@@ -379,6 +411,14 @@ query (materialized connector fields come from the stored SQL table). Warehouse
379
411
  sources use DuckDB SQL and can be queried together. Live remote sources use
380
412
  their native SQL dialect and must be queried one at a time.
381
413
 
414
+ Warehouse SQL queries accept up to **20 distinct sources per query**. The shared
415
+ [`WAREHOUSE_QUERY_SOURCE_LIMIT`](../core/src/constants/queryLimits.ts) keeps the
416
+ SQL executor, natural-language query sessions, and UI source picker consistent.
417
+ This cap bounds the number of sources prepared for a query (each source can
418
+ contain many tables); it does not limit workspace connections or change access
419
+ permissions. Select only the sources needed. Requests above the cap are rejected
420
+ before source loading.
421
+
382
422
  ```ts
383
423
  const dataset = sources.items.find((source) => source.type === 'dataset');
384
424
  if (!dataset) throw new Error('No dataset is available');
@@ -424,6 +464,14 @@ handling).
424
464
 
425
465
  ## Error Handling
426
466
 
467
+ App and Business Action authorization failures can return `permission_denied` with
468
+ `error.details` containing `operation`, `requiredLevel` (`read`, `write`, or `admin`),
469
+ and `reason`. Reasons are `caller_permission_required`, `application_grant_required`,
470
+ `source_delegation_required`, or `declared_capability_required`. Both SDK entries
471
+ preserve these fields on `PermuteApiError.details`. Details are optional: unreadable,
472
+ missing, and foreign resources return the same opaque 404, so a caller cannot use
473
+ denials to discover private resources. See [authentication](https://permute.ai/docs/authentication#authorization-errors).
474
+
427
475
  ```ts
428
476
  import { PermuteApiError } from '@permute/sdk';
429
477
 
@@ -589,14 +637,21 @@ directly; invoking any bound action requires viewer confirmation.
589
637
 
590
638
  Source reads require whole-resource read permission for both the app and viewer,
591
639
  including databases, datasets, connectors, and operation outputs. Table, row,
592
- and column grants are unsupported; subResourceId is available only to revoke an
593
- existing scoped grant. Test source discovery and
594
- a bounded query as the intended viewer before testing the assistant; an empty
640
+ and column grants within a shared source are unsupported; subResourceId is available
641
+ only to revoke an existing scoped grant. Role-based reads can use separate filtered
642
+ Data Table or Data Flow outputs shared with the appropriate viewers and apps while
643
+ broader upstream sources stay restricted. Follow the
644
+ [filtered-output guide](https://permute.ai/docs/guides/deploy-app#app-filtered-views)
645
+ for allowed rows/columns, historical access, and refresh after assignment changes.
646
+ Test source discovery and a bounded query as the intended viewer before testing the assistant; an empty
595
647
  source list describes that viewer's app access, not the workspace's contents.
596
648
 
597
649
  Plan app and viewer permissions separately. Use `client.apps.setGrant()` for exact
598
650
  approved app source IDs; an administrator uses Permute sharing for viewer app and
599
- source access. The public SDK has no general user-permission mutation methods.
651
+ source access. Authorized management clients can also use `client.permissions.list`,
652
+ `create`, `update`, `delete`, and `inspect`; hosted app, delegated action, MCP, and
653
+ connector sessions cannot manage grants. The management key needs its own access
654
+ and delegation authority.
600
655
  Inspect the complete source before approval (a database may contain other apps’
601
656
  tables); never widen a rejected table grant automatically. Apps and keys do not
602
657
  inherit their creators’ access. The public
@@ -664,6 +719,15 @@ operation only after resolving any earlier uncertain write.
664
719
 
665
720
  ## Business actions
666
721
 
722
+ Handlers can read declared managed database tables with
723
+ `db.read({ sourceId, table, where, limit })`. Use trusted `caller: { id, type }`
724
+ to choose permitted rows, return only approved fields, and grant invocation access
725
+ without granting database Read. Declare the published schema revision and
726
+ `readTables` in the action's source binding (`writeTables: []` for read-only use).
727
+ Caller identity does not include membership roles; application-specific team rules
728
+ can use a server-side roster. See the
729
+ [caller-filtered database read example](https://permute.ai/docs/guides/business-actions#action-database-reads).
730
+
667
731
  Action handlers can receive a declared `platform` SDK facade. Add `platform.methods`
668
732
  and `platform.permissions` to the definition, then call
669
733
  `platform.withStep('upload').datasets.create({ type: 'file', fileName: input.fileName, contentType: input.contentType, sizeBytes: input.sizeBytes })`.
@@ -671,8 +735,9 @@ Without `data`, the call returns dataset metadata and an upload target; the hand
671
735
  can return that target for the browser to upload bytes. Providing `data` also
672
736
  uploads bytes inside the action and must fit its execution and payload limits.
673
737
  The server runs the real SDK using the action's delegated grants (callers need
674
- only action invocation permission). Saving and publishing require resource admin
675
- authority. Every SDK call needs a distinct, deterministic step ID, including reads.
738
+ only action invocation permission). Saving requires Edit draft on the action and
739
+ Read on declared resources; publishing requires Publish and resource Admin to
740
+ delegate those capabilities. Every SDK call needs a distinct, deterministic step ID, including reads.
676
741
  Completed calls replay their saved results; reusing an ID with a different method
677
742
  or arguments returns `request_conflict`. Calls with uncertain outcomes return
678
743
  `outcome_unknown` and block automatic resend. Earlier SDK effects aren't rolled
@@ -681,14 +746,63 @@ Calls share action time and payload limits; dataset helpers return plain data.
681
746
  See the [business-actions guide](https://permute.ai/docs/guides/business-actions)
682
747
  for supported methods, limits, and authoring examples.
683
748
 
749
+ For hosted browser uploads, send file metadata through the bound action and return
750
+ `{ datasetId: dataset.id, upload: dataset.upload }` in its declared output contract.
751
+ Send the `File` as the raw body of `fetch(upload.url, { method: upload.method,
752
+ headers: upload.headers, body: file, credentials: 'omit', redirect: 'error' })`.
753
+ Keep every returned header (including `If-None-Match: *`); don't wrap bytes in
754
+ `FormData` or send cookies or API keys to S3. File bytes bypass the action's
755
+ 100 KB input limit. Compiled signed-in apps permit connections to the stage's exact
756
+ regional Datasets bucket; its CORS rule supports PUT and the returned headers,
757
+ including from custom app domains.
758
+
759
+ S3 object-created events start normal dataset processing. Use a separately bound
760
+ status action declaring `datasets.get` to poll with a new invocation request ID
761
+ for each fresh read; enforce any caller-specific ownership rules in that action.
762
+ Hosted app sessions cannot call dataset APIs directly. Upload URLs are bearer
763
+ capabilities valid for up to 15 minutes (temporary AWS credentials can expire
764
+ earlier), so don't persist or log them. Replaying the create action returns the
765
+ original target without renewing its expiry. After an uncertain PUT, inspect
766
+ processing status before requesting another dataset; a 412 means an object
767
+ already occupies the signed key.
768
+
684
769
  Use `client.actions.create`, `definition`, and `saveDefinition` to author a typed
685
770
  handler with declared database, connector, or SDK capabilities. SDK-only and
686
771
  connector-only actions need no managed database. Publish with
687
772
  `client.revisions.publish`, then call `client.actions.invoke` with a stable
688
- `requestId` and input. `list` exposes published contracts; reading definitions
689
- requires admin permission. See the [business action guide](https://permute.ai/docs/guides/business-actions)
773
+ `requestId` and input. `list` and `get` expose published contracts and declared capabilities; reading definitions
774
+ requires View code permission. See the [business action guide](https://permute.ai/docs/guides/business-actions)
690
775
  for the complete create, save, publish, and invoke workflow.
691
776
 
777
+ ### Self-describing action contracts
778
+
779
+ Use input/output schema descriptions to explain purpose, business terms,
780
+ relationships, create/update behavior, consequential effects, and result meaning
781
+ (external callers cannot inspect the handler). Declare known fields, enums,
782
+ required/optional and nullable values, bounds, and typed outputs structurally.
783
+ Keep field descriptions beside their fields and operation descriptions beside
784
+ their alternatives. Reuse schema definitions for published contracts and handler
785
+ validation where practical.
786
+
787
+ Bounded `oneOf` alternatives support operation-specific inputs: give each
788
+ alternative a required selector with a distinct `const` value. Exactly one must
789
+ match. Limits are 32 alternatives per `oneOf`, 500 schema nodes, and depth 12.
790
+ Regexes, references, formats, and other composition keywords remain unsupported.
791
+ Keep authorization, normalization, formats, and live business-state checks in the handler.
792
+
793
+ Supply input/output and field `examples`; save and publication validate them
794
+ without executing the handler. Limits are 10 values per examples array and 50
795
+ examples per input/output contract. Defaults are descriptive and are not inserted.
796
+ Test the handler against examples, rejections, and conflicts as well: structural
797
+ validation cannot guarantee a later write succeeds.
798
+
799
+ `client.actions.list()` and `get()` return the current published contract, or
800
+ `contract: null` before publication. App MCP discovery retains its app's permitted
801
+ action bindings and exact revision pins. Draft changes do not update those views.
802
+ Declared capabilities are bounds, not a preview of affected records. See the
803
+ [contract-authoring guide](https://permute.ai/docs/guides/business-actions#action-contracts)
804
+ for a complete schema example.
805
+
692
806
  Permute authenticates callers and checks the action’s required invocation
693
807
  permission. Hosted app calls also require app access, an app invocation grant,
694
808
  and the action revision pinned in the served release. Administrators approve
@@ -729,6 +843,10 @@ values up to 500). Invalid rejections and unexpected exceptions return a safe
729
843
  `execution_failed` response; exception text stays in server logs.
730
844
 
731
845
  Both SDK entries expose `PermuteApiError.code`, `.status`, and `.details`.
846
+ Schema validation details include `path`, `rule`, and `schemaPath`, with bounded
847
+ `allowedValues` or `constraint` where available. Compound errors can include
848
+ `issues`; truncation flags indicate omitted diagnostics. Hosted MCP retains the
849
+ same public error code and details in its error result.
732
850
  Branch on the code (not message text):
733
851
 
734
852
  | Code | HTTP | Recovery |
@@ -749,7 +867,9 @@ does not establish that nothing happened; reconcile provider state first.
749
867
  ### Connector bindings
750
868
 
751
869
  An action definition can bind multiple connector accounts by name alongside its database
752
- schema bindings. Save and publish require admin permission on each selected resource.
870
+ schema bindings. Saving requires Edit draft on the action and Read on each selected
871
+ resource; publishing requires Publish on the action and source Admin to delegate
872
+ the capabilities.
753
873
  The action runs with those delegated capabilities; callers need its invocation permission.
754
874
 
755
875
  ```ts
@@ -836,3 +956,13 @@ await client.apps.setAddress(app.id, {
836
956
  ```
837
957
 
838
958
  Set `address: null` with the currently observed URL to remove it. Stale edits and occupied names return 409. Each hostname uses its own app session; permissions and password-demo restrictions apply on every address. Namespace ownership management is restricted to signed-in organization admins, while these app-level methods support API keys with app admin permission.
959
+
960
+ ## Request missing access
961
+
962
+ Use `client.accessRequests.create({ resourceId, level: 'read', reason: 'Need this app for customer support' })` to record a request for the authenticated caller. Recording a request does not grant access or confirm that the resource exists. List your requests with `client.accessRequests.list()`.
963
+
964
+ Reviewers use `client.accessRequests.list({ view: 'review', state: 'pending' })`, then `client.accessRequests.decide(requestId, { decision: 'approved' })` to grant the requested caller access, verify effective access and close the request atomically. Approval never expands app grants (missing app access must be handled separately). Use `resolved` only to verify access already granted. Requesters can cancel with `{ decision: 'cancelled' }` (reviewers can reject with `{ decision: 'rejected' }`).
965
+
966
+ Lists include a `total` count under the same authorization and filters as their rows. Use `{ view: 'mine', state: 'pending' }` for your pending requests and `{ view: 'history' }` for completed or expired requests you own or currently administer. Resource administrators can list across their authorized resources or narrow with `resourceId`. Expiry and visibility filters apply before cursor pagination.
967
+
968
+ Hosted apps use `app.accessRequests.create/list/get/cancel`; the server derives app scope from the signed session. See the [access-request contract](../core/src/permissions/README.md) for expiry, reviewer authority and current limits.
package/dist/app.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { AccessRequest, AccessRequestInput, AccessRequestList } from './types.js';
2
+ export type { AccessRequest, AccessRequestInput, AccessRequestList } from './types.js';
1
3
  import type { ActionRequest, ActionReceipt, QueryRequest, QueryResponse, AppUser, ChatSendRequest, ChatDecisionRequest, ChatResponse, SourceList, SourceDetail } from './types.js';
2
4
  export { PermuteApiError } from './errors.js';
3
5
  export type { ActionRequest, ActionReceipt, QueryRequest, QueryResponse, AppUser, ChatSendRequest, ChatDecisionRequest, ChatResponse, SourceList, SourceDetail, } from './types.js';
@@ -15,6 +17,12 @@ export declare class PermuteAppClient {
15
17
  private readonly revisionId;
16
18
  private readonly fetcher;
17
19
  constructor(options?: PermuteAppClientOptions);
20
+ readonly accessRequests: {
21
+ create: (body: AccessRequestInput, options?: AppRequestOptions) => Promise<AccessRequest>;
22
+ list: (cursor?: string, options?: AppRequestOptions) => Promise<AccessRequestList>;
23
+ get: (requestId: string, options?: AppRequestOptions) => Promise<AccessRequest>;
24
+ cancel: (requestId: string, options?: AppRequestOptions) => Promise<AccessRequest>;
25
+ };
18
26
  readonly actions: {
19
27
  /** Keep requestId and input unchanged when retrying an uncertain result. */
20
28
  invoke: (actionId: string, request: ActionRequest, options?: AppRequestOptions) => Promise<ActionReceipt>;
package/dist/app.js CHANGED
@@ -19,6 +19,12 @@ export class PermuteAppClient {
19
19
  this.revisionId = revision[1];
20
20
  this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
21
21
  }
22
+ accessRequests = {
23
+ create: (body, options) => this.request('access-requests', body, options),
24
+ list: (cursor, options) => this.request(`access-requests${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`, undefined, options),
25
+ get: (requestId, options) => this.request(`access-requests/${encodeURIComponent(requestId)}`, undefined, options),
26
+ cancel: (requestId, options) => this.request(`access-requests/${encodeURIComponent(requestId)}/decisions`, { decision: 'cancelled' }, options),
27
+ };
22
28
  actions = {
23
29
  /** Keep requestId and input unchanged when retrying an uncertain result. */
24
30
  invoke: (actionId, request, options) => this.request(`actions/${encodeURIComponent(actionId)}/invoke`, request, options),
@@ -0,0 +1,66 @@
1
+ import { PermuteClient } from '../client.js';
2
+ import { type CredentialStore, type LoginCredentials } from './store.js';
3
+ export { SystemCredentialStore, type CredentialStore, type LoginCredentials } from './store.js';
4
+ export declare const DEFAULT_ISSUER = "https://auth.permute.ai";
5
+ export declare const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
6
+ export interface OAuthOptions {
7
+ issuer?: string;
8
+ apiUrl?: string;
9
+ store?: CredentialStore;
10
+ fetch?: typeof fetch;
11
+ /** Called once before the default OS credential store is accessed; no tokens are passed. */
12
+ onCredentialStoreAccess?: (issuer: string) => void;
13
+ }
14
+ export declare class OAuthLogin {
15
+ readonly issuer: string;
16
+ readonly apiUrl: string;
17
+ private readonly store;
18
+ private readonly fetchImpl;
19
+ constructor(options?: OAuthOptions);
20
+ private endpoint;
21
+ private post;
22
+ private tokens;
23
+ private persist;
24
+ beginDevice(): Promise<{
25
+ deviceCode: string;
26
+ userCode: string;
27
+ url: string;
28
+ expiresIn: number;
29
+ expiresAt: number;
30
+ interval: number;
31
+ }>;
32
+ finishDevice(request: Awaited<ReturnType<OAuthLogin['beginDevice']>>, signal?: AbortSignal): Promise<{
33
+ issuer: string;
34
+ apiUrl: string;
35
+ workspaceId: string | undefined;
36
+ organizationId: string;
37
+ sessionId: string;
38
+ access: string;
39
+ refresh: string;
40
+ expiresAt: number;
41
+ }>;
42
+ beginBrowser(redirectURI: string): {
43
+ url: string;
44
+ verifier: string;
45
+ state: string;
46
+ redirectURI: string;
47
+ };
48
+ finishBrowser(request: ReturnType<OAuthLogin['beginBrowser']>, callback: URL): Promise<{
49
+ issuer: string;
50
+ apiUrl: string;
51
+ workspaceId: string | undefined;
52
+ organizationId: string;
53
+ sessionId: string;
54
+ access: string;
55
+ refresh: string;
56
+ expiresAt: number;
57
+ }>;
58
+ credentials(): Promise<LoginCredentials>;
59
+ client(): Promise<PermuteClient>;
60
+ logout(): Promise<void>;
61
+ private revoke;
62
+ }
63
+ export declare class OAuthLoginError extends Error {
64
+ readonly code: string;
65
+ constructor(code: string);
66
+ }
@@ -0,0 +1,221 @@
1
+ import { z } from 'zod';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import { setTimeout } from 'node:timers/promises';
4
+ import { PermuteClient } from '../client.js';
5
+ import { TOKEN_REFRESH_BUFFER_MS, SystemCredentialStore, } from './store.js';
6
+ export { SystemCredentialStore } from './store.js';
7
+ export const DEFAULT_ISSUER = 'https://auth.permute.ai';
8
+ const CLIENT_ID = 'permute-cli';
9
+ export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
10
+ const TokensSchema = z.object({
11
+ access_token: z.string().min(1),
12
+ refresh_token: z.string().min(1),
13
+ expires_in: z.number().int().positive(),
14
+ workspace_id: z.string().min(1).optional(),
15
+ organization_id: z.string().min(1),
16
+ session_id: z.string().min(1),
17
+ });
18
+ const DeviceSchema = z.object({
19
+ device_code: z.string().min(1),
20
+ user_code: z.string().min(1),
21
+ verification_uri_complete: z.string().url(),
22
+ expires_in: z.number().int().positive(),
23
+ interval: z.number().int().min(5),
24
+ });
25
+ export class OAuthLogin {
26
+ issuer;
27
+ apiUrl;
28
+ store;
29
+ fetchImpl;
30
+ constructor(options = {}) {
31
+ this.issuer = this.endpoint(options.issuer ?? DEFAULT_ISSUER);
32
+ this.apiUrl = this.endpoint(options.apiUrl ?? 'https://api.permute.ai');
33
+ this.store = options.store ?? new SystemCredentialStore(this.issuer, options.onCredentialStoreAccess);
34
+ this.fetchImpl = options.fetch ?? fetch;
35
+ }
36
+ endpoint(value) {
37
+ const url = new URL(value);
38
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname))) ||
39
+ url.username ||
40
+ url.password ||
41
+ url.search ||
42
+ url.hash ||
43
+ url.pathname !== '/')
44
+ throw new Error('Use an HTTPS origin (or loopback for local development).');
45
+ return url.origin;
46
+ }
47
+ async post(path, input) {
48
+ const response = await this.fetchImpl(`${this.issuer}${path}`, {
49
+ method: 'POST',
50
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
51
+ body: new URLSearchParams(input),
52
+ signal: AbortSignal.timeout(15_000),
53
+ redirect: 'error',
54
+ });
55
+ const result = await response.json();
56
+ if (!response.ok) {
57
+ const error = z.object({ error: z.string().max(100) }).safeParse(result);
58
+ throw new OAuthLoginError(error.success ? error.data.error : 'login_failed');
59
+ }
60
+ return result;
61
+ }
62
+ tokens(value) {
63
+ const parsed = TokensSchema.safeParse(value);
64
+ if (!parsed.success)
65
+ throw new Error('Invalid credential response');
66
+ return parsed.data;
67
+ }
68
+ async persist(tokens, previous) {
69
+ const credentials = {
70
+ issuer: this.issuer,
71
+ apiUrl: this.apiUrl,
72
+ workspaceId: tokens.workspace_id,
73
+ organizationId: tokens.organization_id,
74
+ sessionId: tokens.session_id,
75
+ access: tokens.access_token,
76
+ refresh: tokens.refresh_token,
77
+ expiresAt: Date.now() + tokens.expires_in * 1000,
78
+ };
79
+ try {
80
+ const existing = previous ?? (await this.store.read());
81
+ if (existing && existing.sessionId !== tokens.session_id)
82
+ await this.revoke(existing.refresh);
83
+ await this.store.write(credentials);
84
+ }
85
+ catch (error) {
86
+ // Failed replacement or secure storage must not orphan the new credential.
87
+ await this.revoke(tokens.refresh_token);
88
+ throw error;
89
+ }
90
+ return credentials;
91
+ }
92
+ async beginDevice() {
93
+ const parsed = DeviceSchema.safeParse(await this.post('/cli/device/authorization', { client_id: CLIENT_ID, scope: 'workspace' }));
94
+ if (!parsed.success)
95
+ throw new Error('Invalid device login response');
96
+ const result = parsed.data;
97
+ return {
98
+ deviceCode: result.device_code,
99
+ userCode: result.user_code,
100
+ url: result.verification_uri_complete,
101
+ expiresIn: result.expires_in,
102
+ expiresAt: Date.now() + result.expires_in * 1000,
103
+ interval: result.interval,
104
+ };
105
+ }
106
+ async finishDevice(request, signal) {
107
+ const deadline = request.expiresAt;
108
+ let interval = request.interval;
109
+ while (Date.now() < deadline) {
110
+ await setTimeout(interval * 1000, undefined, { signal });
111
+ try {
112
+ return await this.store.exclusive(async () => {
113
+ const tokens = this.tokens(await this.post('/token', {
114
+ client_id: CLIENT_ID,
115
+ grant_type: DEVICE_GRANT,
116
+ device_code: request.deviceCode,
117
+ }));
118
+ return this.persist(tokens);
119
+ });
120
+ }
121
+ catch (error) {
122
+ if (!(error instanceof OAuthLoginError))
123
+ throw error;
124
+ if (error.code === 'authorization_pending')
125
+ continue;
126
+ if (error.code === 'slow_down') {
127
+ interval += 5;
128
+ continue;
129
+ }
130
+ throw error;
131
+ }
132
+ }
133
+ throw new OAuthLoginError('expired_token');
134
+ }
135
+ beginBrowser(redirectURI) {
136
+ const verifier = randomBytes(32).toString('base64url');
137
+ const state = randomBytes(32).toString('base64url');
138
+ const url = new URL(`${this.issuer}/authorize`);
139
+ url.search = new URLSearchParams({
140
+ client_id: CLIENT_ID,
141
+ scope: 'workspace',
142
+ response_type: 'code',
143
+ redirect_uri: redirectURI,
144
+ state,
145
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
146
+ code_challenge_method: 'S256',
147
+ }).toString();
148
+ return { url: url.toString(), verifier, state, redirectURI };
149
+ }
150
+ async finishBrowser(request, callback) {
151
+ if (callback.origin + callback.pathname !== request.redirectURI ||
152
+ callback.searchParams.get('state') !== request.state)
153
+ throw new Error('Login callback did not match this request');
154
+ if (callback.searchParams.has('error'))
155
+ throw new OAuthLoginError('access_denied');
156
+ const code = callback.searchParams.get('code');
157
+ if (!code)
158
+ throw new Error('Login callback has no authorization code');
159
+ return this.store.exclusive(async () => {
160
+ const tokens = this.tokens(await this.post('/token', {
161
+ client_id: CLIENT_ID,
162
+ grant_type: 'authorization_code',
163
+ redirect_uri: request.redirectURI,
164
+ code_verifier: request.verifier,
165
+ code,
166
+ }));
167
+ return this.persist(tokens);
168
+ });
169
+ }
170
+ async credentials() {
171
+ return this.store.exclusive(async () => {
172
+ const current = await this.store.read();
173
+ if (!current || current.apiUrl !== this.apiUrl)
174
+ throw new Error('No login for this server. Run permute auth login.');
175
+ if (current.expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS)
176
+ return current;
177
+ const tokens = this.tokens(await this.post('/token', {
178
+ client_id: CLIENT_ID,
179
+ grant_type: 'refresh_token',
180
+ refresh_token: current.refresh,
181
+ }));
182
+ return this.persist(tokens, current);
183
+ });
184
+ }
185
+ async client() {
186
+ const credentials = await this.credentials();
187
+ return new PermuteClient({
188
+ baseUrl: this.apiUrl,
189
+ fetch: this.fetchImpl,
190
+ workspaceId: credentials.workspaceId,
191
+ accessToken: async () => (await this.credentials()).access,
192
+ });
193
+ }
194
+ async logout() {
195
+ await this.store.exclusive(async () => {
196
+ const current = await this.store.read();
197
+ if (!current)
198
+ return;
199
+ // Keep the local record on failure so revocation can be retried.
200
+ await this.revoke(current.refresh);
201
+ await this.store.remove();
202
+ });
203
+ }
204
+ async revoke(refresh) {
205
+ const response = await this.fetchImpl(`${this.issuer}/revoke`, {
206
+ method: 'POST',
207
+ body: new URLSearchParams({ client_id: CLIENT_ID, token: refresh }),
208
+ signal: AbortSignal.timeout(15_000),
209
+ redirect: 'error',
210
+ });
211
+ if (!response.ok)
212
+ throw new Error('Could not revoke login. Retry logout when connected.');
213
+ }
214
+ }
215
+ export class OAuthLoginError extends Error {
216
+ code;
217
+ constructor(code) {
218
+ super(`Login failed (${code}). Run permute auth login to try again.`);
219
+ this.code = code;
220
+ }
221
+ }
@@ -0,0 +1,47 @@
1
+ import { z } from 'zod';
2
+ export declare const TOKEN_REFRESH_BUFFER_MS = 60000;
3
+ declare const LoginCredentialsSchema: z.ZodObject<{
4
+ issuer: z.ZodString;
5
+ apiUrl: z.ZodString;
6
+ workspaceId: z.ZodOptional<z.ZodString>;
7
+ organizationId: z.ZodOptional<z.ZodString>;
8
+ sessionId: z.ZodString;
9
+ access: z.ZodString;
10
+ refresh: z.ZodString;
11
+ expiresAt: z.ZodNumber;
12
+ }, z.core.$strip>;
13
+ export type LoginCredentials = z.infer<typeof LoginCredentialsSchema>;
14
+ export interface CredentialStore {
15
+ read(): Promise<LoginCredentials | null>;
16
+ write(value: LoginCredentials): Promise<void>;
17
+ remove(): Promise<void>;
18
+ exclusive<T>(run: () => Promise<T>): Promise<T>;
19
+ }
20
+ /** Credentials are cached in memory only; disk holds a lock and a non-secret change marker. */
21
+ export declare class SystemCredentialStore implements CredentialStore {
22
+ private readonly issuer;
23
+ private readonly onAccess?;
24
+ private readonly account;
25
+ private readonly directory;
26
+ private readonly revisionPath;
27
+ private cached?;
28
+ private announced;
29
+ constructor(issuer: string, onAccess?: ((issuer: string) => void) | undefined);
30
+ private entry;
31
+ read(): Promise<{
32
+ issuer: string;
33
+ apiUrl: string;
34
+ workspaceId?: string | undefined;
35
+ organizationId?: string | undefined;
36
+ sessionId: string;
37
+ access: string;
38
+ refresh: string;
39
+ expiresAt: number;
40
+ } | null>;
41
+ private validate;
42
+ write(value: LoginCredentials): Promise<void>;
43
+ remove(): Promise<void>;
44
+ private markChanged;
45
+ exclusive<T>(run: () => Promise<T>): Promise<T>;
46
+ }
47
+ export {};